code
stringlengths 38
801k
| repo_path
stringlengths 6
263
|
---|---|
pub const _MM_HINT_T0 = @as(u32, 1);
pub const _MM_HINT_T1 = @as(u32, 2);
pub const _MM_HINT_T2 = @as(u32, 3);
pub const _MM_HINT_NTA = @as(u32, 0);
pub const IOCTL_STORAGE_BASE = @as(u32, 45);
pub const IOCTL_SCMBUS_BASE = @as(u32, 89);
pub const IOCTL_DISK_BASE = @as(u32, 7);
pub const IOCTL_CHANGER_BASE = @as(u32, 48);
pub const FILE_SPECIAL_ACCESS = @as(u32, 0);
pub const ANYSIZE_ARRAY = @as(u32, 1);
pub const MEMORY_ALLOCATION_ALIGNMENT = @as(u32, 16);
pub const SYSTEM_CACHE_ALIGNMENT_SIZE = @as(u32, 64);
pub const PRAGMA_DEPRECATED_DDK = @as(u32, 1);
pub const UCSCHAR_INVALID_CHARACTER = @as(u32, 4294967295);
pub const MIN_UCSCHAR = @as(u32, 0);
pub const MAX_UCSCHAR = @as(u32, 1114111);
pub const ALL_PROCESSOR_GROUPS = @as(u32, 65535);
pub const MAXIMUM_PROC_PER_GROUP = @as(u32, 64);
pub const APPLICATION_ERROR_MASK = @as(u32, 536870912);
pub const ERROR_SEVERITY_SUCCESS = @as(u32, 0);
pub const ERROR_SEVERITY_INFORMATIONAL = @as(u32, 1073741824);
pub const ERROR_SEVERITY_WARNING = @as(u32, 2147483648);
pub const ERROR_SEVERITY_ERROR = @as(u32, 3221225472);
pub const MAXLONGLONG = @as(u64, 9223372036854775807);
pub const UNICODE_STRING_MAX_CHARS = @as(u32, 32767);
pub const MINCHAR = @as(u32, 128);
pub const MAXCHAR = @as(u32, 127);
pub const MINSHORT = @as(u32, 32768);
pub const MAXSHORT = @as(u32, 32767);
pub const MINLONG = @as(u32, 2147483648);
pub const MAXLONG = @as(u32, 2147483647);
pub const MAXBYTE = @as(u32, 255);
pub const MAXWORD = @as(u32, 65535);
pub const MAXDWORD = @as(u32, 4294967295);
pub const ENCLAVE_SHORT_ID_LENGTH = @as(u32, 16);
pub const ENCLAVE_LONG_ID_LENGTH = @as(u32, 32);
pub const VER_SERVER_NT = @as(u32, 2147483648);
pub const VER_WORKSTATION_NT = @as(u32, 1073741824);
pub const VER_SUITE_SMALLBUSINESS = @as(u32, 1);
pub const VER_SUITE_ENTERPRISE = @as(u32, 2);
pub const VER_SUITE_BACKOFFICE = @as(u32, 4);
pub const VER_SUITE_COMMUNICATIONS = @as(u32, 8);
pub const VER_SUITE_TERMINAL = @as(u32, 16);
pub const VER_SUITE_SMALLBUSINESS_RESTRICTED = @as(u32, 32);
pub const VER_SUITE_EMBEDDEDNT = @as(u32, 64);
pub const VER_SUITE_DATACENTER = @as(u32, 128);
pub const VER_SUITE_SINGLEUSERTS = @as(u32, 256);
pub const VER_SUITE_PERSONAL = @as(u32, 512);
pub const VER_SUITE_BLADE = @as(u32, 1024);
pub const VER_SUITE_EMBEDDED_RESTRICTED = @as(u32, 2048);
pub const VER_SUITE_SECURITY_APPLIANCE = @as(u32, 4096);
pub const VER_SUITE_STORAGE_SERVER = @as(u32, 8192);
pub const VER_SUITE_COMPUTE_SERVER = @as(u32, 16384);
pub const VER_SUITE_WH_SERVER = @as(u32, 32768);
pub const VER_SUITE_MULTIUSERTS = @as(u32, 131072);
pub const PRODUCT_STANDARD_SERVER_CORE = @as(u32, 13);
pub const PRODUCT_SOLUTION_EMBEDDEDSERVER_CORE = @as(u32, 57);
pub const PRODUCT_PROFESSIONAL_EMBEDDED = @as(u32, 58);
pub const PRODUCT_EMBEDDED = @as(u32, 65);
pub const PRODUCT_EMBEDDED_AUTOMOTIVE = @as(u32, 85);
pub const PRODUCT_EMBEDDED_INDUSTRY_A = @as(u32, 86);
pub const PRODUCT_THINPC = @as(u32, 87);
pub const PRODUCT_EMBEDDED_A = @as(u32, 88);
pub const PRODUCT_EMBEDDED_INDUSTRY = @as(u32, 89);
pub const PRODUCT_EMBEDDED_E = @as(u32, 90);
pub const PRODUCT_EMBEDDED_INDUSTRY_E = @as(u32, 91);
pub const PRODUCT_EMBEDDED_INDUSTRY_A_E = @as(u32, 92);
pub const PRODUCT_CORE_ARM = @as(u32, 97);
pub const PRODUCT_EMBEDDED_INDUSTRY_EVAL = @as(u32, 105);
pub const PRODUCT_EMBEDDED_INDUSTRY_E_EVAL = @as(u32, 106);
pub const PRODUCT_EMBEDDED_EVAL = @as(u32, 107);
pub const PRODUCT_EMBEDDED_E_EVAL = @as(u32, 108);
pub const PRODUCT_NANO_SERVER = @as(u32, 109);
pub const PRODUCT_CLOUD_STORAGE_SERVER = @as(u32, 110);
pub const PRODUCT_CORE_CONNECTED = @as(u32, 111);
pub const PRODUCT_PROFESSIONAL_STUDENT = @as(u32, 112);
pub const PRODUCT_CORE_CONNECTED_N = @as(u32, 113);
pub const PRODUCT_PROFESSIONAL_STUDENT_N = @as(u32, 114);
pub const PRODUCT_CORE_CONNECTED_SINGLELANGUAGE = @as(u32, 115);
pub const PRODUCT_CORE_CONNECTED_COUNTRYSPECIFIC = @as(u32, 116);
pub const PRODUCT_CONNECTED_CAR = @as(u32, 117);
pub const PRODUCT_INDUSTRY_HANDHELD = @as(u32, 118);
pub const PRODUCT_PPI_PRO = @as(u32, 119);
pub const PRODUCT_ARM64_SERVER = @as(u32, 120);
pub const PRODUCT_CLOUD_HOST_INFRASTRUCTURE_SERVER = @as(u32, 124);
pub const PRODUCT_PROFESSIONAL_S = @as(u32, 127);
pub const PRODUCT_PROFESSIONAL_S_N = @as(u32, 128);
pub const PRODUCT_HOLOGRAPHIC = @as(u32, 135);
pub const PRODUCT_HOLOGRAPHIC_BUSINESS = @as(u32, 136);
pub const PRODUCT_PRO_SINGLE_LANGUAGE = @as(u32, 138);
pub const PRODUCT_PRO_CHINA = @as(u32, 139);
pub const PRODUCT_ENTERPRISE_SUBSCRIPTION = @as(u32, 140);
pub const PRODUCT_ENTERPRISE_SUBSCRIPTION_N = @as(u32, 141);
pub const PRODUCT_DATACENTER_NANO_SERVER = @as(u32, 143);
pub const PRODUCT_STANDARD_NANO_SERVER = @as(u32, 144);
pub const PRODUCT_DATACENTER_WS_SERVER_CORE = @as(u32, 147);
pub const PRODUCT_STANDARD_WS_SERVER_CORE = @as(u32, 148);
pub const PRODUCT_UTILITY_VM = @as(u32, 149);
pub const PRODUCT_DATACENTER_EVALUATION_SERVER_CORE = @as(u32, 159);
pub const PRODUCT_STANDARD_EVALUATION_SERVER_CORE = @as(u32, 160);
pub const PRODUCT_PRO_FOR_EDUCATION = @as(u32, 164);
pub const PRODUCT_PRO_FOR_EDUCATION_N = @as(u32, 165);
pub const PRODUCT_AZURE_SERVER_CORE = @as(u32, 168);
pub const PRODUCT_AZURE_NANO_SERVER = @as(u32, 169);
pub const PRODUCT_ENTERPRISEG = @as(u32, 171);
pub const PRODUCT_ENTERPRISEGN = @as(u32, 172);
pub const PRODUCT_SERVERRDSH = @as(u32, 175);
pub const PRODUCT_CLOUD = @as(u32, 178);
pub const PRODUCT_CLOUDN = @as(u32, 179);
pub const PRODUCT_HUBOS = @as(u32, 180);
pub const PRODUCT_ONECOREUPDATEOS = @as(u32, 182);
pub const PRODUCT_CLOUDE = @as(u32, 183);
pub const PRODUCT_ANDROMEDA = @as(u32, 184);
pub const PRODUCT_IOTOS = @as(u32, 185);
pub const PRODUCT_CLOUDEN = @as(u32, 186);
pub const PRODUCT_IOTEDGEOS = @as(u32, 187);
pub const PRODUCT_IOTENTERPRISE = @as(u32, 188);
pub const PRODUCT_LITE = @as(u32, 189);
pub const PRODUCT_IOTENTERPRISES = @as(u32, 191);
pub const PRODUCT_XBOX_SYSTEMOS = @as(u32, 192);
pub const PRODUCT_XBOX_NATIVEOS = @as(u32, 193);
pub const PRODUCT_XBOX_GAMEOS = @as(u32, 194);
pub const PRODUCT_XBOX_ERAOS = @as(u32, 195);
pub const PRODUCT_XBOX_DURANGOHOSTOS = @as(u32, 196);
pub const PRODUCT_XBOX_SCARLETTHOSTOS = @as(u32, 197);
pub const PRODUCT_UNLICENSED = @as(u32, 2882382797);
pub const LANG_NEUTRAL = @as(u32, 0);
pub const LANG_INVARIANT = @as(u32, 127);
pub const LANG_AFRIKAANS = @as(u32, 54);
pub const LANG_ALBANIAN = @as(u32, 28);
pub const LANG_ALSATIAN = @as(u32, 132);
pub const LANG_AMHARIC = @as(u32, 94);
pub const LANG_ARABIC = @as(u32, 1);
pub const LANG_ARMENIAN = @as(u32, 43);
pub const LANG_ASSAMESE = @as(u32, 77);
pub const LANG_AZERI = @as(u32, 44);
pub const LANG_AZERBAIJANI = @as(u32, 44);
pub const LANG_BANGLA = @as(u32, 69);
pub const LANG_BASHKIR = @as(u32, 109);
pub const LANG_BASQUE = @as(u32, 45);
pub const LANG_BELARUSIAN = @as(u32, 35);
pub const LANG_BENGALI = @as(u32, 69);
pub const LANG_BRETON = @as(u32, 126);
pub const LANG_BOSNIAN = @as(u32, 26);
pub const LANG_BOSNIAN_NEUTRAL = @as(u32, 30746);
pub const LANG_BULGARIAN = @as(u32, 2);
pub const LANG_CATALAN = @as(u32, 3);
pub const LANG_CENTRAL_KURDISH = @as(u32, 146);
pub const LANG_CHEROKEE = @as(u32, 92);
pub const LANG_CHINESE = @as(u32, 4);
pub const LANG_CHINESE_SIMPLIFIED = @as(u32, 4);
pub const LANG_CHINESE_TRADITIONAL = @as(u32, 31748);
pub const LANG_CORSICAN = @as(u32, 131);
pub const LANG_CROATIAN = @as(u32, 26);
pub const LANG_CZECH = @as(u32, 5);
pub const LANG_DANISH = @as(u32, 6);
pub const LANG_DARI = @as(u32, 140);
pub const LANG_DIVEHI = @as(u32, 101);
pub const LANG_DUTCH = @as(u32, 19);
pub const LANG_ENGLISH = @as(u32, 9);
pub const LANG_ESTONIAN = @as(u32, 37);
pub const LANG_FAEROESE = @as(u32, 56);
pub const LANG_FARSI = @as(u32, 41);
pub const LANG_FILIPINO = @as(u32, 100);
pub const LANG_FINNISH = @as(u32, 11);
pub const LANG_FRENCH = @as(u32, 12);
pub const LANG_FRISIAN = @as(u32, 98);
pub const LANG_FULAH = @as(u32, 103);
pub const LANG_GALICIAN = @as(u32, 86);
pub const LANG_GEORGIAN = @as(u32, 55);
pub const LANG_GERMAN = @as(u32, 7);
pub const LANG_GREEK = @as(u32, 8);
pub const LANG_GREENLANDIC = @as(u32, 111);
pub const LANG_GUJARATI = @as(u32, 71);
pub const LANG_HAUSA = @as(u32, 104);
pub const LANG_HAWAIIAN = @as(u32, 117);
pub const LANG_HEBREW = @as(u32, 13);
pub const LANG_HINDI = @as(u32, 57);
pub const LANG_HUNGARIAN = @as(u32, 14);
pub const LANG_ICELANDIC = @as(u32, 15);
pub const LANG_IGBO = @as(u32, 112);
pub const LANG_INDONESIAN = @as(u32, 33);
pub const LANG_INUKTITUT = @as(u32, 93);
pub const LANG_IRISH = @as(u32, 60);
pub const LANG_ITALIAN = @as(u32, 16);
pub const LANG_JAPANESE = @as(u32, 17);
pub const LANG_KANNADA = @as(u32, 75);
pub const LANG_KASHMIRI = @as(u32, 96);
pub const LANG_KAZAK = @as(u32, 63);
pub const LANG_KHMER = @as(u32, 83);
pub const LANG_KICHE = @as(u32, 134);
pub const LANG_KINYARWANDA = @as(u32, 135);
pub const LANG_KONKANI = @as(u32, 87);
pub const LANG_KOREAN = @as(u32, 18);
pub const LANG_KYRGYZ = @as(u32, 64);
pub const LANG_LAO = @as(u32, 84);
pub const LANG_LATVIAN = @as(u32, 38);
pub const LANG_LITHUANIAN = @as(u32, 39);
pub const LANG_LOWER_SORBIAN = @as(u32, 46);
pub const LANG_LUXEMBOURGISH = @as(u32, 110);
pub const LANG_MACEDONIAN = @as(u32, 47);
pub const LANG_MALAY = @as(u32, 62);
pub const LANG_MALAYALAM = @as(u32, 76);
pub const LANG_MALTESE = @as(u32, 58);
pub const LANG_MANIPURI = @as(u32, 88);
pub const LANG_MAORI = @as(u32, 129);
pub const LANG_MAPUDUNGUN = @as(u32, 122);
pub const LANG_MARATHI = @as(u32, 78);
pub const LANG_MOHAWK = @as(u32, 124);
pub const LANG_MONGOLIAN = @as(u32, 80);
pub const LANG_NEPALI = @as(u32, 97);
pub const LANG_NORWEGIAN = @as(u32, 20);
pub const LANG_OCCITAN = @as(u32, 130);
pub const LANG_ODIA = @as(u32, 72);
pub const LANG_ORIYA = @as(u32, 72);
pub const LANG_PASHTO = @as(u32, 99);
pub const LANG_PERSIAN = @as(u32, 41);
pub const LANG_POLISH = @as(u32, 21);
pub const LANG_PORTUGUESE = @as(u32, 22);
pub const LANG_PULAR = @as(u32, 103);
pub const LANG_PUNJABI = @as(u32, 70);
pub const LANG_QUECHUA = @as(u32, 107);
pub const LANG_ROMANIAN = @as(u32, 24);
pub const LANG_ROMANSH = @as(u32, 23);
pub const LANG_RUSSIAN = @as(u32, 25);
pub const LANG_SAKHA = @as(u32, 133);
pub const LANG_SAMI = @as(u32, 59);
pub const LANG_SANSKRIT = @as(u32, 79);
pub const LANG_SCOTTISH_GAELIC = @as(u32, 145);
pub const LANG_SERBIAN = @as(u32, 26);
pub const LANG_SERBIAN_NEUTRAL = @as(u32, 31770);
pub const LANG_SINDHI = @as(u32, 89);
pub const LANG_SINHALESE = @as(u32, 91);
pub const LANG_SLOVAK = @as(u32, 27);
pub const LANG_SLOVENIAN = @as(u32, 36);
pub const LANG_SOTHO = @as(u32, 108);
pub const LANG_SPANISH = @as(u32, 10);
pub const LANG_SWAHILI = @as(u32, 65);
pub const LANG_SWEDISH = @as(u32, 29);
pub const LANG_SYRIAC = @as(u32, 90);
pub const LANG_TAJIK = @as(u32, 40);
pub const LANG_TAMAZIGHT = @as(u32, 95);
pub const LANG_TAMIL = @as(u32, 73);
pub const LANG_TATAR = @as(u32, 68);
pub const LANG_TELUGU = @as(u32, 74);
pub const LANG_THAI = @as(u32, 30);
pub const LANG_TIBETAN = @as(u32, 81);
pub const LANG_TIGRIGNA = @as(u32, 115);
pub const LANG_TIGRINYA = @as(u32, 115);
pub const LANG_TSWANA = @as(u32, 50);
pub const LANG_TURKISH = @as(u32, 31);
pub const LANG_TURKMEN = @as(u32, 66);
pub const LANG_UIGHUR = @as(u32, 128);
pub const LANG_UKRAINIAN = @as(u32, 34);
pub const LANG_UPPER_SORBIAN = @as(u32, 46);
pub const LANG_URDU = @as(u32, 32);
pub const LANG_UZBEK = @as(u32, 67);
pub const LANG_VALENCIAN = @as(u32, 3);
pub const LANG_VIETNAMESE = @as(u32, 42);
pub const LANG_WELSH = @as(u32, 82);
pub const LANG_WOLOF = @as(u32, 136);
pub const LANG_XHOSA = @as(u32, 52);
pub const LANG_YAKUT = @as(u32, 133);
pub const LANG_YI = @as(u32, 120);
pub const LANG_YORUBA = @as(u32, 106);
pub const LANG_ZULU = @as(u32, 53);
pub const SUBLANG_NEUTRAL = @as(u32, 0);
pub const SUBLANG_DEFAULT = @as(u32, 1);
pub const SUBLANG_SYS_DEFAULT = @as(u32, 2);
pub const SUBLANG_CUSTOM_DEFAULT = @as(u32, 3);
pub const SUBLANG_CUSTOM_UNSPECIFIED = @as(u32, 4);
pub const SUBLANG_UI_CUSTOM_DEFAULT = @as(u32, 5);
pub const SUBLANG_AFRIKAANS_SOUTH_AFRICA = @as(u32, 1);
pub const SUBLANG_ALBANIAN_ALBANIA = @as(u32, 1);
pub const SUBLANG_ALSATIAN_FRANCE = @as(u32, 1);
pub const SUBLANG_AMHARIC_ETHIOPIA = @as(u32, 1);
pub const SUBLANG_ARABIC_SAUDI_ARABIA = @as(u32, 1);
pub const SUBLANG_ARABIC_IRAQ = @as(u32, 2);
pub const SUBLANG_ARABIC_EGYPT = @as(u32, 3);
pub const SUBLANG_ARABIC_LIBYA = @as(u32, 4);
pub const SUBLANG_ARABIC_ALGERIA = @as(u32, 5);
pub const SUBLANG_ARABIC_MOROCCO = @as(u32, 6);
pub const SUBLANG_ARABIC_TUNISIA = @as(u32, 7);
pub const SUBLANG_ARABIC_OMAN = @as(u32, 8);
pub const SUBLANG_ARABIC_YEMEN = @as(u32, 9);
pub const SUBLANG_ARABIC_SYRIA = @as(u32, 10);
pub const SUBLANG_ARABIC_JORDAN = @as(u32, 11);
pub const SUBLANG_ARABIC_LEBANON = @as(u32, 12);
pub const SUBLANG_ARABIC_KUWAIT = @as(u32, 13);
pub const SUBLANG_ARABIC_UAE = @as(u32, 14);
pub const SUBLANG_ARABIC_BAHRAIN = @as(u32, 15);
pub const SUBLANG_ARABIC_QATAR = @as(u32, 16);
pub const SUBLANG_ARMENIAN_ARMENIA = @as(u32, 1);
pub const SUBLANG_ASSAMESE_INDIA = @as(u32, 1);
pub const SUBLANG_AZERI_LATIN = @as(u32, 1);
pub const SUBLANG_AZERI_CYRILLIC = @as(u32, 2);
pub const SUBLANG_AZERBAIJANI_AZERBAIJAN_LATIN = @as(u32, 1);
pub const SUBLANG_AZERBAIJANI_AZERBAIJAN_CYRILLIC = @as(u32, 2);
pub const SUBLANG_BANGLA_INDIA = @as(u32, 1);
pub const SUBLANG_BANGLA_BANGLADESH = @as(u32, 2);
pub const SUBLANG_BASHKIR_RUSSIA = @as(u32, 1);
pub const SUBLANG_BASQUE_BASQUE = @as(u32, 1);
pub const SUBLANG_BELARUSIAN_BELARUS = @as(u32, 1);
pub const SUBLANG_BENGALI_INDIA = @as(u32, 1);
pub const SUBLANG_BENGALI_BANGLADESH = @as(u32, 2);
pub const SUBLANG_BOSNIAN_BOSNIA_HERZEGOVINA_LATIN = @as(u32, 5);
pub const SUBLANG_BOSNIAN_BOSNIA_HERZEGOVINA_CYRILLIC = @as(u32, 8);
pub const SUBLANG_BRETON_FRANCE = @as(u32, 1);
pub const SUBLANG_BULGARIAN_BULGARIA = @as(u32, 1);
pub const SUBLANG_CATALAN_CATALAN = @as(u32, 1);
pub const SUBLANG_CENTRAL_KURDISH_IRAQ = @as(u32, 1);
pub const SUBLANG_CHEROKEE_CHEROKEE = @as(u32, 1);
pub const SUBLANG_CHINESE_TRADITIONAL = @as(u32, 1);
pub const SUBLANG_CHINESE_SIMPLIFIED = @as(u32, 2);
pub const SUBLANG_CHINESE_HONGKONG = @as(u32, 3);
pub const SUBLANG_CHINESE_SINGAPORE = @as(u32, 4);
pub const SUBLANG_CHINESE_MACAU = @as(u32, 5);
pub const SUBLANG_CORSICAN_FRANCE = @as(u32, 1);
pub const SUBLANG_CZECH_CZECH_REPUBLIC = @as(u32, 1);
pub const SUBLANG_CROATIAN_CROATIA = @as(u32, 1);
pub const SUBLANG_CROATIAN_BOSNIA_HERZEGOVINA_LATIN = @as(u32, 4);
pub const SUBLANG_DANISH_DENMARK = @as(u32, 1);
pub const SUBLANG_DARI_AFGHANISTAN = @as(u32, 1);
pub const SUBLANG_DIVEHI_MALDIVES = @as(u32, 1);
pub const SUBLANG_DUTCH = @as(u32, 1);
pub const SUBLANG_DUTCH_BELGIAN = @as(u32, 2);
pub const SUBLANG_ENGLISH_US = @as(u32, 1);
pub const SUBLANG_ENGLISH_UK = @as(u32, 2);
pub const SUBLANG_ENGLISH_AUS = @as(u32, 3);
pub const SUBLANG_ENGLISH_CAN = @as(u32, 4);
pub const SUBLANG_ENGLISH_NZ = @as(u32, 5);
pub const SUBLANG_ENGLISH_EIRE = @as(u32, 6);
pub const SUBLANG_ENGLISH_SOUTH_AFRICA = @as(u32, 7);
pub const SUBLANG_ENGLISH_JAMAICA = @as(u32, 8);
pub const SUBLANG_ENGLISH_CARIBBEAN = @as(u32, 9);
pub const SUBLANG_ENGLISH_BELIZE = @as(u32, 10);
pub const SUBLANG_ENGLISH_TRINIDAD = @as(u32, 11);
pub const SUBLANG_ENGLISH_ZIMBABWE = @as(u32, 12);
pub const SUBLANG_ENGLISH_PHILIPPINES = @as(u32, 13);
pub const SUBLANG_ENGLISH_INDIA = @as(u32, 16);
pub const SUBLANG_ENGLISH_MALAYSIA = @as(u32, 17);
pub const SUBLANG_ENGLISH_SINGAPORE = @as(u32, 18);
pub const SUBLANG_ESTONIAN_ESTONIA = @as(u32, 1);
pub const SUBLANG_FAEROESE_FAROE_ISLANDS = @as(u32, 1);
pub const SUBLANG_FILIPINO_PHILIPPINES = @as(u32, 1);
pub const SUBLANG_FINNISH_FINLAND = @as(u32, 1);
pub const SUBLANG_FRENCH = @as(u32, 1);
pub const SUBLANG_FRENCH_BELGIAN = @as(u32, 2);
pub const SUBLANG_FRENCH_CANADIAN = @as(u32, 3);
pub const SUBLANG_FRENCH_SWISS = @as(u32, 4);
pub const SUBLANG_FRENCH_LUXEMBOURG = @as(u32, 5);
pub const SUBLANG_FRENCH_MONACO = @as(u32, 6);
pub const SUBLANG_FRISIAN_NETHERLANDS = @as(u32, 1);
pub const SUBLANG_FULAH_SENEGAL = @as(u32, 2);
pub const SUBLANG_GALICIAN_GALICIAN = @as(u32, 1);
pub const SUBLANG_GEORGIAN_GEORGIA = @as(u32, 1);
pub const SUBLANG_GERMAN = @as(u32, 1);
pub const SUBLANG_GERMAN_SWISS = @as(u32, 2);
pub const SUBLANG_GERMAN_AUSTRIAN = @as(u32, 3);
pub const SUBLANG_GERMAN_LUXEMBOURG = @as(u32, 4);
pub const SUBLANG_GERMAN_LIECHTENSTEIN = @as(u32, 5);
pub const SUBLANG_GREEK_GREECE = @as(u32, 1);
pub const SUBLANG_GREENLANDIC_GREENLAND = @as(u32, 1);
pub const SUBLANG_GUJARATI_INDIA = @as(u32, 1);
pub const SUBLANG_HAUSA_NIGERIA_LATIN = @as(u32, 1);
pub const SUBLANG_HAWAIIAN_US = @as(u32, 1);
pub const SUBLANG_HEBREW_ISRAEL = @as(u32, 1);
pub const SUBLANG_HINDI_INDIA = @as(u32, 1);
pub const SUBLANG_HUNGARIAN_HUNGARY = @as(u32, 1);
pub const SUBLANG_ICELANDIC_ICELAND = @as(u32, 1);
pub const SUBLANG_IGBO_NIGERIA = @as(u32, 1);
pub const SUBLANG_INDONESIAN_INDONESIA = @as(u32, 1);
pub const SUBLANG_INUKTITUT_CANADA = @as(u32, 1);
pub const SUBLANG_INUKTITUT_CANADA_LATIN = @as(u32, 2);
pub const SUBLANG_IRISH_IRELAND = @as(u32, 2);
pub const SUBLANG_ITALIAN = @as(u32, 1);
pub const SUBLANG_ITALIAN_SWISS = @as(u32, 2);
pub const SUBLANG_JAPANESE_JAPAN = @as(u32, 1);
pub const SUBLANG_KANNADA_INDIA = @as(u32, 1);
pub const SUBLANG_KASHMIRI_SASIA = @as(u32, 2);
pub const SUBLANG_KASHMIRI_INDIA = @as(u32, 2);
pub const SUBLANG_KAZAK_KAZAKHSTAN = @as(u32, 1);
pub const SUBLANG_KHMER_CAMBODIA = @as(u32, 1);
pub const SUBLANG_KICHE_GUATEMALA = @as(u32, 1);
pub const SUBLANG_KINYARWANDA_RWANDA = @as(u32, 1);
pub const SUBLANG_KONKANI_INDIA = @as(u32, 1);
pub const SUBLANG_KOREAN = @as(u32, 1);
pub const SUBLANG_KYRGYZ_KYRGYZSTAN = @as(u32, 1);
pub const SUBLANG_LAO_LAO = @as(u32, 1);
pub const SUBLANG_LATVIAN_LATVIA = @as(u32, 1);
pub const SUBLANG_LITHUANIAN = @as(u32, 1);
pub const SUBLANG_LOWER_SORBIAN_GERMANY = @as(u32, 2);
pub const SUBLANG_LUXEMBOURGISH_LUXEMBOURG = @as(u32, 1);
pub const SUBLANG_MACEDONIAN_MACEDONIA = @as(u32, 1);
pub const SUBLANG_MALAY_MALAYSIA = @as(u32, 1);
pub const SUBLANG_MALAY_BRUNEI_DARUSSALAM = @as(u32, 2);
pub const SUBLANG_MALAYALAM_INDIA = @as(u32, 1);
pub const SUBLANG_MALTESE_MALTA = @as(u32, 1);
pub const SUBLANG_MAORI_NEW_ZEALAND = @as(u32, 1);
pub const SUBLANG_MAPUDUNGUN_CHILE = @as(u32, 1);
pub const SUBLANG_MARATHI_INDIA = @as(u32, 1);
pub const SUBLANG_MOHAWK_MOHAWK = @as(u32, 1);
pub const SUBLANG_MONGOLIAN_CYRILLIC_MONGOLIA = @as(u32, 1);
pub const SUBLANG_MONGOLIAN_PRC = @as(u32, 2);
pub const SUBLANG_NEPALI_INDIA = @as(u32, 2);
pub const SUBLANG_NEPALI_NEPAL = @as(u32, 1);
pub const SUBLANG_NORWEGIAN_BOKMAL = @as(u32, 1);
pub const SUBLANG_NORWEGIAN_NYNORSK = @as(u32, 2);
pub const SUBLANG_OCCITAN_FRANCE = @as(u32, 1);
pub const SUBLANG_ODIA_INDIA = @as(u32, 1);
pub const SUBLANG_ORIYA_INDIA = @as(u32, 1);
pub const SUBLANG_PASHTO_AFGHANISTAN = @as(u32, 1);
pub const SUBLANG_PERSIAN_IRAN = @as(u32, 1);
pub const SUBLANG_POLISH_POLAND = @as(u32, 1);
pub const SUBLANG_PORTUGUESE = @as(u32, 2);
pub const SUBLANG_PORTUGUESE_BRAZILIAN = @as(u32, 1);
pub const SUBLANG_PULAR_SENEGAL = @as(u32, 2);
pub const SUBLANG_PUNJABI_INDIA = @as(u32, 1);
pub const SUBLANG_PUNJABI_PAKISTAN = @as(u32, 2);
pub const SUBLANG_QUECHUA_BOLIVIA = @as(u32, 1);
pub const SUBLANG_QUECHUA_ECUADOR = @as(u32, 2);
pub const SUBLANG_QUECHUA_PERU = @as(u32, 3);
pub const SUBLANG_ROMANIAN_ROMANIA = @as(u32, 1);
pub const SUBLANG_ROMANSH_SWITZERLAND = @as(u32, 1);
pub const SUBLANG_RUSSIAN_RUSSIA = @as(u32, 1);
pub const SUBLANG_SAKHA_RUSSIA = @as(u32, 1);
pub const SUBLANG_SAMI_NORTHERN_NORWAY = @as(u32, 1);
pub const SUBLANG_SAMI_NORTHERN_SWEDEN = @as(u32, 2);
pub const SUBLANG_SAMI_NORTHERN_FINLAND = @as(u32, 3);
pub const SUBLANG_SAMI_LULE_NORWAY = @as(u32, 4);
pub const SUBLANG_SAMI_LULE_SWEDEN = @as(u32, 5);
pub const SUBLANG_SAMI_SOUTHERN_NORWAY = @as(u32, 6);
pub const SUBLANG_SAMI_SOUTHERN_SWEDEN = @as(u32, 7);
pub const SUBLANG_SAMI_SKOLT_FINLAND = @as(u32, 8);
pub const SUBLANG_SAMI_INARI_FINLAND = @as(u32, 9);
pub const SUBLANG_SANSKRIT_INDIA = @as(u32, 1);
pub const SUBLANG_SCOTTISH_GAELIC = @as(u32, 1);
pub const SUBLANG_SERBIAN_BOSNIA_HERZEGOVINA_LATIN = @as(u32, 6);
pub const SUBLANG_SERBIAN_BOSNIA_HERZEGOVINA_CYRILLIC = @as(u32, 7);
pub const SUBLANG_SERBIAN_MONTENEGRO_LATIN = @as(u32, 11);
pub const SUBLANG_SERBIAN_MONTENEGRO_CYRILLIC = @as(u32, 12);
pub const SUBLANG_SERBIAN_SERBIA_LATIN = @as(u32, 9);
pub const SUBLANG_SERBIAN_SERBIA_CYRILLIC = @as(u32, 10);
pub const SUBLANG_SERBIAN_CROATIA = @as(u32, 1);
pub const SUBLANG_SERBIAN_LATIN = @as(u32, 2);
pub const SUBLANG_SERBIAN_CYRILLIC = @as(u32, 3);
pub const SUBLANG_SINDHI_INDIA = @as(u32, 1);
pub const SUBLANG_SINDHI_PAKISTAN = @as(u32, 2);
pub const SUBLANG_SINDHI_AFGHANISTAN = @as(u32, 2);
pub const SUBLANG_SINHALESE_SRI_LANKA = @as(u32, 1);
pub const SUBLANG_SOTHO_NORTHERN_SOUTH_AFRICA = @as(u32, 1);
pub const SUBLANG_SLOVAK_SLOVAKIA = @as(u32, 1);
pub const SUBLANG_SLOVENIAN_SLOVENIA = @as(u32, 1);
pub const SUBLANG_SPANISH = @as(u32, 1);
pub const SUBLANG_SPANISH_MEXICAN = @as(u32, 2);
pub const SUBLANG_SPANISH_MODERN = @as(u32, 3);
pub const SUBLANG_SPANISH_GUATEMALA = @as(u32, 4);
pub const SUBLANG_SPANISH_COSTA_RICA = @as(u32, 5);
pub const SUBLANG_SPANISH_PANAMA = @as(u32, 6);
pub const SUBLANG_SPANISH_DOMINICAN_REPUBLIC = @as(u32, 7);
pub const SUBLANG_SPANISH_VENEZUELA = @as(u32, 8);
pub const SUBLANG_SPANISH_COLOMBIA = @as(u32, 9);
pub const SUBLANG_SPANISH_PERU = @as(u32, 10);
pub const SUBLANG_SPANISH_ARGENTINA = @as(u32, 11);
pub const SUBLANG_SPANISH_ECUADOR = @as(u32, 12);
pub const SUBLANG_SPANISH_CHILE = @as(u32, 13);
pub const SUBLANG_SPANISH_URUGUAY = @as(u32, 14);
pub const SUBLANG_SPANISH_PARAGUAY = @as(u32, 15);
pub const SUBLANG_SPANISH_BOLIVIA = @as(u32, 16);
pub const SUBLANG_SPANISH_EL_SALVADOR = @as(u32, 17);
pub const SUBLANG_SPANISH_HONDURAS = @as(u32, 18);
pub const SUBLANG_SPANISH_NICARAGUA = @as(u32, 19);
pub const SUBLANG_SPANISH_PUERTO_RICO = @as(u32, 20);
pub const SUBLANG_SPANISH_US = @as(u32, 21);
pub const SUBLANG_SWAHILI_KENYA = @as(u32, 1);
pub const SUBLANG_SWEDISH = @as(u32, 1);
pub const SUBLANG_SWEDISH_FINLAND = @as(u32, 2);
pub const SUBLANG_SYRIAC_SYRIA = @as(u32, 1);
pub const SUBLANG_TAJIK_TAJIKISTAN = @as(u32, 1);
pub const SUBLANG_TAMAZIGHT_ALGERIA_LATIN = @as(u32, 2);
pub const SUBLANG_TAMAZIGHT_MOROCCO_TIFINAGH = @as(u32, 4);
pub const SUBLANG_TAMIL_INDIA = @as(u32, 1);
pub const SUBLANG_TAMIL_SRI_LANKA = @as(u32, 2);
pub const SUBLANG_TATAR_RUSSIA = @as(u32, 1);
pub const SUBLANG_TELUGU_INDIA = @as(u32, 1);
pub const SUBLANG_THAI_THAILAND = @as(u32, 1);
pub const SUBLANG_TIBETAN_PRC = @as(u32, 1);
pub const SUBLANG_TIGRIGNA_ERITREA = @as(u32, 2);
pub const SUBLANG_TIGRINYA_ERITREA = @as(u32, 2);
pub const SUBLANG_TIGRINYA_ETHIOPIA = @as(u32, 1);
pub const SUBLANG_TSWANA_BOTSWANA = @as(u32, 2);
pub const SUBLANG_TSWANA_SOUTH_AFRICA = @as(u32, 1);
pub const SUBLANG_TURKISH_TURKEY = @as(u32, 1);
pub const SUBLANG_TURKMEN_TURKMENISTAN = @as(u32, 1);
pub const SUBLANG_UIGHUR_PRC = @as(u32, 1);
pub const SUBLANG_UKRAINIAN_UKRAINE = @as(u32, 1);
pub const SUBLANG_UPPER_SORBIAN_GERMANY = @as(u32, 1);
pub const SUBLANG_URDU_PAKISTAN = @as(u32, 1);
pub const SUBLANG_URDU_INDIA = @as(u32, 2);
pub const SUBLANG_UZBEK_LATIN = @as(u32, 1);
pub const SUBLANG_UZBEK_CYRILLIC = @as(u32, 2);
pub const SUBLANG_VALENCIAN_VALENCIA = @as(u32, 2);
pub const SUBLANG_VIETNAMESE_VIETNAM = @as(u32, 1);
pub const SUBLANG_WELSH_UNITED_KINGDOM = @as(u32, 1);
pub const SUBLANG_WOLOF_SENEGAL = @as(u32, 1);
pub const SUBLANG_XHOSA_SOUTH_AFRICA = @as(u32, 1);
pub const SUBLANG_YAKUT_RUSSIA = @as(u32, 1);
pub const SUBLANG_YI_PRC = @as(u32, 1);
pub const SUBLANG_YORUBA_NIGERIA = @as(u32, 1);
pub const SUBLANG_ZULU_SOUTH_AFRICA = @as(u32, 1);
pub const SORT_DEFAULT = @as(u32, 0);
pub const SORT_INVARIANT_MATH = @as(u32, 1);
pub const SORT_JAPANESE_XJIS = @as(u32, 0);
pub const SORT_JAPANESE_UNICODE = @as(u32, 1);
pub const SORT_JAPANESE_RADICALSTROKE = @as(u32, 4);
pub const SORT_CHINESE_BIG5 = @as(u32, 0);
pub const SORT_CHINESE_PRCP = @as(u32, 0);
pub const SORT_CHINESE_UNICODE = @as(u32, 1);
pub const SORT_CHINESE_PRC = @as(u32, 2);
pub const SORT_CHINESE_BOPOMOFO = @as(u32, 3);
pub const SORT_CHINESE_RADICALSTROKE = @as(u32, 4);
pub const SORT_KOREAN_KSC = @as(u32, 0);
pub const SORT_KOREAN_UNICODE = @as(u32, 1);
pub const SORT_GERMAN_PHONE_BOOK = @as(u32, 1);
pub const SORT_HUNGARIAN_DEFAULT = @as(u32, 0);
pub const SORT_HUNGARIAN_TECHNICAL = @as(u32, 1);
pub const SORT_GEORGIAN_TRADITIONAL = @as(u32, 0);
pub const SORT_GEORGIAN_MODERN = @as(u32, 1);
pub const NLS_VALID_LOCALE_MASK = @as(u32, 1048575);
pub const LOCALE_NAME_MAX_LENGTH = @as(u32, 85);
pub const LOCALE_TRANSIENT_KEYBOARD1 = @as(u32, 8192);
pub const LOCALE_TRANSIENT_KEYBOARD2 = @as(u32, 9216);
pub const LOCALE_TRANSIENT_KEYBOARD3 = @as(u32, 10240);
pub const LOCALE_TRANSIENT_KEYBOARD4 = @as(u32, 11264);
pub const MAXIMUM_WAIT_OBJECTS = @as(u32, 64);
pub const EXCEPTION_READ_FAULT = @as(u32, 0);
pub const EXCEPTION_WRITE_FAULT = @as(u32, 1);
pub const EXCEPTION_EXECUTE_FAULT = @as(u32, 8);
pub const CONTEXT_AMD64 = @as(i32, 1048576);
pub const CONTEXT_KERNEL_DEBUGGER = @as(i32, 67108864);
pub const CONTEXT_EXCEPTION_ACTIVE = @as(i32, 134217728);
pub const CONTEXT_SERVICE_ACTIVE = @as(i32, 268435456);
pub const CONTEXT_EXCEPTION_REQUEST = @as(i32, 1073741824);
pub const CONTEXT_EXCEPTION_REPORTING = @as(i32, -2147483648);
pub const INITIAL_MXCSR = @as(u32, 8064);
pub const INITIAL_FPCSR = @as(u32, 639);
pub const RUNTIME_FUNCTION_INDIRECT = @as(u32, 1);
pub const UNW_FLAG_NO_EPILOGUE = @as(u32, 2147483648);
pub const UNWIND_CHAIN_LIMIT = @as(u32, 32);
pub const UNWIND_HISTORY_TABLE_SIZE = @as(u32, 12);
pub const PF_TEMPORAL_LEVEL_1 = @as(u32, 0);
pub const PF_TEMPORAL_LEVEL_2 = @as(u32, 1);
pub const PF_TEMPORAL_LEVEL_3 = @as(u32, 2);
pub const PF_NON_TEMPORAL_LEVEL_ALL = @as(u32, 3);
pub const CONTEXT_ARM = @as(i32, 2097152);
pub const CONTEXT_UNWOUND_TO_CALL = @as(u32, 536870912);
pub const INITIAL_CPSR = @as(u32, 16);
pub const INITIAL_FPSCR = @as(u32, 0);
pub const ARM_MAX_BREAKPOINTS = @as(u32, 8);
pub const ARM_MAX_WATCHPOINTS = @as(u32, 1);
pub const CONTEXT_ARM64 = @as(i32, 4194304);
pub const CONTEXT_RET_TO_GUEST = @as(u32, 67108864);
pub const ARM64_MAX_BREAKPOINTS = @as(u32, 8);
pub const ARM64_MAX_WATCHPOINTS = @as(u32, 2);
pub const BREAK_DEBUG_BASE = @as(u32, 524288);
pub const ASSERT_BREAKPOINT = @as(u32, 524291);
pub const SIZE_OF_80387_REGISTERS = @as(u32, 80);
pub const CONTEXT_i386 = @as(i32, 65536);
pub const CONTEXT_i486 = @as(i32, 65536);
pub const MAXIMUM_SUPPORTED_EXTENSION = @as(u32, 512);
pub const EXCEPTION_NONCONTINUABLE = @as(u32, 1);
pub const EXCEPTION_UNWINDING = @as(u32, 2);
pub const EXCEPTION_EXIT_UNWIND = @as(u32, 4);
pub const EXCEPTION_STACK_INVALID = @as(u32, 8);
pub const EXCEPTION_NESTED_CALL = @as(u32, 16);
pub const EXCEPTION_TARGET_UNWIND = @as(u32, 32);
pub const EXCEPTION_COLLIDED_UNWIND = @as(u32, 64);
pub const EXCEPTION_MAXIMUM_PARAMETERS = @as(u32, 15);
pub const DELETE = @as(u32, 65536);
pub const WRITE_DAC = @as(u32, 262144);
pub const WRITE_OWNER = @as(u32, 524288);
pub const ACCESS_SYSTEM_SECURITY = @as(u32, 16777216);
pub const MAXIMUM_ALLOWED = @as(u32, 33554432);
pub const GENERIC_READ = @as(u32, 2147483648);
pub const GENERIC_WRITE = @as(u32, 1073741824);
pub const GENERIC_EXECUTE = @as(u32, 536870912);
pub const GENERIC_ALL = @as(u32, 268435456);
pub const SID_REVISION = @as(u32, 1);
pub const SID_MAX_SUB_AUTHORITIES = @as(u32, 15);
pub const SID_RECOMMENDED_SUB_AUTHORITIES = @as(u32, 1);
pub const SID_HASH_SIZE = @as(u32, 32);
pub const SECURITY_NULL_RID = @as(i32, 0);
pub const SECURITY_WORLD_RID = @as(i32, 0);
pub const SECURITY_LOCAL_RID = @as(i32, 0);
pub const SECURITY_LOCAL_LOGON_RID = @as(i32, 1);
pub const SECURITY_CREATOR_OWNER_RID = @as(i32, 0);
pub const SECURITY_CREATOR_GROUP_RID = @as(i32, 1);
pub const SECURITY_CREATOR_OWNER_SERVER_RID = @as(i32, 2);
pub const SECURITY_CREATOR_GROUP_SERVER_RID = @as(i32, 3);
pub const SECURITY_CREATOR_OWNER_RIGHTS_RID = @as(i32, 4);
pub const SECURITY_DIALUP_RID = @as(i32, 1);
pub const SECURITY_NETWORK_RID = @as(i32, 2);
pub const SECURITY_BATCH_RID = @as(i32, 3);
pub const SECURITY_INTERACTIVE_RID = @as(i32, 4);
pub const SECURITY_LOGON_IDS_RID = @as(i32, 5);
pub const SECURITY_LOGON_IDS_RID_COUNT = @as(i32, 3);
pub const SECURITY_SERVICE_RID = @as(i32, 6);
pub const SECURITY_ANONYMOUS_LOGON_RID = @as(i32, 7);
pub const SECURITY_PROXY_RID = @as(i32, 8);
pub const SECURITY_ENTERPRISE_CONTROLLERS_RID = @as(i32, 9);
pub const SECURITY_PRINCIPAL_SELF_RID = @as(i32, 10);
pub const SECURITY_AUTHENTICATED_USER_RID = @as(i32, 11);
pub const SECURITY_RESTRICTED_CODE_RID = @as(i32, 12);
pub const SECURITY_TERMINAL_SERVER_RID = @as(i32, 13);
pub const SECURITY_REMOTE_LOGON_RID = @as(i32, 14);
pub const SECURITY_THIS_ORGANIZATION_RID = @as(i32, 15);
pub const SECURITY_IUSER_RID = @as(i32, 17);
pub const SECURITY_LOCAL_SYSTEM_RID = @as(i32, 18);
pub const SECURITY_LOCAL_SERVICE_RID = @as(i32, 19);
pub const SECURITY_NETWORK_SERVICE_RID = @as(i32, 20);
pub const SECURITY_NT_NON_UNIQUE = @as(i32, 21);
pub const SECURITY_NT_NON_UNIQUE_SUB_AUTH_COUNT = @as(i32, 3);
pub const SECURITY_ENTERPRISE_READONLY_CONTROLLERS_RID = @as(i32, 22);
pub const SECURITY_BUILTIN_DOMAIN_RID = @as(i32, 32);
pub const SECURITY_WRITE_RESTRICTED_CODE_RID = @as(i32, 33);
pub const SECURITY_PACKAGE_BASE_RID = @as(i32, 64);
pub const SECURITY_PACKAGE_RID_COUNT = @as(i32, 2);
pub const SECURITY_PACKAGE_NTLM_RID = @as(i32, 10);
pub const SECURITY_PACKAGE_SCHANNEL_RID = @as(i32, 14);
pub const SECURITY_PACKAGE_DIGEST_RID = @as(i32, 21);
pub const SECURITY_CRED_TYPE_BASE_RID = @as(i32, 65);
pub const SECURITY_CRED_TYPE_RID_COUNT = @as(i32, 2);
pub const SECURITY_CRED_TYPE_THIS_ORG_CERT_RID = @as(i32, 1);
pub const SECURITY_MIN_BASE_RID = @as(i32, 80);
pub const SECURITY_SERVICE_ID_BASE_RID = @as(i32, 80);
pub const SECURITY_SERVICE_ID_RID_COUNT = @as(i32, 6);
pub const SECURITY_RESERVED_ID_BASE_RID = @as(i32, 81);
pub const SECURITY_APPPOOL_ID_BASE_RID = @as(i32, 82);
pub const SECURITY_APPPOOL_ID_RID_COUNT = @as(i32, 6);
pub const SECURITY_VIRTUALSERVER_ID_BASE_RID = @as(i32, 83);
pub const SECURITY_VIRTUALSERVER_ID_RID_COUNT = @as(i32, 6);
pub const SECURITY_USERMODEDRIVERHOST_ID_BASE_RID = @as(i32, 84);
pub const SECURITY_USERMODEDRIVERHOST_ID_RID_COUNT = @as(i32, 6);
pub const SECURITY_CLOUD_INFRASTRUCTURE_SERVICES_ID_BASE_RID = @as(i32, 85);
pub const SECURITY_CLOUD_INFRASTRUCTURE_SERVICES_ID_RID_COUNT = @as(i32, 6);
pub const SECURITY_WMIHOST_ID_BASE_RID = @as(i32, 86);
pub const SECURITY_WMIHOST_ID_RID_COUNT = @as(i32, 6);
pub const SECURITY_TASK_ID_BASE_RID = @as(i32, 87);
pub const SECURITY_NFS_ID_BASE_RID = @as(i32, 88);
pub const SECURITY_COM_ID_BASE_RID = @as(i32, 89);
pub const SECURITY_WINDOW_MANAGER_BASE_RID = @as(i32, 90);
pub const SECURITY_RDV_GFX_BASE_RID = @as(i32, 91);
pub const SECURITY_DASHOST_ID_BASE_RID = @as(i32, 92);
pub const SECURITY_DASHOST_ID_RID_COUNT = @as(i32, 6);
pub const SECURITY_USERMANAGER_ID_BASE_RID = @as(i32, 93);
pub const SECURITY_USERMANAGER_ID_RID_COUNT = @as(i32, 6);
pub const SECURITY_WINRM_ID_BASE_RID = @as(i32, 94);
pub const SECURITY_WINRM_ID_RID_COUNT = @as(i32, 6);
pub const SECURITY_CCG_ID_BASE_RID = @as(i32, 95);
pub const SECURITY_UMFD_BASE_RID = @as(i32, 96);
pub const SECURITY_VIRTUALACCOUNT_ID_RID_COUNT = @as(i32, 6);
pub const SECURITY_MAX_BASE_RID = @as(i32, 111);
pub const SECURITY_MAX_ALWAYS_FILTERED = @as(i32, 999);
pub const SECURITY_MIN_NEVER_FILTERED = @as(i32, 1000);
pub const SECURITY_OTHER_ORGANIZATION_RID = @as(i32, 1000);
pub const SECURITY_WINDOWSMOBILE_ID_BASE_RID = @as(i32, 112);
pub const SECURITY_INSTALLER_GROUP_CAPABILITY_BASE = @as(u32, 32);
pub const SECURITY_INSTALLER_GROUP_CAPABILITY_RID_COUNT = @as(u32, 9);
pub const SECURITY_INSTALLER_CAPABILITY_RID_COUNT = @as(u32, 10);
pub const SECURITY_LOCAL_ACCOUNT_RID = @as(i32, 113);
pub const SECURITY_LOCAL_ACCOUNT_AND_ADMIN_RID = @as(i32, 114);
pub const DOMAIN_GROUP_RID_AUTHORIZATION_DATA_IS_COMPOUNDED = @as(i32, 496);
pub const DOMAIN_GROUP_RID_AUTHORIZATION_DATA_CONTAINS_CLAIMS = @as(i32, 497);
pub const DOMAIN_GROUP_RID_ENTERPRISE_READONLY_DOMAIN_CONTROLLERS = @as(i32, 498);
pub const FOREST_USER_RID_MAX = @as(i32, 499);
pub const DOMAIN_USER_RID_ADMIN = @as(i32, 500);
pub const DOMAIN_USER_RID_GUEST = @as(i32, 501);
pub const DOMAIN_USER_RID_KRBTGT = @as(i32, 502);
pub const DOMAIN_USER_RID_DEFAULT_ACCOUNT = @as(i32, 503);
pub const DOMAIN_USER_RID_WDAG_ACCOUNT = @as(i32, 504);
pub const DOMAIN_USER_RID_MAX = @as(i32, 999);
pub const DOMAIN_GROUP_RID_ADMINS = @as(i32, 512);
pub const DOMAIN_GROUP_RID_USERS = @as(i32, 513);
pub const DOMAIN_GROUP_RID_GUESTS = @as(i32, 514);
pub const DOMAIN_GROUP_RID_COMPUTERS = @as(i32, 515);
pub const DOMAIN_GROUP_RID_CONTROLLERS = @as(i32, 516);
pub const DOMAIN_GROUP_RID_CERT_ADMINS = @as(i32, 517);
pub const DOMAIN_GROUP_RID_SCHEMA_ADMINS = @as(i32, 518);
pub const DOMAIN_GROUP_RID_ENTERPRISE_ADMINS = @as(i32, 519);
pub const DOMAIN_GROUP_RID_POLICY_ADMINS = @as(i32, 520);
pub const DOMAIN_GROUP_RID_READONLY_CONTROLLERS = @as(i32, 521);
pub const DOMAIN_GROUP_RID_CLONEABLE_CONTROLLERS = @as(i32, 522);
pub const DOMAIN_GROUP_RID_CDC_RESERVED = @as(i32, 524);
pub const DOMAIN_GROUP_RID_PROTECTED_USERS = @as(i32, 525);
pub const DOMAIN_GROUP_RID_KEY_ADMINS = @as(i32, 526);
pub const DOMAIN_GROUP_RID_ENTERPRISE_KEY_ADMINS = @as(i32, 527);
pub const DOMAIN_ALIAS_RID_ADMINS = @as(i32, 544);
pub const DOMAIN_ALIAS_RID_USERS = @as(i32, 545);
pub const DOMAIN_ALIAS_RID_GUESTS = @as(i32, 546);
pub const DOMAIN_ALIAS_RID_POWER_USERS = @as(i32, 547);
pub const DOMAIN_ALIAS_RID_ACCOUNT_OPS = @as(i32, 548);
pub const DOMAIN_ALIAS_RID_SYSTEM_OPS = @as(i32, 549);
pub const DOMAIN_ALIAS_RID_PRINT_OPS = @as(i32, 550);
pub const DOMAIN_ALIAS_RID_BACKUP_OPS = @as(i32, 551);
pub const DOMAIN_ALIAS_RID_REPLICATOR = @as(i32, 552);
pub const DOMAIN_ALIAS_RID_RAS_SERVERS = @as(i32, 553);
pub const DOMAIN_ALIAS_RID_PREW2KCOMPACCESS = @as(i32, 554);
pub const DOMAIN_ALIAS_RID_REMOTE_DESKTOP_USERS = @as(i32, 555);
pub const DOMAIN_ALIAS_RID_NETWORK_CONFIGURATION_OPS = @as(i32, 556);
pub const DOMAIN_ALIAS_RID_INCOMING_FOREST_TRUST_BUILDERS = @as(i32, 557);
pub const DOMAIN_ALIAS_RID_MONITORING_USERS = @as(i32, 558);
pub const DOMAIN_ALIAS_RID_LOGGING_USERS = @as(i32, 559);
pub const DOMAIN_ALIAS_RID_AUTHORIZATIONACCESS = @as(i32, 560);
pub const DOMAIN_ALIAS_RID_TS_LICENSE_SERVERS = @as(i32, 561);
pub const DOMAIN_ALIAS_RID_DCOM_USERS = @as(i32, 562);
pub const DOMAIN_ALIAS_RID_IUSERS = @as(i32, 568);
pub const DOMAIN_ALIAS_RID_CRYPTO_OPERATORS = @as(i32, 569);
pub const DOMAIN_ALIAS_RID_CACHEABLE_PRINCIPALS_GROUP = @as(i32, 571);
pub const DOMAIN_ALIAS_RID_NON_CACHEABLE_PRINCIPALS_GROUP = @as(i32, 572);
pub const DOMAIN_ALIAS_RID_EVENT_LOG_READERS_GROUP = @as(i32, 573);
pub const DOMAIN_ALIAS_RID_CERTSVC_DCOM_ACCESS_GROUP = @as(i32, 574);
pub const DOMAIN_ALIAS_RID_RDS_REMOTE_ACCESS_SERVERS = @as(i32, 575);
pub const DOMAIN_ALIAS_RID_RDS_ENDPOINT_SERVERS = @as(i32, 576);
pub const DOMAIN_ALIAS_RID_RDS_MANAGEMENT_SERVERS = @as(i32, 577);
pub const DOMAIN_ALIAS_RID_HYPER_V_ADMINS = @as(i32, 578);
pub const DOMAIN_ALIAS_RID_ACCESS_CONTROL_ASSISTANCE_OPS = @as(i32, 579);
pub const DOMAIN_ALIAS_RID_REMOTE_MANAGEMENT_USERS = @as(i32, 580);
pub const DOMAIN_ALIAS_RID_DEFAULT_ACCOUNT = @as(i32, 581);
pub const DOMAIN_ALIAS_RID_STORAGE_REPLICA_ADMINS = @as(i32, 582);
pub const DOMAIN_ALIAS_RID_DEVICE_OWNERS = @as(i32, 583);
pub const SECURITY_APP_PACKAGE_BASE_RID = @as(i32, 2);
pub const SECURITY_BUILTIN_APP_PACKAGE_RID_COUNT = @as(i32, 2);
pub const SECURITY_APP_PACKAGE_RID_COUNT = @as(i32, 8);
pub const SECURITY_CAPABILITY_BASE_RID = @as(i32, 3);
pub const SECURITY_CAPABILITY_APP_RID = @as(u64, 1024);
pub const SECURITY_BUILTIN_CAPABILITY_RID_COUNT = @as(i32, 2);
pub const SECURITY_CAPABILITY_RID_COUNT = @as(i32, 5);
pub const SECURITY_CHILD_PACKAGE_RID_COUNT = @as(i32, 12);
pub const SECURITY_BUILTIN_PACKAGE_ANY_PACKAGE = @as(i32, 1);
pub const SECURITY_BUILTIN_PACKAGE_ANY_RESTRICTED_PACKAGE = @as(i32, 2);
pub const SECURITY_CAPABILITY_INTERNET_CLIENT = @as(i32, 1);
pub const SECURITY_CAPABILITY_INTERNET_CLIENT_SERVER = @as(i32, 2);
pub const SECURITY_CAPABILITY_PRIVATE_NETWORK_CLIENT_SERVER = @as(i32, 3);
pub const SECURITY_CAPABILITY_PICTURES_LIBRARY = @as(i32, 4);
pub const SECURITY_CAPABILITY_VIDEOS_LIBRARY = @as(i32, 5);
pub const SECURITY_CAPABILITY_MUSIC_LIBRARY = @as(i32, 6);
pub const SECURITY_CAPABILITY_DOCUMENTS_LIBRARY = @as(i32, 7);
pub const SECURITY_CAPABILITY_ENTERPRISE_AUTHENTICATION = @as(i32, 8);
pub const SECURITY_CAPABILITY_SHARED_USER_CERTIFICATES = @as(i32, 9);
pub const SECURITY_CAPABILITY_REMOVABLE_STORAGE = @as(i32, 10);
pub const SECURITY_CAPABILITY_APPOINTMENTS = @as(i32, 11);
pub const SECURITY_CAPABILITY_CONTACTS = @as(i32, 12);
pub const SECURITY_CAPABILITY_INTERNET_EXPLORER = @as(i32, 4096);
pub const SECURITY_MANDATORY_UNTRUSTED_RID = @as(i32, 0);
pub const SECURITY_MANDATORY_LOW_RID = @as(i32, 4096);
pub const SECURITY_MANDATORY_MEDIUM_RID = @as(i32, 8192);
pub const SECURITY_MANDATORY_MEDIUM_PLUS_RID = @as(u32, 8448);
pub const SECURITY_MANDATORY_HIGH_RID = @as(i32, 12288);
pub const SECURITY_MANDATORY_SYSTEM_RID = @as(i32, 16384);
pub const SECURITY_MANDATORY_PROTECTED_PROCESS_RID = @as(i32, 20480);
pub const SECURITY_AUTHENTICATION_AUTHORITY_RID_COUNT = @as(i32, 1);
pub const SECURITY_AUTHENTICATION_AUTHORITY_ASSERTED_RID = @as(i32, 1);
pub const SECURITY_AUTHENTICATION_SERVICE_ASSERTED_RID = @as(i32, 2);
pub const SECURITY_AUTHENTICATION_FRESH_KEY_AUTH_RID = @as(i32, 3);
pub const SECURITY_AUTHENTICATION_KEY_TRUST_RID = @as(i32, 4);
pub const SECURITY_AUTHENTICATION_KEY_PROPERTY_MFA_RID = @as(i32, 5);
pub const SECURITY_AUTHENTICATION_KEY_PROPERTY_ATTESTATION_RID = @as(i32, 6);
pub const SECURITY_PROCESS_TRUST_AUTHORITY_RID_COUNT = @as(i32, 2);
pub const SECURITY_PROCESS_PROTECTION_TYPE_FULL_RID = @as(i32, 1024);
pub const SECURITY_PROCESS_PROTECTION_TYPE_LITE_RID = @as(i32, 512);
pub const SECURITY_PROCESS_PROTECTION_TYPE_NONE_RID = @as(i32, 0);
pub const SECURITY_PROCESS_PROTECTION_LEVEL_WINTCB_RID = @as(i32, 8192);
pub const SECURITY_PROCESS_PROTECTION_LEVEL_WINDOWS_RID = @as(i32, 4096);
pub const SECURITY_PROCESS_PROTECTION_LEVEL_APP_RID = @as(i32, 2048);
pub const SECURITY_PROCESS_PROTECTION_LEVEL_ANTIMALWARE_RID = @as(i32, 1536);
pub const SECURITY_PROCESS_PROTECTION_LEVEL_AUTHENTICODE_RID = @as(i32, 1024);
pub const SECURITY_PROCESS_PROTECTION_LEVEL_NONE_RID = @as(i32, 0);
pub const SECURITY_TRUSTED_INSTALLER_RID1 = @as(u32, 956008885);
pub const SECURITY_TRUSTED_INSTALLER_RID2 = @as(u32, 3418522649);
pub const SECURITY_TRUSTED_INSTALLER_RID3 = @as(u32, 1831038044);
pub const SECURITY_TRUSTED_INSTALLER_RID4 = @as(u32, 1853292631);
pub const SECURITY_TRUSTED_INSTALLER_RID5 = @as(u32, 2271478464);
pub const SE_GROUP_MANDATORY = @as(i32, 1);
pub const SE_GROUP_ENABLED_BY_DEFAULT = @as(i32, 2);
pub const SE_GROUP_ENABLED = @as(i32, 4);
pub const SE_GROUP_OWNER = @as(i32, 8);
pub const SE_GROUP_USE_FOR_DENY_ONLY = @as(i32, 16);
pub const SE_GROUP_INTEGRITY = @as(i32, 32);
pub const SE_GROUP_INTEGRITY_ENABLED = @as(i32, 64);
pub const SE_GROUP_LOGON_ID = @as(i32, -1073741824);
pub const SE_GROUP_RESOURCE = @as(i32, 536870912);
pub const ACL_REVISION1 = @as(u32, 1);
pub const ACL_REVISION2 = @as(u32, 2);
pub const ACL_REVISION3 = @as(u32, 3);
pub const ACL_REVISION4 = @as(u32, 4);
pub const ACCESS_MIN_MS_ACE_TYPE = @as(u32, 0);
pub const ACCESS_ALLOWED_ACE_TYPE = @as(u32, 0);
pub const ACCESS_DENIED_ACE_TYPE = @as(u32, 1);
pub const SYSTEM_AUDIT_ACE_TYPE = @as(u32, 2);
pub const SYSTEM_ALARM_ACE_TYPE = @as(u32, 3);
pub const ACCESS_MAX_MS_V2_ACE_TYPE = @as(u32, 3);
pub const ACCESS_ALLOWED_COMPOUND_ACE_TYPE = @as(u32, 4);
pub const ACCESS_MAX_MS_V3_ACE_TYPE = @as(u32, 4);
pub const ACCESS_MIN_MS_OBJECT_ACE_TYPE = @as(u32, 5);
pub const ACCESS_ALLOWED_OBJECT_ACE_TYPE = @as(u32, 5);
pub const ACCESS_DENIED_OBJECT_ACE_TYPE = @as(u32, 6);
pub const SYSTEM_AUDIT_OBJECT_ACE_TYPE = @as(u32, 7);
pub const SYSTEM_ALARM_OBJECT_ACE_TYPE = @as(u32, 8);
pub const ACCESS_MAX_MS_OBJECT_ACE_TYPE = @as(u32, 8);
pub const ACCESS_MAX_MS_V4_ACE_TYPE = @as(u32, 8);
pub const ACCESS_MAX_MS_ACE_TYPE = @as(u32, 8);
pub const ACCESS_ALLOWED_CALLBACK_ACE_TYPE = @as(u32, 9);
pub const ACCESS_DENIED_CALLBACK_ACE_TYPE = @as(u32, 10);
pub const ACCESS_ALLOWED_CALLBACK_OBJECT_ACE_TYPE = @as(u32, 11);
pub const ACCESS_DENIED_CALLBACK_OBJECT_ACE_TYPE = @as(u32, 12);
pub const SYSTEM_AUDIT_CALLBACK_ACE_TYPE = @as(u32, 13);
pub const SYSTEM_ALARM_CALLBACK_ACE_TYPE = @as(u32, 14);
pub const SYSTEM_AUDIT_CALLBACK_OBJECT_ACE_TYPE = @as(u32, 15);
pub const SYSTEM_ALARM_CALLBACK_OBJECT_ACE_TYPE = @as(u32, 16);
pub const SYSTEM_MANDATORY_LABEL_ACE_TYPE = @as(u32, 17);
pub const SYSTEM_RESOURCE_ATTRIBUTE_ACE_TYPE = @as(u32, 18);
pub const SYSTEM_SCOPED_POLICY_ID_ACE_TYPE = @as(u32, 19);
pub const SYSTEM_PROCESS_TRUST_LABEL_ACE_TYPE = @as(u32, 20);
pub const SYSTEM_ACCESS_FILTER_ACE_TYPE = @as(u32, 21);
pub const ACCESS_MAX_MS_V5_ACE_TYPE = @as(u32, 21);
pub const VALID_INHERIT_FLAGS = @as(u32, 31);
pub const CRITICAL_ACE_FLAG = @as(u32, 32);
pub const TRUST_PROTECTED_FILTER_ACE_FLAG = @as(u32, 64);
pub const SYSTEM_MANDATORY_LABEL_NO_WRITE_UP = @as(u32, 1);
pub const SYSTEM_MANDATORY_LABEL_NO_READ_UP = @as(u32, 2);
pub const SYSTEM_MANDATORY_LABEL_NO_EXECUTE_UP = @as(u32, 4);
pub const SYSTEM_PROCESS_TRUST_LABEL_VALID_MASK = @as(u32, 16777215);
pub const SYSTEM_PROCESS_TRUST_NOCONSTRAINT_MASK = @as(u32, 4294967295);
pub const SYSTEM_ACCESS_FILTER_VALID_MASK = @as(u32, 16777215);
pub const SYSTEM_ACCESS_FILTER_NOCONSTRAINT_MASK = @as(u32, 4294967295);
pub const SECURITY_DESCRIPTOR_REVISION = @as(u32, 1);
pub const SECURITY_DESCRIPTOR_REVISION1 = @as(u32, 1);
pub const SE_OWNER_DEFAULTED = @as(u32, 1);
pub const SE_GROUP_DEFAULTED = @as(u32, 2);
pub const SE_DACL_PRESENT = @as(u32, 4);
pub const SE_DACL_DEFAULTED = @as(u32, 8);
pub const SE_SACL_PRESENT = @as(u32, 16);
pub const SE_SACL_DEFAULTED = @as(u32, 32);
pub const SE_DACL_AUTO_INHERIT_REQ = @as(u32, 256);
pub const SE_SACL_AUTO_INHERIT_REQ = @as(u32, 512);
pub const SE_DACL_AUTO_INHERITED = @as(u32, 1024);
pub const SE_SACL_AUTO_INHERITED = @as(u32, 2048);
pub const SE_DACL_PROTECTED = @as(u32, 4096);
pub const SE_SACL_PROTECTED = @as(u32, 8192);
pub const SE_RM_CONTROL_VALID = @as(u32, 16384);
pub const SE_SELF_RELATIVE = @as(u32, 32768);
pub const ACCESS_OBJECT_GUID = @as(u32, 0);
pub const ACCESS_PROPERTY_SET_GUID = @as(u32, 1);
pub const ACCESS_PROPERTY_GUID = @as(u32, 2);
pub const ACCESS_MAX_LEVEL = @as(u32, 4);
pub const AUDIT_ALLOW_NO_PRIVILEGE = @as(u32, 1);
pub const PRIVILEGE_SET_ALL_NECESSARY = @as(u32, 1);
pub const ACCESS_REASON_TYPE_MASK = @as(u32, 16711680);
pub const ACCESS_REASON_DATA_MASK = @as(u32, 65535);
pub const ACCESS_REASON_STAGING_MASK = @as(u32, 2147483648);
pub const ACCESS_REASON_EXDATA_MASK = @as(u32, 2130706432);
pub const SE_SECURITY_DESCRIPTOR_FLAG_NO_OWNER_ACE = @as(u32, 1);
pub const SE_SECURITY_DESCRIPTOR_FLAG_NO_LABEL_ACE = @as(u32, 2);
pub const SE_SECURITY_DESCRIPTOR_FLAG_NO_ACCESS_FILTER_ACE = @as(u32, 4);
pub const SE_SECURITY_DESCRIPTOR_VALID_FLAGS = @as(u32, 7);
pub const SE_ACCESS_CHECK_FLAG_NO_LEARNING_MODE_LOGGING = @as(u32, 8);
pub const SE_ACCESS_CHECK_VALID_FLAGS = @as(u32, 8);
pub const POLICY_AUDIT_SUBCATEGORY_COUNT = @as(u32, 59);
pub const TOKEN_SOURCE_LENGTH = @as(u32, 8);
pub const CLAIM_SECURITY_ATTRIBUTE_TYPE_INVALID = @as(u32, 0);
pub const CLAIM_SECURITY_ATTRIBUTE_CUSTOM_FLAGS = @as(u32, 4294901760);
pub const CLAIM_SECURITY_ATTRIBUTES_INFORMATION_VERSION_V1 = @as(u32, 1);
pub const PROCESS_TRUST_LABEL_SECURITY_INFORMATION = @as(i32, 128);
pub const ACCESS_FILTER_SECURITY_INFORMATION = @as(i32, 256);
pub const SE_SIGNING_LEVEL_UNCHECKED = @as(u32, 0);
pub const SE_SIGNING_LEVEL_UNSIGNED = @as(u32, 1);
pub const SE_SIGNING_LEVEL_ENTERPRISE = @as(u32, 2);
pub const SE_SIGNING_LEVEL_CUSTOM_1 = @as(u32, 3);
pub const SE_SIGNING_LEVEL_AUTHENTICODE = @as(u32, 4);
pub const SE_SIGNING_LEVEL_CUSTOM_2 = @as(u32, 5);
pub const SE_SIGNING_LEVEL_STORE = @as(u32, 6);
pub const SE_SIGNING_LEVEL_CUSTOM_3 = @as(u32, 7);
pub const SE_SIGNING_LEVEL_MICROSOFT = @as(u32, 8);
pub const SE_SIGNING_LEVEL_CUSTOM_4 = @as(u32, 9);
pub const SE_SIGNING_LEVEL_CUSTOM_5 = @as(u32, 10);
pub const SE_SIGNING_LEVEL_DYNAMIC_CODEGEN = @as(u32, 11);
pub const SE_SIGNING_LEVEL_WINDOWS = @as(u32, 12);
pub const SE_SIGNING_LEVEL_CUSTOM_7 = @as(u32, 13);
pub const SE_SIGNING_LEVEL_WINDOWS_TCB = @as(u32, 14);
pub const SE_SIGNING_LEVEL_CUSTOM_6 = @as(u32, 15);
pub const SE_LEARNING_MODE_FLAG_PERMISSIVE = @as(u32, 1);
pub const JOB_OBJECT_ASSIGN_PROCESS = @as(u32, 1);
pub const JOB_OBJECT_SET_ATTRIBUTES = @as(u32, 2);
pub const JOB_OBJECT_QUERY = @as(u32, 4);
pub const JOB_OBJECT_TERMINATE = @as(u32, 8);
pub const JOB_OBJECT_SET_SECURITY_ATTRIBUTES = @as(u32, 16);
pub const JOB_OBJECT_IMPERSONATE = @as(u32, 32);
pub const FLS_MAXIMUM_AVAILABLE = @as(u32, 4080);
pub const TLS_MINIMUM_AVAILABLE = @as(u32, 64);
pub const THREAD_DYNAMIC_CODE_ALLOW = @as(u32, 1);
pub const THREAD_BASE_PRIORITY_LOWRT = @as(u32, 15);
pub const THREAD_BASE_PRIORITY_MAX = @as(u32, 2);
pub const THREAD_BASE_PRIORITY_MIN = @as(i32, -2);
pub const THREAD_BASE_PRIORITY_IDLE = @as(i32, -15);
pub const MEMORY_PRIORITY_LOWEST = @as(u32, 0);
pub const DYNAMIC_EH_CONTINUATION_TARGET_ADD = @as(u32, 1);
pub const DYNAMIC_EH_CONTINUATION_TARGET_PROCESSED = @as(u32, 2);
pub const QUOTA_LIMITS_HARDWS_MIN_ENABLE = @as(u32, 1);
pub const QUOTA_LIMITS_HARDWS_MIN_DISABLE = @as(u32, 2);
pub const QUOTA_LIMITS_HARDWS_MAX_ENABLE = @as(u32, 4);
pub const QUOTA_LIMITS_HARDWS_MAX_DISABLE = @as(u32, 8);
pub const QUOTA_LIMITS_USE_DEFAULT_LIMITS = @as(u32, 16);
pub const MAX_HW_COUNTERS = @as(u32, 16);
pub const THREAD_PROFILING_FLAG_DISPATCH = @as(u32, 1);
pub const JOB_OBJECT_NET_RATE_CONTROL_MAX_DSCP_TAG = @as(u32, 64);
pub const JOB_OBJECT_MSG_END_OF_JOB_TIME = @as(u32, 1);
pub const JOB_OBJECT_MSG_END_OF_PROCESS_TIME = @as(u32, 2);
pub const JOB_OBJECT_MSG_ACTIVE_PROCESS_LIMIT = @as(u32, 3);
pub const JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO = @as(u32, 4);
pub const JOB_OBJECT_MSG_NEW_PROCESS = @as(u32, 6);
pub const JOB_OBJECT_MSG_EXIT_PROCESS = @as(u32, 7);
pub const JOB_OBJECT_MSG_ABNORMAL_EXIT_PROCESS = @as(u32, 8);
pub const JOB_OBJECT_MSG_PROCESS_MEMORY_LIMIT = @as(u32, 9);
pub const JOB_OBJECT_MSG_JOB_MEMORY_LIMIT = @as(u32, 10);
pub const JOB_OBJECT_MSG_NOTIFICATION_LIMIT = @as(u32, 11);
pub const JOB_OBJECT_MSG_JOB_CYCLE_TIME_LIMIT = @as(u32, 12);
pub const JOB_OBJECT_MSG_SILO_TERMINATED = @as(u32, 13);
pub const JOB_OBJECT_MSG_MINIMUM = @as(u32, 1);
pub const JOB_OBJECT_MSG_MAXIMUM = @as(u32, 13);
pub const JOB_OBJECT_UILIMIT_ALL = @as(u32, 255);
pub const JOB_OBJECT_UI_VALID_FLAGS = @as(u32, 255);
pub const JOB_OBJECT_CPU_RATE_CONTROL_MIN_MAX_RATE = @as(u32, 16);
pub const JOB_OBJECT_CPU_RATE_CONTROL_VALID_FLAGS = @as(u32, 31);
pub const EVENT_MODIFY_STATE = @as(u32, 2);
pub const MUTANT_QUERY_STATE = @as(u32, 1);
pub const SEMAPHORE_MODIFY_STATE = @as(u32, 2);
pub const TIMER_QUERY_STATE = @as(u32, 1);
pub const TIMER_MODIFY_STATE = @as(u32, 2);
pub const TIME_ZONE_ID_UNKNOWN = @as(u32, 0);
pub const TIME_ZONE_ID_STANDARD = @as(u32, 1);
pub const TIME_ZONE_ID_DAYLIGHT = @as(u32, 2);
pub const LTP_PC_SMT = @as(u32, 1);
pub const CACHE_FULLY_ASSOCIATIVE = @as(u32, 255);
pub const SYSTEM_CPU_SET_INFORMATION_PARKED = @as(u32, 1);
pub const SYSTEM_CPU_SET_INFORMATION_ALLOCATED = @as(u32, 2);
pub const SYSTEM_CPU_SET_INFORMATION_ALLOCATED_TO_TARGET_PROCESS = @as(u32, 4);
pub const SYSTEM_CPU_SET_INFORMATION_REALTIME = @as(u32, 8);
pub const PROCESSOR_INTEL_386 = @as(u32, 386);
pub const PROCESSOR_INTEL_486 = @as(u32, 486);
pub const PROCESSOR_INTEL_PENTIUM = @as(u32, 586);
pub const PROCESSOR_INTEL_IA64 = @as(u32, 2200);
pub const PROCESSOR_AMD_X8664 = @as(u32, 8664);
pub const PROCESSOR_MIPS_R4000 = @as(u32, 4000);
pub const PROCESSOR_ALPHA_21064 = @as(u32, 21064);
pub const PROCESSOR_PPC_601 = @as(u32, 601);
pub const PROCESSOR_PPC_603 = @as(u32, 603);
pub const PROCESSOR_PPC_604 = @as(u32, 604);
pub const PROCESSOR_PPC_620 = @as(u32, 620);
pub const PROCESSOR_HITACHI_SH3 = @as(u32, 10003);
pub const PROCESSOR_HITACHI_SH3E = @as(u32, 10004);
pub const PROCESSOR_HITACHI_SH4 = @as(u32, 10005);
pub const PROCESSOR_MOTOROLA_821 = @as(u32, 821);
pub const PROCESSOR_SHx_SH3 = @as(u32, 103);
pub const PROCESSOR_SHx_SH4 = @as(u32, 104);
pub const PROCESSOR_STRONGARM = @as(u32, 2577);
pub const PROCESSOR_ARM720 = @as(u32, 1824);
pub const PROCESSOR_ARM820 = @as(u32, 2080);
pub const PROCESSOR_ARM920 = @as(u32, 2336);
pub const PROCESSOR_ARM_7TDMI = @as(u32, 70001);
pub const PROCESSOR_OPTIL = @as(u32, 18767);
pub const PROCESSOR_ARCHITECTURE_MIPS = @as(u32, 1);
pub const PROCESSOR_ARCHITECTURE_ALPHA = @as(u32, 2);
pub const PROCESSOR_ARCHITECTURE_PPC = @as(u32, 3);
pub const PROCESSOR_ARCHITECTURE_SHX = @as(u32, 4);
pub const PROCESSOR_ARCHITECTURE_ALPHA64 = @as(u32, 7);
pub const PROCESSOR_ARCHITECTURE_MSIL = @as(u32, 8);
pub const PROCESSOR_ARCHITECTURE_IA32_ON_WIN64 = @as(u32, 10);
pub const PROCESSOR_ARCHITECTURE_NEUTRAL = @as(u32, 11);
pub const PROCESSOR_ARCHITECTURE_ARM64 = @as(u32, 12);
pub const PROCESSOR_ARCHITECTURE_ARM32_ON_WIN64 = @as(u32, 13);
pub const PROCESSOR_ARCHITECTURE_IA32_ON_ARM64 = @as(u32, 14);
pub const PF_PPC_MOVEMEM_64BIT_OK = @as(u32, 4);
pub const PF_ALPHA_BYTE_INSTRUCTIONS = @as(u32, 5);
pub const PF_SSE_DAZ_MODE_AVAILABLE = @as(u32, 11);
pub const PF_ARM_NEON_INSTRUCTIONS_AVAILABLE = @as(u32, 19);
pub const PF_RDRAND_INSTRUCTION_AVAILABLE = @as(u32, 28);
pub const PF_RDTSCP_INSTRUCTION_AVAILABLE = @as(u32, 32);
pub const PF_RDPID_INSTRUCTION_AVAILABLE = @as(u32, 33);
pub const PF_MONITORX_INSTRUCTION_AVAILABLE = @as(u32, 35);
pub const PF_SSSE3_INSTRUCTIONS_AVAILABLE = @as(u32, 36);
pub const PF_SSE4_1_INSTRUCTIONS_AVAILABLE = @as(u32, 37);
pub const PF_SSE4_2_INSTRUCTIONS_AVAILABLE = @as(u32, 38);
pub const PF_AVX_INSTRUCTIONS_AVAILABLE = @as(u32, 39);
pub const PF_AVX2_INSTRUCTIONS_AVAILABLE = @as(u32, 40);
pub const PF_AVX512F_INSTRUCTIONS_AVAILABLE = @as(u32, 41);
pub const XSTATE_LEGACY_FLOATING_POINT = @as(u32, 0);
pub const XSTATE_LEGACY_SSE = @as(u32, 1);
pub const XSTATE_GSSE = @as(u32, 2);
pub const XSTATE_MPX_BNDREGS = @as(u32, 3);
pub const XSTATE_MPX_BNDCSR = @as(u32, 4);
pub const XSTATE_AVX512_KMASK = @as(u32, 5);
pub const XSTATE_AVX512_ZMM_H = @as(u32, 6);
pub const XSTATE_AVX512_ZMM = @as(u32, 7);
pub const XSTATE_IPT = @as(u32, 8);
pub const XSTATE_CET_U = @as(u32, 11);
pub const XSTATE_LWP = @as(u32, 62);
pub const MAXIMUM_XSTATE_FEATURES = @as(u32, 64);
pub const XSTATE_COMPACTION_ENABLE = @as(u32, 63);
pub const XSTATE_ALIGN_BIT = @as(u32, 1);
pub const XSTATE_CONTROLFLAG_XSAVEOPT_MASK = @as(u32, 1);
pub const XSTATE_CONTROLFLAG_XSAVEC_MASK = @as(u32, 2);
pub const CFG_CALL_TARGET_VALID = @as(u32, 1);
pub const CFG_CALL_TARGET_PROCESSED = @as(u32, 2);
pub const CFG_CALL_TARGET_CONVERT_EXPORT_SUPPRESSED_TO_VALID = @as(u32, 4);
pub const SESSION_QUERY_ACCESS = @as(u32, 1);
pub const SESSION_MODIFY_ACCESS = @as(u32, 2);
pub const MEM_TOP_DOWN = @as(u32, 1048576);
pub const MEM_WRITE_WATCH = @as(u32, 2097152);
pub const MEM_PHYSICAL = @as(u32, 4194304);
pub const MEM_ROTATE = @as(u32, 8388608);
pub const MEM_DIFFERENT_IMAGE_BASE_OK = @as(u32, 8388608);
pub const MEM_4MB_PAGES = @as(u32, 2147483648);
pub const MEM_COALESCE_PLACEHOLDERS = @as(u32, 1);
pub const MEM_EXTENDED_PARAMETER_GRAPHICS = @as(u32, 1);
pub const MEM_EXTENDED_PARAMETER_NONPAGED = @as(u32, 2);
pub const MEM_EXTENDED_PARAMETER_ZERO_PAGES_OPTIONAL = @as(u32, 4);
pub const MEM_EXTENDED_PARAMETER_NONPAGED_LARGE = @as(u32, 8);
pub const MEM_EXTENDED_PARAMETER_NONPAGED_HUGE = @as(u32, 16);
pub const MEM_EXTENDED_PARAMETER_SOFT_FAULT_PAGES = @as(u32, 32);
pub const MEM_EXTENDED_PARAMETER_TYPE_BITS = @as(u32, 8);
pub const WRITE_WATCH_FLAG_RESET = @as(u32, 1);
pub const ENCLAVE_TYPE_SGX = @as(u32, 1);
pub const ENCLAVE_TYPE_SGX2 = @as(u32, 2);
pub const ENCLAVE_TYPE_VBS = @as(u32, 16);
pub const ENCLAVE_VBS_FLAG_DEBUG = @as(u32, 1);
pub const ENCLAVE_TYPE_VBS_BASIC = @as(u32, 17);
pub const VBS_BASIC_PAGE_MEASURED_DATA = @as(u32, 1);
pub const VBS_BASIC_PAGE_UNMEASURED_DATA = @as(u32, 2);
pub const VBS_BASIC_PAGE_ZERO_FILL = @as(u32, 3);
pub const VBS_BASIC_PAGE_THREAD_DESCRIPTOR = @as(u32, 4);
pub const VBS_BASIC_PAGE_SYSTEM_CALL = @as(u32, 5);
pub const TREE_CONNECT_ATTRIBUTE_PRIVACY = @as(u32, 16384);
pub const TREE_CONNECT_ATTRIBUTE_INTEGRITY = @as(u32, 32768);
pub const TREE_CONNECT_ATTRIBUTE_GLOBAL = @as(u32, 4);
pub const TREE_CONNECT_ATTRIBUTE_PINNED = @as(u32, 2);
pub const FILE_ATTRIBUTE_STRICTLY_SEQUENTIAL = @as(u32, 536870912);
pub const MAILSLOT_NO_MESSAGE = @as(u32, 4294967295);
pub const MAILSLOT_WAIT_FOREVER = @as(u32, 4294967295);
pub const FILE_CASE_SENSITIVE_SEARCH = @as(u32, 1);
pub const FILE_CASE_PRESERVED_NAMES = @as(u32, 2);
pub const FILE_UNICODE_ON_DISK = @as(u32, 4);
pub const FILE_PERSISTENT_ACLS = @as(u32, 8);
pub const FILE_FILE_COMPRESSION = @as(u32, 16);
pub const FILE_VOLUME_QUOTAS = @as(u32, 32);
pub const FILE_SUPPORTS_SPARSE_FILES = @as(u32, 64);
pub const FILE_SUPPORTS_REPARSE_POINTS = @as(u32, 128);
pub const FILE_SUPPORTS_REMOTE_STORAGE = @as(u32, 256);
pub const FILE_RETURNS_CLEANUP_RESULT_INFO = @as(u32, 512);
pub const FILE_SUPPORTS_POSIX_UNLINK_RENAME = @as(u32, 1024);
pub const FILE_VOLUME_IS_COMPRESSED = @as(u32, 32768);
pub const FILE_SUPPORTS_OBJECT_IDS = @as(u32, 65536);
pub const FILE_SUPPORTS_ENCRYPTION = @as(u32, 131072);
pub const FILE_NAMED_STREAMS = @as(u32, 262144);
pub const FILE_READ_ONLY_VOLUME = @as(u32, 524288);
pub const FILE_SEQUENTIAL_WRITE_ONCE = @as(u32, 1048576);
pub const FILE_SUPPORTS_TRANSACTIONS = @as(u32, 2097152);
pub const FILE_SUPPORTS_HARD_LINKS = @as(u32, 4194304);
pub const FILE_SUPPORTS_EXTENDED_ATTRIBUTES = @as(u32, 8388608);
pub const FILE_SUPPORTS_OPEN_BY_FILE_ID = @as(u32, 16777216);
pub const FILE_SUPPORTS_USN_JOURNAL = @as(u32, 33554432);
pub const FILE_SUPPORTS_INTEGRITY_STREAMS = @as(u32, 67108864);
pub const FILE_SUPPORTS_BLOCK_REFCOUNTING = @as(u32, 134217728);
pub const FILE_SUPPORTS_SPARSE_VDL = @as(u32, 268435456);
pub const FILE_DAX_VOLUME = @as(u32, 536870912);
pub const FILE_SUPPORTS_GHOSTING = @as(u32, 1073741824);
pub const FILE_CS_FLAG_CASE_SENSITIVE_DIR = @as(u32, 1);
pub const FLUSH_FLAGS_FILE_DATA_ONLY = @as(u32, 1);
pub const FLUSH_FLAGS_NO_SYNC = @as(u32, 2);
pub const FLUSH_FLAGS_FILE_DATA_SYNC_ONLY = @as(u32, 4);
pub const IO_REPARSE_TAG_RESERVED_ZERO = @as(u32, 0);
pub const IO_REPARSE_TAG_RESERVED_ONE = @as(u32, 1);
pub const IO_REPARSE_TAG_RESERVED_TWO = @as(u32, 2);
pub const IO_REPARSE_TAG_MOUNT_POINT = @as(i32, -1610612733);
pub const IO_REPARSE_TAG_HSM = @as(i32, -1073741820);
pub const IO_REPARSE_TAG_HSM2 = @as(i32, -2147483642);
pub const IO_REPARSE_TAG_SIS = @as(i32, -2147483641);
pub const IO_REPARSE_TAG_WIM = @as(i32, -2147483640);
pub const IO_REPARSE_TAG_CSV = @as(i32, -2147483639);
pub const IO_REPARSE_TAG_DFS = @as(i32, -2147483638);
pub const IO_REPARSE_TAG_SYMLINK = @as(i32, -1610612724);
pub const IO_REPARSE_TAG_DFSR = @as(i32, -2147483630);
pub const IO_REPARSE_TAG_DEDUP = @as(i32, -2147483629);
pub const IO_REPARSE_TAG_NFS = @as(i32, -2147483628);
pub const IO_REPARSE_TAG_FILE_PLACEHOLDER = @as(i32, -2147483627);
pub const IO_REPARSE_TAG_WOF = @as(i32, -2147483625);
pub const IO_REPARSE_TAG_WCI = @as(i32, -2147483624);
pub const IO_REPARSE_TAG_WCI_1 = @as(i32, -1879044072);
pub const IO_REPARSE_TAG_GLOBAL_REPARSE = @as(i32, -1610612711);
pub const IO_REPARSE_TAG_CLOUD = @as(i32, -1879048166);
pub const IO_REPARSE_TAG_CLOUD_1 = @as(i32, -1879044070);
pub const IO_REPARSE_TAG_CLOUD_2 = @as(i32, -1879039974);
pub const IO_REPARSE_TAG_CLOUD_3 = @as(i32, -1879035878);
pub const IO_REPARSE_TAG_CLOUD_4 = @as(i32, -1879031782);
pub const IO_REPARSE_TAG_CLOUD_5 = @as(i32, -1879027686);
pub const IO_REPARSE_TAG_CLOUD_6 = @as(i32, -1879023590);
pub const IO_REPARSE_TAG_CLOUD_7 = @as(i32, -1879019494);
pub const IO_REPARSE_TAG_CLOUD_8 = @as(i32, -1879015398);
pub const IO_REPARSE_TAG_CLOUD_9 = @as(i32, -1879011302);
pub const IO_REPARSE_TAG_CLOUD_A = @as(i32, -1879007206);
pub const IO_REPARSE_TAG_CLOUD_B = @as(i32, -1879003110);
pub const IO_REPARSE_TAG_CLOUD_C = @as(i32, -1878999014);
pub const IO_REPARSE_TAG_CLOUD_D = @as(i32, -1878994918);
pub const IO_REPARSE_TAG_CLOUD_E = @as(i32, -1878990822);
pub const IO_REPARSE_TAG_CLOUD_F = @as(i32, -1878986726);
pub const IO_REPARSE_TAG_CLOUD_MASK = @as(i32, 61440);
pub const IO_REPARSE_TAG_APPEXECLINK = @as(i32, -2147483621);
pub const IO_REPARSE_TAG_PROJFS = @as(i32, -1879048164);
pub const IO_REPARSE_TAG_STORAGE_SYNC = @as(i32, -2147483618);
pub const IO_REPARSE_TAG_WCI_TOMBSTONE = @as(i32, -1610612705);
pub const IO_REPARSE_TAG_UNHANDLED = @as(i32, -2147483616);
pub const IO_REPARSE_TAG_ONEDRIVE = @as(i32, -2147483615);
pub const IO_REPARSE_TAG_PROJFS_TOMBSTONE = @as(i32, -1610612702);
pub const IO_REPARSE_TAG_AF_UNIX = @as(i32, -2147483613);
pub const IO_REPARSE_TAG_WCI_LINK = @as(i32, -1610612697);
pub const IO_REPARSE_TAG_WCI_LINK_1 = @as(i32, -1610608601);
pub const SCRUB_DATA_INPUT_FLAG_RESUME = @as(u32, 1);
pub const SCRUB_DATA_INPUT_FLAG_SKIP_IN_SYNC = @as(u32, 2);
pub const SCRUB_DATA_INPUT_FLAG_SKIP_NON_INTEGRITY_DATA = @as(u32, 4);
pub const SCRUB_DATA_INPUT_FLAG_IGNORE_REDUNDANCY = @as(u32, 8);
pub const SCRUB_DATA_INPUT_FLAG_SKIP_DATA = @as(u32, 16);
pub const SCRUB_DATA_INPUT_FLAG_SCRUB_BY_OBJECT_ID = @as(u32, 32);
pub const SCRUB_DATA_INPUT_FLAG_OPLOCK_NOT_ACQUIRED = @as(u32, 64);
pub const SCRUB_DATA_OUTPUT_FLAG_INCOMPLETE = @as(u32, 1);
pub const SCRUB_DATA_OUTPUT_FLAG_NON_USER_DATA_RANGE = @as(u32, 65536);
pub const SCRUB_DATA_OUTPUT_FLAG_PARITY_EXTENT_DATA_RETURNED = @as(u32, 131072);
pub const SCRUB_DATA_OUTPUT_FLAG_RESUME_CONTEXT_LENGTH_SPECIFIED = @as(u32, 262144);
pub const SHUFFLE_FILE_FLAG_SKIP_INITIALIZING_NEW_CLUSTERS = @as(u32, 1);
pub const IO_COMPLETION_MODIFY_STATE = @as(u32, 2);
pub const NETWORK_APP_INSTANCE_CSV_FLAGS_VALID_ONLY_IF_CSV_COORDINATOR = @as(u32, 1);
pub const GUID_MAX_POWER_SAVINGS = Guid.initString("a1841308-3541-4fab-bc81-f71556f20b4a");
pub const GUID_MIN_POWER_SAVINGS = Guid.initString("8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c");
pub const GUID_TYPICAL_POWER_SAVINGS = Guid.initString("381b4222-f694-41f0-9685-ff5bb260df2e");
pub const NO_SUBGROUP_GUID = Guid.initString("fea3413e-7e05-4911-9a71-700331f1c294");
pub const ALL_POWERSCHEMES_GUID = Guid.initString("68a1e95e-13ea-41e1-8011-0c496ca490b0");
pub const GUID_POWERSCHEME_PERSONALITY = Guid.initString("245d8541-3943-4422-b025-13a784f679b7");
pub const GUID_ACTIVE_POWERSCHEME = Guid.initString("31f9f286-5084-42fe-b720-2b0264993763");
pub const GUID_IDLE_RESILIENCY_SUBGROUP = Guid.initString("2e601130-5351-4d9d-8e04-252966bad054");
pub const GUID_IDLE_RESILIENCY_PERIOD = Guid.initString("c42b79aa-aa3a-484b-a98f-2cf32aa90a28");
pub const GUID_DEEP_SLEEP_ENABLED = Guid.initString("d502f7ee-1dc7-4efd-a55d-f04b6f5c0545");
pub const GUID_DEEP_SLEEP_PLATFORM_STATE = Guid.initString("d23f2fb8-9536-4038-9c94-1ce02e5c2152");
pub const GUID_DISK_COALESCING_POWERDOWN_TIMEOUT = Guid.initString("c36f0eb4-2988-4a70-8eee-0884fc2c2433");
pub const GUID_EXECUTION_REQUIRED_REQUEST_TIMEOUT = Guid.initString("3166bc41-7e98-4e03-b34e-ec0f5f2b218e");
pub const GUID_VIDEO_SUBGROUP = Guid.initString("7516b95f-f776-4464-8c53-06167f40cc99");
pub const GUID_VIDEO_POWERDOWN_TIMEOUT = Guid.initString("3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e");
pub const GUID_VIDEO_ANNOYANCE_TIMEOUT = Guid.initString("82dbcf2d-cd67-40c5-bfdc-9f1a5ccd4663");
pub const GUID_VIDEO_ADAPTIVE_PERCENT_INCREASE = Guid.initString("eed904df-b142-4183-b10b-5a1197a37864");
pub const GUID_VIDEO_DIM_TIMEOUT = Guid.initString("17aaa29b-8b43-4b94-aafe-35f64daaf1ee");
pub const GUID_VIDEO_ADAPTIVE_POWERDOWN = Guid.initString("90959d22-d6a1-49b9-af93-bce885ad335b");
pub const GUID_MONITOR_POWER_ON = Guid.initString("02731015-4510-4526-99e6-e5a17ebd1aea");
pub const GUID_DEVICE_POWER_POLICY_VIDEO_BRIGHTNESS = Guid.initString("aded5e82-b909-4619-9949-f5d71dac0bcb");
pub const GUID_DEVICE_POWER_POLICY_VIDEO_DIM_BRIGHTNESS = Guid.initString("f1fbfde2-a960-4165-9f88-50667911ce96");
pub const GUID_VIDEO_CURRENT_MONITOR_BRIGHTNESS = Guid.initString("8ffee2c6-2d01-46be-adb9-398addc5b4ff");
pub const GUID_VIDEO_ADAPTIVE_DISPLAY_BRIGHTNESS = Guid.initString("fbd9aa66-9553-4097-ba44-ed6e9d65eab8");
pub const GUID_CONSOLE_DISPLAY_STATE = Guid.initString("6fe69556-704a-47a0-8f24-c28d936fda47");
pub const GUID_ALLOW_DISPLAY_REQUIRED = Guid.initString("a9ceb8da-cd46-44fb-a98b-02af69de4623");
pub const GUID_VIDEO_CONSOLE_LOCK_TIMEOUT = Guid.initString("8ec4b3a5-6868-48c2-be75-4f3044be88a7");
pub const GUID_ADVANCED_COLOR_QUALITY_BIAS = Guid.initString("684c3e69-a4f7-4014-8754-d45179a56167");
pub const GUID_ADAPTIVE_POWER_BEHAVIOR_SUBGROUP = Guid.initString("8619b916-e004-4dd8-9b66-dae86f806698");
pub const GUID_NON_ADAPTIVE_INPUT_TIMEOUT = Guid.initString("5adbbfbc-074e-4da1-ba38-db8b36b2c8f3");
pub const GUID_ADAPTIVE_INPUT_CONTROLLER_STATE = Guid.initString("0e98fae9-f45a-4de1-a757-6031f197f6ea");
pub const GUID_DISK_SUBGROUP = Guid.initString("0012ee47-9041-4b5d-9b77-535fba8b1442");
pub const GUID_DISK_MAX_POWER = Guid.initString("51dea550-bb38-4bc4-991b-eacf37be5ec8");
pub const GUID_DISK_POWERDOWN_TIMEOUT = Guid.initString("6738e2c4-e8a5-4a42-b16a-e040e769756e");
pub const GUID_DISK_IDLE_TIMEOUT = Guid.initString("58e39ba8-b8e6-4ef6-90d0-89ae32b258d6");
pub const GUID_DISK_BURST_IGNORE_THRESHOLD = Guid.initString("80e3c60e-bb94-4ad8-bbe0-0d3195efc663");
pub const GUID_DISK_ADAPTIVE_POWERDOWN = Guid.initString("396a32e1-499a-40b2-9124-a96afe707667");
pub const GUID_DISK_NVME_NOPPME = Guid.initString("fc7372b6-ab2d-43ee-8797-15e9841f2cca");
pub const GUID_SLEEP_SUBGROUP = Guid.initString("238c9fa8-0aad-41ed-83f4-97be242c8f20");
pub const GUID_SLEEP_IDLE_THRESHOLD = Guid.initString("81cd32e0-7833-44f3-8737-7081f38d1f70");
pub const GUID_STANDBY_TIMEOUT = Guid.initString("29f6c1db-86da-48c5-9fdb-f2b67b1f44da");
pub const GUID_UNATTEND_SLEEP_TIMEOUT = Guid.initString("7bc4a2f9-d8fc-4469-b07b-33eb785aaca0");
pub const GUID_HIBERNATE_TIMEOUT = Guid.initString("9d7815a6-7ee4-497e-8888-515a05f02364");
pub const GUID_HIBERNATE_FASTS4_POLICY = Guid.initString("94ac6d29-73ce-41a6-809f-6363ba21b47e");
pub const GUID_CRITICAL_POWER_TRANSITION = Guid.initString("b7a27025-e569-46c2-a504-2b96cad225a1");
pub const GUID_SYSTEM_AWAYMODE = Guid.initString("98a7f580-01f7-48aa-9c0f-44352c29e5c0");
pub const GUID_ALLOW_AWAYMODE = Guid.initString("25dfa149-5dd1-4736-b5ab-e8a37b5b8187");
pub const GUID_USER_PRESENCE_PREDICTION = Guid.initString("82011705-fb95-4d46-8d35-4042b1d20def");
pub const GUID_STANDBY_BUDGET_GRACE_PERIOD = Guid.initString("60c07fe1-0556-45cf-9903-d56e32210242");
pub const GUID_STANDBY_BUDGET_PERCENT = Guid.initString("9fe527be-1b70-48da-930d-7bcf17b44990");
pub const GUID_STANDBY_RESERVE_GRACE_PERIOD = Guid.initString("c763ee92-71e8-4127-84eb-f6ed043a3e3d");
pub const GUID_STANDBY_RESERVE_TIME = Guid.initString("468fe7e5-1158-46ec-88bc-5b96c9e44fd0");
pub const GUID_STANDBY_RESET_PERCENT = Guid.initString("49cb11a5-56e2-4afb-9d38-3df47872e21b");
pub const GUID_ALLOW_STANDBY_STATES = Guid.initString("abfc2519-3608-4c2a-94ea-171b0ed546ab");
pub const GUID_ALLOW_RTC_WAKE = Guid.initString("bd3b718a-0680-4d9d-8ab2-e1d2b4ac806d");
pub const GUID_LEGACY_RTC_MITIGATION = Guid.initString("1a34bdc3-7e6b-442e-a9d0-64b6ef378e84");
pub const GUID_ALLOW_SYSTEM_REQUIRED = Guid.initString("a4b195f5-8225-47d8-8012-9d41369786e2");
pub const GUID_POWER_SAVING_STATUS = Guid.initString("e00958c0-c213-4ace-ac77-fecced2eeea5");
pub const GUID_ENERGY_SAVER_SUBGROUP = Guid.initString("de830923-a562-41af-a086-e3a2c6bad2da");
pub const GUID_ENERGY_SAVER_BATTERY_THRESHOLD = Guid.initString("e69653ca-cf7f-4f05-aa73-cb833fa90ad4");
pub const GUID_ENERGY_SAVER_BRIGHTNESS = Guid.initString("13d09884-f74e-474a-a852-b6bde8ad03a8");
pub const GUID_ENERGY_SAVER_POLICY = Guid.initString("5c5bb349-ad29-4ee2-9d0b-2b25270f7a81");
pub const GUID_SYSTEM_BUTTON_SUBGROUP = Guid.initString("4f971e89-eebd-4455-a8de-9e59040e7347");
pub const POWERBUTTON_ACTION_INDEX_NOTHING = @as(u32, 0);
pub const POWERBUTTON_ACTION_INDEX_SLEEP = @as(u32, 1);
pub const POWERBUTTON_ACTION_INDEX_HIBERNATE = @as(u32, 2);
pub const POWERBUTTON_ACTION_INDEX_SHUTDOWN = @as(u32, 3);
pub const POWERBUTTON_ACTION_INDEX_TURN_OFF_THE_DISPLAY = @as(u32, 4);
pub const POWERBUTTON_ACTION_VALUE_NOTHING = @as(u32, 0);
pub const POWERBUTTON_ACTION_VALUE_SLEEP = @as(u32, 2);
pub const POWERBUTTON_ACTION_VALUE_HIBERNATE = @as(u32, 3);
pub const POWERBUTTON_ACTION_VALUE_SHUTDOWN = @as(u32, 6);
pub const POWERBUTTON_ACTION_VALUE_TURN_OFF_THE_DISPLAY = @as(u32, 8);
pub const GUID_POWERBUTTON_ACTION = Guid.initString("7648efa3-dd9c-4e3e-b566-50f929386280");
pub const GUID_SLEEPBUTTON_ACTION = Guid.initString("96996bc0-ad50-47ec-923b-6f41874dd9eb");
pub const GUID_USERINTERFACEBUTTON_ACTION = Guid.initString("a7066653-8d6c-40a8-910e-a1f54b84c7e5");
pub const GUID_LIDCLOSE_ACTION = Guid.initString("5ca83367-6e45-459f-a27b-476b1d01c936");
pub const GUID_LIDOPEN_POWERSTATE = Guid.initString("99ff10e7-23b1-4c07-a9d1-5c3206d741b4");
pub const GUID_BATTERY_SUBGROUP = Guid.initString("e73a048d-bf27-4f12-9731-8b2076e8891f");
pub const GUID_BATTERY_DISCHARGE_ACTION_0 = Guid.initString("637ea02f-bbcb-4015-8e2c-a1c7b9c0b546");
pub const GUID_BATTERY_DISCHARGE_LEVEL_0 = Guid.initString("9a66d8d7-4ff7-4ef9-b5a2-5a326ca2a469");
pub const GUID_BATTERY_DISCHARGE_FLAGS_0 = Guid.initString("5dbb7c9f-38e9-40d2-9749-4f8a0e9f640f");
pub const GUID_BATTERY_DISCHARGE_ACTION_1 = Guid.initString("d8742dcb-3e6a-4b3c-b3fe-374623cdcf06");
pub const GUID_BATTERY_DISCHARGE_LEVEL_1 = Guid.initString("8183ba9a-e910-48da-8769-14ae6dc1170a");
pub const GUID_BATTERY_DISCHARGE_FLAGS_1 = Guid.initString("bcded951-187b-4d05-bccc-f7e51960c258");
pub const GUID_BATTERY_DISCHARGE_ACTION_2 = Guid.initString("421cba38-1a8e-4881-ac89-e33a8b04ece4");
pub const GUID_BATTERY_DISCHARGE_LEVEL_2 = Guid.initString("07a07ca2-adaf-40d7-b077-533aaded1bfa");
pub const GUID_BATTERY_DISCHARGE_FLAGS_2 = Guid.initString("7fd2f0c4-feb7-4da3-8117-e3fbedc46582");
pub const GUID_BATTERY_DISCHARGE_ACTION_3 = Guid.initString("80472613-9780-455e-b308-72d3003cf2f8");
pub const GUID_BATTERY_DISCHARGE_LEVEL_3 = Guid.initString("58afd5a6-c2dd-47d2-9fbf-ef70cc5c5965");
pub const GUID_BATTERY_DISCHARGE_FLAGS_3 = Guid.initString("73613ccf-dbfa-4279-8356-4935f6bf62f3");
pub const GUID_PROCESSOR_SETTINGS_SUBGROUP = Guid.initString("54533251-82be-4824-96c1-47b60b740d00");
pub const GUID_PROCESSOR_THROTTLE_POLICY = Guid.initString("57027304-4af6-4104-9260-e3d95248fc36");
pub const PERFSTATE_POLICY_CHANGE_IDEAL = @as(u32, 0);
pub const PERFSTATE_POLICY_CHANGE_SINGLE = @as(u32, 1);
pub const PERFSTATE_POLICY_CHANGE_ROCKET = @as(u32, 2);
pub const PERFSTATE_POLICY_CHANGE_IDEAL_AGGRESSIVE = @as(u32, 3);
pub const GUID_PROCESSOR_THROTTLE_MAXIMUM = Guid.initString("bc5038f7-23e0-4960-96da-33abaf5935ec");
pub const GUID_PROCESSOR_THROTTLE_MAXIMUM_1 = Guid.initString("bc5038f7-23e0-4960-96da-33abaf5935ed");
pub const GUID_PROCESSOR_THROTTLE_MINIMUM = Guid.initString("893dee8e-2bef-41e0-89c6-b55d0929964c");
pub const GUID_PROCESSOR_THROTTLE_MINIMUM_1 = Guid.initString("893dee8e-2bef-41e0-89c6-b55d0929964d");
pub const GUID_PROCESSOR_FREQUENCY_LIMIT = Guid.initString("75b0ae3f-bce0-45a7-8c89-c9611c25e100");
pub const GUID_PROCESSOR_FREQUENCY_LIMIT_1 = Guid.initString("75b0ae3f-bce0-45a7-8c89-c9611c25e101");
pub const GUID_PROCESSOR_ALLOW_THROTTLING = Guid.initString("3b04d4fd-1cc7-4f23-ab1c-d1337819c4bb");
pub const PROCESSOR_THROTTLE_DISABLED = @as(u32, 0);
pub const PROCESSOR_THROTTLE_ENABLED = @as(u32, 1);
pub const PROCESSOR_THROTTLE_AUTOMATIC = @as(u32, 2);
pub const GUID_PROCESSOR_IDLESTATE_POLICY = Guid.initString("68f262a7-f621-4069-b9a5-4874169be23c");
pub const GUID_PROCESSOR_PERFSTATE_POLICY = Guid.initString("bbdc3814-18e9-4463-8a55-d197327c45c0");
pub const GUID_PROCESSOR_PERF_INCREASE_THRESHOLD = Guid.initString("06cadf0e-64ed-448a-8927-ce7bf90eb35d");
pub const GUID_PROCESSOR_PERF_INCREASE_THRESHOLD_1 = Guid.initString("06cadf0e-64ed-448a-8927-ce7bf90eb35e");
pub const GUID_PROCESSOR_PERF_DECREASE_THRESHOLD = Guid.initString("12a0ab44-fe28-4fa9-b3bd-4b64f44960a6");
pub const GUID_PROCESSOR_PERF_DECREASE_THRESHOLD_1 = Guid.initString("12a0ab44-fe28-4fa9-b3bd-4b64f44960a7");
pub const GUID_PROCESSOR_PERF_INCREASE_POLICY = Guid.initString("465e1f50-b610-473a-ab58-00d1077dc418");
pub const GUID_PROCESSOR_PERF_INCREASE_POLICY_1 = Guid.initString("465e1f50-b610-473a-ab58-00d1077dc419");
pub const GUID_PROCESSOR_PERF_DECREASE_POLICY = Guid.initString("40fbefc7-2e9d-4d25-a185-0cfd8574bac6");
pub const GUID_PROCESSOR_PERF_DECREASE_POLICY_1 = Guid.initString("40fbefc7-2e9d-4d25-a185-0cfd8574bac7");
pub const GUID_PROCESSOR_PERF_INCREASE_TIME = Guid.initString("984cf492-3bed-4488-a8f9-4286c97bf5aa");
pub const GUID_PROCESSOR_PERF_INCREASE_TIME_1 = Guid.initString("984cf492-3bed-4488-a8f9-4286c97bf5ab");
pub const GUID_PROCESSOR_PERF_DECREASE_TIME = Guid.initString("d8edeb9b-95cf-4f95-a73c-b061973693c8");
pub const GUID_PROCESSOR_PERF_DECREASE_TIME_1 = Guid.initString("d8edeb9b-95cf-4f95-a73c-b061973693c9");
pub const GUID_PROCESSOR_PERF_TIME_CHECK = Guid.initString("4d2b0152-7d5c-498b-88e2-34345392a2c5");
pub const GUID_PROCESSOR_PERF_BOOST_POLICY = Guid.initString("45bcc044-d885-43e2-8605-ee0ec6e96b59");
pub const PROCESSOR_PERF_BOOST_POLICY_DISABLED = @as(u32, 0);
pub const PROCESSOR_PERF_BOOST_POLICY_MAX = @as(u32, 100);
pub const GUID_PROCESSOR_PERF_BOOST_MODE = Guid.initString("be337238-0d82-4146-a960-4f3749d470c7");
pub const PROCESSOR_PERF_BOOST_MODE_DISABLED = @as(u32, 0);
pub const PROCESSOR_PERF_BOOST_MODE_ENABLED = @as(u32, 1);
pub const PROCESSOR_PERF_BOOST_MODE_AGGRESSIVE = @as(u32, 2);
pub const PROCESSOR_PERF_BOOST_MODE_EFFICIENT_ENABLED = @as(u32, 3);
pub const PROCESSOR_PERF_BOOST_MODE_EFFICIENT_AGGRESSIVE = @as(u32, 4);
pub const PROCESSOR_PERF_BOOST_MODE_AGGRESSIVE_AT_GUARANTEED = @as(u32, 5);
pub const PROCESSOR_PERF_BOOST_MODE_EFFICIENT_AGGRESSIVE_AT_GUARANTEED = @as(u32, 6);
pub const GUID_PROCESSOR_PERF_AUTONOMOUS_MODE = Guid.initString("8baa4a8a-14c6-4451-8e8b-14bdbd197537");
pub const PROCESSOR_PERF_AUTONOMOUS_MODE_DISABLED = @as(u32, 0);
pub const PROCESSOR_PERF_AUTONOMOUS_MODE_ENABLED = @as(u32, 1);
pub const GUID_PROCESSOR_PERF_ENERGY_PERFORMANCE_PREFERENCE = Guid.initString("36687f9e-e3a5-4dbf-b1dc-15eb381c6863");
pub const GUID_PROCESSOR_PERF_ENERGY_PERFORMANCE_PREFERENCE_1 = Guid.initString("36687f9e-e3a5-4dbf-b1dc-15eb381c6864");
pub const PROCESSOR_PERF_PERFORMANCE_PREFERENCE = @as(u32, 255);
pub const PROCESSOR_PERF_ENERGY_PREFERENCE = @as(u32, 0);
pub const GUID_PROCESSOR_PERF_AUTONOMOUS_ACTIVITY_WINDOW = Guid.initString("cfeda3d0-7697-4566-a922-a9086cd49dfa");
pub const PROCESSOR_PERF_MINIMUM_ACTIVITY_WINDOW = @as(u32, 0);
pub const PROCESSOR_PERF_MAXIMUM_ACTIVITY_WINDOW = @as(u32, 1270000000);
pub const GUID_PROCESSOR_DUTY_CYCLING = Guid.initString("4e4450b3-6179-4e91-b8f1-5bb9938f81a1");
pub const PROCESSOR_DUTY_CYCLING_DISABLED = @as(u32, 0);
pub const PROCESSOR_DUTY_CYCLING_ENABLED = @as(u32, 1);
pub const GUID_PROCESSOR_IDLE_ALLOW_SCALING = Guid.initString("6c2993b0-8f48-481f-bcc6-00dd2742aa06");
pub const GUID_PROCESSOR_IDLE_DISABLE = Guid.initString("5d76a2ca-e8c0-402f-a133-2158492d58ad");
pub const GUID_PROCESSOR_IDLE_STATE_MAXIMUM = Guid.initString("9943e905-9a30-4ec1-9b99-44dd3b76f7a2");
pub const GUID_PROCESSOR_IDLE_TIME_CHECK = Guid.initString("c4581c31-89ab-4597-8e2b-9c9cab440e6b");
pub const GUID_PROCESSOR_IDLE_DEMOTE_THRESHOLD = Guid.initString("4b92d758-5a24-4851-a470-815d78aee119");
pub const GUID_PROCESSOR_IDLE_PROMOTE_THRESHOLD = Guid.initString("7b224883-b3cc-4d79-819f-8374152cbe7c");
pub const GUID_PROCESSOR_CORE_PARKING_INCREASE_THRESHOLD = Guid.initString("df142941-20f3-4edf-9a4a-9c83d3d717d1");
pub const GUID_PROCESSOR_CORE_PARKING_DECREASE_THRESHOLD = Guid.initString("68dd2f27-a4ce-4e11-8487-3794e4135dfa");
pub const GUID_PROCESSOR_CORE_PARKING_INCREASE_POLICY = Guid.initString("c7be0679-2817-4d69-9d02-519a537ed0c6");
pub const CORE_PARKING_POLICY_CHANGE_IDEAL = @as(u32, 0);
pub const CORE_PARKING_POLICY_CHANGE_SINGLE = @as(u32, 1);
pub const CORE_PARKING_POLICY_CHANGE_ROCKET = @as(u32, 2);
pub const CORE_PARKING_POLICY_CHANGE_MULTISTEP = @as(u32, 3);
pub const GUID_PROCESSOR_CORE_PARKING_DECREASE_POLICY = Guid.initString("71021b41-c749-4d21-be74-a00f335d582b");
pub const GUID_PROCESSOR_CORE_PARKING_MAX_CORES = Guid.initString("ea062031-0e34-4ff1-9b6d-eb1059334028");
pub const GUID_PROCESSOR_CORE_PARKING_MAX_CORES_1 = Guid.initString("ea062031-0e34-4ff1-9b6d-eb1059334029");
pub const GUID_PROCESSOR_CORE_PARKING_MIN_CORES = Guid.initString("0cc5b647-c1df-4637-891a-dec35c318583");
pub const GUID_PROCESSOR_CORE_PARKING_MIN_CORES_1 = Guid.initString("0cc5b647-c1df-4637-891a-dec35c318584");
pub const GUID_PROCESSOR_CORE_PARKING_INCREASE_TIME = Guid.initString("2ddd5a84-5a71-437e-912a-db0b8c788732");
pub const GUID_PROCESSOR_CORE_PARKING_DECREASE_TIME = Guid.initString("dfd10d17-d5eb-45dd-877a-9a34ddd15c82");
pub const GUID_PROCESSOR_CORE_PARKING_AFFINITY_HISTORY_DECREASE_FACTOR = Guid.initString("8f7b45e3-c393-480a-878c-f67ac3d07082");
pub const GUID_PROCESSOR_CORE_PARKING_AFFINITY_HISTORY_THRESHOLD = Guid.initString("5b33697b-e89d-4d38-aa46-9e7dfb7cd2f9");
pub const GUID_PROCESSOR_CORE_PARKING_AFFINITY_WEIGHTING = Guid.initString("e70867f1-fa2f-4f4e-aea1-4d8a0ba23b20");
pub const GUID_PROCESSOR_CORE_PARKING_OVER_UTILIZATION_HISTORY_DECREASE_FACTOR = Guid.initString("1299023c-bc28-4f0a-81ec-d3295a8d815d");
pub const GUID_PROCESSOR_CORE_PARKING_OVER_UTILIZATION_HISTORY_THRESHOLD = Guid.initString("9ac18e92-aa3c-4e27-b307-01ae37307129");
pub const GUID_PROCESSOR_CORE_PARKING_OVER_UTILIZATION_WEIGHTING = Guid.initString("8809c2d8-b155-42d4-bcda-0d345651b1db");
pub const GUID_PROCESSOR_CORE_PARKING_OVER_UTILIZATION_THRESHOLD = Guid.initString("943c8cb6-6f93-4227-ad87-e9a3feec08d1");
pub const GUID_PROCESSOR_PARKING_CORE_OVERRIDE = Guid.initString("a55612aa-f624-42c6-a443-7397d064c04f");
pub const GUID_PROCESSOR_PARKING_PERF_STATE = Guid.initString("447235c7-6a8d-4cc0-8e24-9eaf70b96e2b");
pub const GUID_PROCESSOR_PARKING_PERF_STATE_1 = Guid.initString("447235c7-6a8d-4cc0-8e24-9eaf70b96e2c");
pub const GUID_PROCESSOR_PARKING_CONCURRENCY_THRESHOLD = Guid.initString("2430ab6f-a520-44a2-9601-f7f23b5134b1");
pub const GUID_PROCESSOR_PARKING_HEADROOM_THRESHOLD = Guid.initString("f735a673-2066-4f80-a0c5-ddee0cf1bf5d");
pub const GUID_PROCESSOR_PARKING_DISTRIBUTION_THRESHOLD = Guid.initString("4bdaf4e9-d103-46d7-a5f0-6280121616ef");
pub const GUID_PROCESSOR_SOFT_PARKING_LATENCY = Guid.initString("97cfac41-2217-47eb-992d-618b1977c907");
pub const GUID_PROCESSOR_PERF_HISTORY = Guid.initString("7d24baa7-0b84-480f-840c-1b0743c00f5f");
pub const GUID_PROCESSOR_PERF_HISTORY_1 = Guid.initString("7d24baa7-0b84-480f-840c-1b0743c00f60");
pub const GUID_PROCESSOR_PERF_INCREASE_HISTORY = Guid.initString("99b3ef01-752f-46a1-80fb-7730011f2354");
pub const GUID_PROCESSOR_PERF_DECREASE_HISTORY = Guid.initString("0300f6f8-abd6-45a9-b74f-4908691a40b5");
pub const GUID_PROCESSOR_PERF_CORE_PARKING_HISTORY = Guid.initString("77d7f282-8f1a-42cd-8537-45450a839be8");
pub const GUID_PROCESSOR_PERF_LATENCY_HINT = Guid.initString("0822df31-9c83-441c-a079-0de4cf009c7b");
pub const GUID_PROCESSOR_PERF_LATENCY_HINT_PERF = Guid.initString("619b7505-003b-4e82-b7a6-4dd29c300971");
pub const GUID_PROCESSOR_PERF_LATENCY_HINT_PERF_1 = Guid.initString("619b7505-003b-4e82-b7a6-4dd29c300972");
pub const GUID_PROCESSOR_LATENCY_HINT_MIN_UNPARK = Guid.initString("616cdaa5-695e-4545-97ad-97dc2d1bdd88");
pub const GUID_PROCESSOR_LATENCY_HINT_MIN_UNPARK_1 = Guid.initString("616cdaa5-695e-4545-97ad-97dc2d1bdd89");
pub const GUID_PROCESSOR_DISTRIBUTE_UTILITY = Guid.initString("e0007330-f589-42ed-a401-5ddb10e785d3");
pub const GUID_PROCESSOR_HETEROGENEOUS_POLICY = Guid.initString("7f2f5cfa-f10c-4823-b5e1-e93ae85f46b5");
pub const GUID_PROCESSOR_HETERO_DECREASE_TIME = Guid.initString("7f2492b6-60b1-45e5-ae55-773f8cd5caec");
pub const GUID_PROCESSOR_HETERO_INCREASE_TIME = Guid.initString("4009efa7-e72d-4cba-9edf-91084ea8cbc3");
pub const GUID_PROCESSOR_HETERO_DECREASE_THRESHOLD = Guid.initString("f8861c27-95e7-475c-865b-13c0cb3f9d6b");
pub const GUID_PROCESSOR_HETERO_INCREASE_THRESHOLD = Guid.initString("b000397d-9b0b-483d-98c9-692a6060cfbf");
pub const GUID_PROCESSOR_CLASS0_FLOOR_PERF = Guid.initString("fddc842b-8364-4edc-94cf-c17f60de1c80");
pub const GUID_PROCESSOR_CLASS1_INITIAL_PERF = Guid.initString("1facfc65-a930-4bc5-9f38-504ec097bbc0");
pub const GUID_PROCESSOR_THREAD_SCHEDULING_POLICY = Guid.initString("93b8b6dc-0698-4d1c-9ee4-0644e900c85d");
pub const GUID_PROCESSOR_SHORT_THREAD_SCHEDULING_POLICY = Guid.initString("bae08b81-2d5e-4688-ad6a-13243356654b");
pub const GUID_SYSTEM_COOLING_POLICY = Guid.initString("94d3a615-a899-4ac5-ae2b-e4d8f634367f");
pub const GUID_PROCESSOR_RESPONSIVENESS_DISABLE_THRESHOLD = Guid.initString("38b8383d-cce0-4c79-9e3e-56a4f17cc480");
pub const GUID_PROCESSOR_RESPONSIVENESS_DISABLE_THRESHOLD_1 = Guid.initString("38b8383d-cce0-4c79-9e3e-56a4f17cc481");
pub const GUID_PROCESSOR_RESPONSIVENESS_ENABLE_THRESHOLD = Guid.initString("3d44e256-7222-4415-a9ed-9c45fa3dd830");
pub const GUID_PROCESSOR_RESPONSIVENESS_ENABLE_THRESHOLD_1 = Guid.initString("3d44e256-7222-4415-a9ed-9c45fa3dd831");
pub const GUID_PROCESSOR_RESPONSIVENESS_DISABLE_TIME = Guid.initString("f565999f-3fb0-411a-a226-3f0198dec130");
pub const GUID_PROCESSOR_RESPONSIVENESS_DISABLE_TIME_1 = Guid.initString("f565999f-3fb0-411a-a226-3f0198dec131");
pub const GUID_PROCESSOR_RESPONSIVENESS_ENABLE_TIME = Guid.initString("3d915188-7830-49ae-a79a-0fb0a1e5a200");
pub const GUID_PROCESSOR_RESPONSIVENESS_ENABLE_TIME_1 = Guid.initString("3d915188-7830-49ae-a79a-0fb0a1e5a201");
pub const GUID_PROCESSOR_RESPONSIVENESS_EPP_CEILING = Guid.initString("4427c73b-9756-4a5c-b84b-c7bda79c7320");
pub const GUID_PROCESSOR_RESPONSIVENESS_EPP_CEILING_1 = Guid.initString("4427c73b-9756-4a5c-b84b-c7bda79c7321");
pub const GUID_PROCESSOR_RESPONSIVENESS_PERF_FLOOR = Guid.initString("ce8e92ee-6a86-4572-bfe0-20c21d03cd40");
pub const GUID_PROCESSOR_RESPONSIVENESS_PERF_FLOOR_1 = Guid.initString("ce8e92ee-6a86-4572-bfe0-20c21d03cd41");
pub const GUID_LOCK_CONSOLE_ON_WAKE = Guid.initString("0e796bdb-100d-47d6-a2d5-f7d2daa51f51");
pub const GUID_DEVICE_IDLE_POLICY = Guid.initString("4faab71a-92e5-4726-b531-224559672d19");
pub const POWER_DEVICE_IDLE_POLICY_PERFORMANCE = @as(u32, 0);
pub const POWER_DEVICE_IDLE_POLICY_CONSERVATIVE = @as(u32, 1);
pub const GUID_CONNECTIVITY_IN_STANDBY = Guid.initString("f15576e8-98b7-4186-b944-eafa664402d9");
pub const POWER_CONNECTIVITY_IN_STANDBY_DISABLED = @as(u32, 0);
pub const POWER_CONNECTIVITY_IN_STANDBY_ENABLED = @as(u32, 1);
pub const POWER_CONNECTIVITY_IN_STANDBY_SYSTEM_MANAGED = @as(u32, 2);
pub const GUID_DISCONNECTED_STANDBY_MODE = Guid.initString("68afb2d9-ee95-47a8-8f50-4115088073b1");
pub const POWER_DISCONNECTED_STANDBY_MODE_NORMAL = @as(u32, 0);
pub const POWER_DISCONNECTED_STANDBY_MODE_AGGRESSIVE = @as(u32, 1);
pub const GUID_ACDC_POWER_SOURCE = Guid.initString("5d3e9a59-e9d5-4b00-a6bd-ff34ff516548");
pub const GUID_LIDSWITCH_STATE_CHANGE = Guid.initString("ba3e0f4d-b817-4094-a2d1-d56379e6a0f3");
pub const GUID_BATTERY_PERCENTAGE_REMAINING = Guid.initString("a7ad8041-b45a-4cae-87a3-eecbb468a9e1");
pub const GUID_BATTERY_COUNT = Guid.initString("7d263f15-fca4-49e5-854b-a9f2bfbd5c24");
pub const GUID_GLOBAL_USER_PRESENCE = Guid.initString("786e8a1d-b427-4344-9207-09e70bdcbea9");
pub const GUID_SESSION_DISPLAY_STATUS = Guid.initString("2b84c20e-ad23-4ddf-93db-05ffbd7efca5");
pub const GUID_SESSION_USER_PRESENCE = Guid.initString("3c0f4548-c03f-4c4d-b9f2-237ede686376");
pub const GUID_IDLE_BACKGROUND_TASK = Guid.initString("515c31d8-f734-163d-a0fd-11a08c91e8f1");
pub const GUID_BACKGROUND_TASK_NOTIFICATION = Guid.initString("cf23f240-2a54-48d8-b114-de1518ff052e");
pub const GUID_APPLAUNCH_BUTTON = Guid.initString("1a689231-7399-4e9a-8f99-b71f999db3fa");
pub const GUID_PCIEXPRESS_SETTINGS_SUBGROUP = Guid.initString("501a4d13-42af-4429-9fd1-a8218c268e20");
pub const GUID_PCIEXPRESS_ASPM_POLICY = Guid.initString("ee12f906-d277-404b-b6da-e5fa1a576df5");
pub const GUID_ENABLE_SWITCH_FORCED_SHUTDOWN = Guid.initString("833a6b62-dfa4-46d1-82f8-e09e34d029d6");
pub const GUID_INTSTEER_SUBGROUP = Guid.initString("48672f38-7a9a-4bb2-8bf8-3d85be19de4e");
pub const GUID_INTSTEER_MODE = Guid.initString("2bfc24f9-5ea2-4801-8213-3dbae01aa39d");
pub const GUID_INTSTEER_LOAD_PER_PROC_TRIGGER = Guid.initString("73cde64d-d720-4bb2-a860-c755afe77ef2");
pub const GUID_INTSTEER_TIME_UNPARK_TRIGGER = Guid.initString("d6ba4903-386f-4c2c-8adb-5c21b3328d25");
pub const GUID_GRAPHICS_SUBGROUP = Guid.initString("5fb4938d-1ee8-4b0f-9a3c-5036b0ab995c");
pub const GUID_GPU_PREFERENCE_POLICY = Guid.initString("dd848b2a-8a5d-4451-9ae2-39cd41658f6c");
pub const GUID_MIXED_REALITY_MODE = Guid.initString("1e626b4e-cf04-4f8d-9cc7-c97c5b0f2391");
pub const GUID_SPR_ACTIVE_SESSION_CHANGE = Guid.initString("0e24ce38-c393-4742-bdb1-744f4b9ee08e");
pub const POWER_SYSTEM_MAXIMUM = @as(u32, 7);
pub const DIAGNOSTIC_REASON_VERSION = @as(u32, 0);
pub const DIAGNOSTIC_REASON_SIMPLE_STRING = @as(u32, 1);
pub const DIAGNOSTIC_REASON_DETAILED_STRING = @as(u32, 2);
pub const DIAGNOSTIC_REASON_NOT_SPECIFIED = @as(u32, 2147483648);
pub const PDCAP_D0_SUPPORTED = @as(u32, 1);
pub const PDCAP_D1_SUPPORTED = @as(u32, 2);
pub const PDCAP_D2_SUPPORTED = @as(u32, 4);
pub const PDCAP_D3_SUPPORTED = @as(u32, 8);
pub const PDCAP_WAKE_FROM_D0_SUPPORTED = @as(u32, 16);
pub const PDCAP_WAKE_FROM_D1_SUPPORTED = @as(u32, 32);
pub const PDCAP_WAKE_FROM_D2_SUPPORTED = @as(u32, 64);
pub const PDCAP_WAKE_FROM_D3_SUPPORTED = @as(u32, 128);
pub const PDCAP_WARM_EJECT_SUPPORTED = @as(u32, 256);
pub const POWER_SETTING_VALUE_VERSION = @as(u32, 1);
pub const PROC_IDLE_BUCKET_COUNT = @as(u32, 6);
pub const PROC_IDLE_BUCKET_COUNT_EX = @as(u32, 16);
pub const ACPI_PPM_SOFTWARE_ALL = @as(u32, 252);
pub const ACPI_PPM_SOFTWARE_ANY = @as(u32, 253);
pub const ACPI_PPM_HARDWARE_ALL = @as(u32, 254);
pub const MS_PPM_SOFTWARE_ALL = @as(u32, 1);
pub const PPM_FIRMWARE_ACPI1C2 = @as(u32, 1);
pub const PPM_FIRMWARE_ACPI1C3 = @as(u32, 2);
pub const PPM_FIRMWARE_ACPI1TSTATES = @as(u32, 4);
pub const PPM_FIRMWARE_CST = @as(u32, 8);
pub const PPM_FIRMWARE_CSD = @as(u32, 16);
pub const PPM_FIRMWARE_PCT = @as(u32, 32);
pub const PPM_FIRMWARE_PSS = @as(u32, 64);
pub const PPM_FIRMWARE_XPSS = @as(u32, 128);
pub const PPM_FIRMWARE_PPC = @as(u32, 256);
pub const PPM_FIRMWARE_PSD = @as(u32, 512);
pub const PPM_FIRMWARE_PTC = @as(u32, 1024);
pub const PPM_FIRMWARE_TSS = @as(u32, 2048);
pub const PPM_FIRMWARE_TPC = @as(u32, 4096);
pub const PPM_FIRMWARE_TSD = @as(u32, 8192);
pub const PPM_FIRMWARE_PCCH = @as(u32, 16384);
pub const PPM_FIRMWARE_PCCP = @as(u32, 32768);
pub const PPM_FIRMWARE_OSC = @as(u32, 65536);
pub const PPM_FIRMWARE_PDC = @as(u32, 131072);
pub const PPM_FIRMWARE_CPC = @as(u32, 262144);
pub const PPM_FIRMWARE_LPI = @as(u32, 524288);
pub const PPM_PERFORMANCE_IMPLEMENTATION_NONE = @as(u32, 0);
pub const PPM_PERFORMANCE_IMPLEMENTATION_PSTATES = @as(u32, 1);
pub const PPM_PERFORMANCE_IMPLEMENTATION_PCCV1 = @as(u32, 2);
pub const PPM_PERFORMANCE_IMPLEMENTATION_CPPC = @as(u32, 3);
pub const PPM_PERFORMANCE_IMPLEMENTATION_PEP = @as(u32, 4);
pub const PPM_IDLE_IMPLEMENTATION_NONE = @as(u32, 0);
pub const PPM_IDLE_IMPLEMENTATION_CSTATES = @as(u32, 1);
pub const PPM_IDLE_IMPLEMENTATION_PEP = @as(u32, 2);
pub const PPM_IDLE_IMPLEMENTATION_MICROPEP = @as(u32, 3);
pub const PPM_IDLE_IMPLEMENTATION_LPISTATES = @as(u32, 4);
pub const PPM_PERFSTATE_CHANGE_GUID = Guid.initString("a5b32ddd-7f39-4abc-b892-900e43b59ebb");
pub const PPM_PERFSTATE_DOMAIN_CHANGE_GUID = Guid.initString("995e6b7f-d653-497a-b978-36a30c29bf01");
pub const PPM_IDLESTATE_CHANGE_GUID = Guid.initString("4838fe4f-f71c-4e51-9ecc-8430a7ac4c6c");
pub const PPM_PERFSTATES_DATA_GUID = Guid.initString("5708cc20-7d40-4bf4-b4aa-2b01338d0126");
pub const PPM_IDLESTATES_DATA_GUID = Guid.initString("ba138e10-e250-4ad7-8616-cf1a7ad410e7");
pub const PPM_IDLE_ACCOUNTING_GUID = Guid.initString("e2a26f78-ae07-4ee0-a30f-ce54f55a94cd");
pub const PPM_IDLE_ACCOUNTING_EX_GUID = Guid.initString("d67abd39-81f8-4a5e-8152-72e31ec912ee");
pub const PPM_THERMALCONSTRAINT_GUID = Guid.initString("a852c2c8-1a4c-423b-8c2c-f30d82931a88");
pub const PPM_PERFMON_PERFSTATE_GUID = Guid.initString("7fd18652-0cfe-40d2-b0a1-0b066a87759e");
pub const PPM_THERMAL_POLICY_CHANGE_GUID = Guid.initString("48f377b8-6880-4c7b-8bdc-380176c6654d");
pub const POWER_ACTION_QUERY_ALLOWED = @as(u32, 1);
pub const POWER_ACTION_UI_ALLOWED = @as(u32, 2);
pub const POWER_ACTION_OVERRIDE_APPS = @as(u32, 4);
pub const POWER_ACTION_HIBERBOOT = @as(u32, 8);
pub const POWER_ACTION_USER_NOTIFY = @as(u32, 16);
pub const POWER_ACTION_DOZE_TO_HIBERNATE = @as(u32, 32);
pub const POWER_ACTION_ACPI_CRITICAL = @as(u32, 16777216);
pub const POWER_ACTION_ACPI_USER_NOTIFY = @as(u32, 33554432);
pub const POWER_ACTION_DIRECTED_DRIPS = @as(u32, 67108864);
pub const POWER_ACTION_PSEUDO_TRANSITION = @as(u32, 134217728);
pub const POWER_ACTION_LIGHTEST_FIRST = @as(u32, 268435456);
pub const POWER_ACTION_LOCK_CONSOLE = @as(u32, 536870912);
pub const POWER_ACTION_DISABLE_WAKES = @as(u32, 1073741824);
pub const POWER_ACTION_CRITICAL = @as(u32, 2147483648);
pub const POWER_USER_NOTIFY_FORCED_SHUTDOWN = @as(u32, 32);
pub const BATTERY_DISCHARGE_FLAGS_EVENTCODE_MASK = @as(u32, 7);
pub const BATTERY_DISCHARGE_FLAGS_ENABLE = @as(u32, 2147483648);
pub const NUM_DISCHARGE_POLICIES = @as(u32, 4);
pub const DISCHARGE_POLICY_CRITICAL = @as(u32, 0);
pub const DISCHARGE_POLICY_LOW = @as(u32, 1);
pub const PROCESSOR_IDLESTATE_POLICY_COUNT = @as(u32, 3);
pub const PO_THROTTLE_NONE = @as(u32, 0);
pub const PO_THROTTLE_CONSTANT = @as(u32, 1);
pub const PO_THROTTLE_DEGRADE = @as(u32, 2);
pub const PO_THROTTLE_ADAPTIVE = @as(u32, 3);
pub const PO_THROTTLE_MAXIMUM = @as(u32, 4);
pub const HIBERFILE_TYPE_NONE = @as(u32, 0);
pub const HIBERFILE_TYPE_REDUCED = @as(u32, 1);
pub const HIBERFILE_TYPE_FULL = @as(u32, 2);
pub const HIBERFILE_TYPE_MAX = @as(u32, 3);
pub const IMAGE_DOS_SIGNATURE = @as(u32, 23117);
pub const IMAGE_OS2_SIGNATURE = @as(u32, 17742);
pub const IMAGE_OS2_SIGNATURE_LE = @as(u32, 17740);
pub const IMAGE_VXD_SIGNATURE = @as(u32, 17740);
pub const IMAGE_NT_SIGNATURE = @as(u32, 17744);
pub const IMAGE_SIZEOF_FILE_HEADER = @as(u32, 20);
pub const IMAGE_NUMBEROF_DIRECTORY_ENTRIES = @as(u32, 16);
pub const IMAGE_SIZEOF_SHORT_NAME = @as(u32, 8);
pub const IMAGE_SIZEOF_SECTION_HEADER = @as(u32, 40);
pub const IMAGE_SIZEOF_SYMBOL = @as(u32, 18);
pub const IMAGE_SYM_SECTION_MAX = @as(u32, 65279);
pub const IMAGE_SYM_TYPE_NULL = @as(u32, 0);
pub const IMAGE_SYM_TYPE_VOID = @as(u32, 1);
pub const IMAGE_SYM_TYPE_CHAR = @as(u32, 2);
pub const IMAGE_SYM_TYPE_SHORT = @as(u32, 3);
pub const IMAGE_SYM_TYPE_INT = @as(u32, 4);
pub const IMAGE_SYM_TYPE_LONG = @as(u32, 5);
pub const IMAGE_SYM_TYPE_FLOAT = @as(u32, 6);
pub const IMAGE_SYM_TYPE_DOUBLE = @as(u32, 7);
pub const IMAGE_SYM_TYPE_STRUCT = @as(u32, 8);
pub const IMAGE_SYM_TYPE_UNION = @as(u32, 9);
pub const IMAGE_SYM_TYPE_ENUM = @as(u32, 10);
pub const IMAGE_SYM_TYPE_MOE = @as(u32, 11);
pub const IMAGE_SYM_TYPE_BYTE = @as(u32, 12);
pub const IMAGE_SYM_TYPE_WORD = @as(u32, 13);
pub const IMAGE_SYM_TYPE_UINT = @as(u32, 14);
pub const IMAGE_SYM_TYPE_DWORD = @as(u32, 15);
pub const IMAGE_SYM_TYPE_PCODE = @as(u32, 32768);
pub const IMAGE_SYM_DTYPE_NULL = @as(u32, 0);
pub const IMAGE_SYM_DTYPE_POINTER = @as(u32, 1);
pub const IMAGE_SYM_DTYPE_FUNCTION = @as(u32, 2);
pub const IMAGE_SYM_DTYPE_ARRAY = @as(u32, 3);
pub const IMAGE_SYM_CLASS_NULL = @as(u32, 0);
pub const IMAGE_SYM_CLASS_AUTOMATIC = @as(u32, 1);
pub const IMAGE_SYM_CLASS_EXTERNAL = @as(u32, 2);
pub const IMAGE_SYM_CLASS_STATIC = @as(u32, 3);
pub const IMAGE_SYM_CLASS_REGISTER = @as(u32, 4);
pub const IMAGE_SYM_CLASS_EXTERNAL_DEF = @as(u32, 5);
pub const IMAGE_SYM_CLASS_LABEL = @as(u32, 6);
pub const IMAGE_SYM_CLASS_UNDEFINED_LABEL = @as(u32, 7);
pub const IMAGE_SYM_CLASS_MEMBER_OF_STRUCT = @as(u32, 8);
pub const IMAGE_SYM_CLASS_ARGUMENT = @as(u32, 9);
pub const IMAGE_SYM_CLASS_STRUCT_TAG = @as(u32, 10);
pub const IMAGE_SYM_CLASS_MEMBER_OF_UNION = @as(u32, 11);
pub const IMAGE_SYM_CLASS_UNION_TAG = @as(u32, 12);
pub const IMAGE_SYM_CLASS_TYPE_DEFINITION = @as(u32, 13);
pub const IMAGE_SYM_CLASS_UNDEFINED_STATIC = @as(u32, 14);
pub const IMAGE_SYM_CLASS_ENUM_TAG = @as(u32, 15);
pub const IMAGE_SYM_CLASS_MEMBER_OF_ENUM = @as(u32, 16);
pub const IMAGE_SYM_CLASS_REGISTER_PARAM = @as(u32, 17);
pub const IMAGE_SYM_CLASS_BIT_FIELD = @as(u32, 18);
pub const IMAGE_SYM_CLASS_FAR_EXTERNAL = @as(u32, 68);
pub const IMAGE_SYM_CLASS_BLOCK = @as(u32, 100);
pub const IMAGE_SYM_CLASS_FUNCTION = @as(u32, 101);
pub const IMAGE_SYM_CLASS_END_OF_STRUCT = @as(u32, 102);
pub const IMAGE_SYM_CLASS_FILE = @as(u32, 103);
pub const IMAGE_SYM_CLASS_SECTION = @as(u32, 104);
pub const IMAGE_SYM_CLASS_WEAK_EXTERNAL = @as(u32, 105);
pub const IMAGE_SYM_CLASS_CLR_TOKEN = @as(u32, 107);
pub const N_BTMASK = @as(u32, 15);
pub const N_TMASK = @as(u32, 48);
pub const N_TMASK1 = @as(u32, 192);
pub const N_TMASK2 = @as(u32, 240);
pub const N_BTSHFT = @as(u32, 4);
pub const N_TSHIFT = @as(u32, 2);
pub const IMAGE_COMDAT_SELECT_NODUPLICATES = @as(u32, 1);
pub const IMAGE_COMDAT_SELECT_ANY = @as(u32, 2);
pub const IMAGE_COMDAT_SELECT_SAME_SIZE = @as(u32, 3);
pub const IMAGE_COMDAT_SELECT_EXACT_MATCH = @as(u32, 4);
pub const IMAGE_COMDAT_SELECT_ASSOCIATIVE = @as(u32, 5);
pub const IMAGE_COMDAT_SELECT_LARGEST = @as(u32, 6);
pub const IMAGE_COMDAT_SELECT_NEWEST = @as(u32, 7);
pub const IMAGE_WEAK_EXTERN_SEARCH_NOLIBRARY = @as(u32, 1);
pub const IMAGE_WEAK_EXTERN_SEARCH_LIBRARY = @as(u32, 2);
pub const IMAGE_WEAK_EXTERN_SEARCH_ALIAS = @as(u32, 3);
pub const IMAGE_WEAK_EXTERN_ANTI_DEPENDENCY = @as(u32, 4);
pub const IMAGE_REL_I386_ABSOLUTE = @as(u32, 0);
pub const IMAGE_REL_I386_DIR16 = @as(u32, 1);
pub const IMAGE_REL_I386_REL16 = @as(u32, 2);
pub const IMAGE_REL_I386_DIR32 = @as(u32, 6);
pub const IMAGE_REL_I386_DIR32NB = @as(u32, 7);
pub const IMAGE_REL_I386_SEG12 = @as(u32, 9);
pub const IMAGE_REL_I386_SECTION = @as(u32, 10);
pub const IMAGE_REL_I386_SECREL = @as(u32, 11);
pub const IMAGE_REL_I386_TOKEN = @as(u32, 12);
pub const IMAGE_REL_I386_SECREL7 = @as(u32, 13);
pub const IMAGE_REL_I386_REL32 = @as(u32, 20);
pub const IMAGE_REL_MIPS_ABSOLUTE = @as(u32, 0);
pub const IMAGE_REL_MIPS_REFHALF = @as(u32, 1);
pub const IMAGE_REL_MIPS_REFWORD = @as(u32, 2);
pub const IMAGE_REL_MIPS_JMPADDR = @as(u32, 3);
pub const IMAGE_REL_MIPS_REFHI = @as(u32, 4);
pub const IMAGE_REL_MIPS_REFLO = @as(u32, 5);
pub const IMAGE_REL_MIPS_GPREL = @as(u32, 6);
pub const IMAGE_REL_MIPS_LITERAL = @as(u32, 7);
pub const IMAGE_REL_MIPS_SECTION = @as(u32, 10);
pub const IMAGE_REL_MIPS_SECREL = @as(u32, 11);
pub const IMAGE_REL_MIPS_SECRELLO = @as(u32, 12);
pub const IMAGE_REL_MIPS_SECRELHI = @as(u32, 13);
pub const IMAGE_REL_MIPS_TOKEN = @as(u32, 14);
pub const IMAGE_REL_MIPS_JMPADDR16 = @as(u32, 16);
pub const IMAGE_REL_MIPS_REFWORDNB = @as(u32, 34);
pub const IMAGE_REL_MIPS_PAIR = @as(u32, 37);
pub const IMAGE_REL_ALPHA_ABSOLUTE = @as(u32, 0);
pub const IMAGE_REL_ALPHA_REFLONG = @as(u32, 1);
pub const IMAGE_REL_ALPHA_REFQUAD = @as(u32, 2);
pub const IMAGE_REL_ALPHA_GPREL32 = @as(u32, 3);
pub const IMAGE_REL_ALPHA_LITERAL = @as(u32, 4);
pub const IMAGE_REL_ALPHA_LITUSE = @as(u32, 5);
pub const IMAGE_REL_ALPHA_GPDISP = @as(u32, 6);
pub const IMAGE_REL_ALPHA_BRADDR = @as(u32, 7);
pub const IMAGE_REL_ALPHA_HINT = @as(u32, 8);
pub const IMAGE_REL_ALPHA_INLINE_REFLONG = @as(u32, 9);
pub const IMAGE_REL_ALPHA_REFHI = @as(u32, 10);
pub const IMAGE_REL_ALPHA_REFLO = @as(u32, 11);
pub const IMAGE_REL_ALPHA_PAIR = @as(u32, 12);
pub const IMAGE_REL_ALPHA_MATCH = @as(u32, 13);
pub const IMAGE_REL_ALPHA_SECTION = @as(u32, 14);
pub const IMAGE_REL_ALPHA_SECREL = @as(u32, 15);
pub const IMAGE_REL_ALPHA_REFLONGNB = @as(u32, 16);
pub const IMAGE_REL_ALPHA_SECRELLO = @as(u32, 17);
pub const IMAGE_REL_ALPHA_SECRELHI = @as(u32, 18);
pub const IMAGE_REL_ALPHA_REFQ3 = @as(u32, 19);
pub const IMAGE_REL_ALPHA_REFQ2 = @as(u32, 20);
pub const IMAGE_REL_ALPHA_REFQ1 = @as(u32, 21);
pub const IMAGE_REL_ALPHA_GPRELLO = @as(u32, 22);
pub const IMAGE_REL_ALPHA_GPRELHI = @as(u32, 23);
pub const IMAGE_REL_PPC_ABSOLUTE = @as(u32, 0);
pub const IMAGE_REL_PPC_ADDR64 = @as(u32, 1);
pub const IMAGE_REL_PPC_ADDR32 = @as(u32, 2);
pub const IMAGE_REL_PPC_ADDR24 = @as(u32, 3);
pub const IMAGE_REL_PPC_ADDR16 = @as(u32, 4);
pub const IMAGE_REL_PPC_ADDR14 = @as(u32, 5);
pub const IMAGE_REL_PPC_REL24 = @as(u32, 6);
pub const IMAGE_REL_PPC_REL14 = @as(u32, 7);
pub const IMAGE_REL_PPC_TOCREL16 = @as(u32, 8);
pub const IMAGE_REL_PPC_TOCREL14 = @as(u32, 9);
pub const IMAGE_REL_PPC_ADDR32NB = @as(u32, 10);
pub const IMAGE_REL_PPC_SECREL = @as(u32, 11);
pub const IMAGE_REL_PPC_SECTION = @as(u32, 12);
pub const IMAGE_REL_PPC_IFGLUE = @as(u32, 13);
pub const IMAGE_REL_PPC_IMGLUE = @as(u32, 14);
pub const IMAGE_REL_PPC_SECREL16 = @as(u32, 15);
pub const IMAGE_REL_PPC_REFHI = @as(u32, 16);
pub const IMAGE_REL_PPC_REFLO = @as(u32, 17);
pub const IMAGE_REL_PPC_PAIR = @as(u32, 18);
pub const IMAGE_REL_PPC_SECRELLO = @as(u32, 19);
pub const IMAGE_REL_PPC_SECRELHI = @as(u32, 20);
pub const IMAGE_REL_PPC_GPREL = @as(u32, 21);
pub const IMAGE_REL_PPC_TOKEN = @as(u32, 22);
pub const IMAGE_REL_PPC_TYPEMASK = @as(u32, 255);
pub const IMAGE_REL_PPC_NEG = @as(u32, 256);
pub const IMAGE_REL_PPC_BRTAKEN = @as(u32, 512);
pub const IMAGE_REL_PPC_BRNTAKEN = @as(u32, 1024);
pub const IMAGE_REL_PPC_TOCDEFN = @as(u32, 2048);
pub const IMAGE_REL_SH3_ABSOLUTE = @as(u32, 0);
pub const IMAGE_REL_SH3_DIRECT16 = @as(u32, 1);
pub const IMAGE_REL_SH3_DIRECT32 = @as(u32, 2);
pub const IMAGE_REL_SH3_DIRECT8 = @as(u32, 3);
pub const IMAGE_REL_SH3_DIRECT8_WORD = @as(u32, 4);
pub const IMAGE_REL_SH3_DIRECT8_LONG = @as(u32, 5);
pub const IMAGE_REL_SH3_DIRECT4 = @as(u32, 6);
pub const IMAGE_REL_SH3_DIRECT4_WORD = @as(u32, 7);
pub const IMAGE_REL_SH3_DIRECT4_LONG = @as(u32, 8);
pub const IMAGE_REL_SH3_PCREL8_WORD = @as(u32, 9);
pub const IMAGE_REL_SH3_PCREL8_LONG = @as(u32, 10);
pub const IMAGE_REL_SH3_PCREL12_WORD = @as(u32, 11);
pub const IMAGE_REL_SH3_STARTOF_SECTION = @as(u32, 12);
pub const IMAGE_REL_SH3_SIZEOF_SECTION = @as(u32, 13);
pub const IMAGE_REL_SH3_SECTION = @as(u32, 14);
pub const IMAGE_REL_SH3_SECREL = @as(u32, 15);
pub const IMAGE_REL_SH3_DIRECT32_NB = @as(u32, 16);
pub const IMAGE_REL_SH3_GPREL4_LONG = @as(u32, 17);
pub const IMAGE_REL_SH3_TOKEN = @as(u32, 18);
pub const IMAGE_REL_SHM_PCRELPT = @as(u32, 19);
pub const IMAGE_REL_SHM_REFLO = @as(u32, 20);
pub const IMAGE_REL_SHM_REFHALF = @as(u32, 21);
pub const IMAGE_REL_SHM_RELLO = @as(u32, 22);
pub const IMAGE_REL_SHM_RELHALF = @as(u32, 23);
pub const IMAGE_REL_SHM_PAIR = @as(u32, 24);
pub const IMAGE_REL_SH_NOMODE = @as(u32, 32768);
pub const IMAGE_REL_ARM_ABSOLUTE = @as(u32, 0);
pub const IMAGE_REL_ARM_ADDR32 = @as(u32, 1);
pub const IMAGE_REL_ARM_ADDR32NB = @as(u32, 2);
pub const IMAGE_REL_ARM_BRANCH24 = @as(u32, 3);
pub const IMAGE_REL_ARM_BRANCH11 = @as(u32, 4);
pub const IMAGE_REL_ARM_TOKEN = @as(u32, 5);
pub const IMAGE_REL_ARM_GPREL12 = @as(u32, 6);
pub const IMAGE_REL_ARM_GPREL7 = @as(u32, 7);
pub const IMAGE_REL_ARM_BLX24 = @as(u32, 8);
pub const IMAGE_REL_ARM_BLX11 = @as(u32, 9);
pub const IMAGE_REL_ARM_SECTION = @as(u32, 14);
pub const IMAGE_REL_ARM_SECREL = @as(u32, 15);
pub const IMAGE_REL_ARM_MOV32A = @as(u32, 16);
pub const IMAGE_REL_ARM_MOV32 = @as(u32, 16);
pub const IMAGE_REL_ARM_MOV32T = @as(u32, 17);
pub const IMAGE_REL_THUMB_MOV32 = @as(u32, 17);
pub const IMAGE_REL_ARM_BRANCH20T = @as(u32, 18);
pub const IMAGE_REL_THUMB_BRANCH20 = @as(u32, 18);
pub const IMAGE_REL_ARM_BRANCH24T = @as(u32, 20);
pub const IMAGE_REL_THUMB_BRANCH24 = @as(u32, 20);
pub const IMAGE_REL_ARM_BLX23T = @as(u32, 21);
pub const IMAGE_REL_THUMB_BLX23 = @as(u32, 21);
pub const IMAGE_REL_AM_ABSOLUTE = @as(u32, 0);
pub const IMAGE_REL_AM_ADDR32 = @as(u32, 1);
pub const IMAGE_REL_AM_ADDR32NB = @as(u32, 2);
pub const IMAGE_REL_AM_CALL32 = @as(u32, 3);
pub const IMAGE_REL_AM_FUNCINFO = @as(u32, 4);
pub const IMAGE_REL_AM_REL32_1 = @as(u32, 5);
pub const IMAGE_REL_AM_REL32_2 = @as(u32, 6);
pub const IMAGE_REL_AM_SECREL = @as(u32, 7);
pub const IMAGE_REL_AM_SECTION = @as(u32, 8);
pub const IMAGE_REL_AM_TOKEN = @as(u32, 9);
pub const IMAGE_REL_ARM64_ABSOLUTE = @as(u32, 0);
pub const IMAGE_REL_ARM64_ADDR32 = @as(u32, 1);
pub const IMAGE_REL_ARM64_ADDR32NB = @as(u32, 2);
pub const IMAGE_REL_ARM64_BRANCH26 = @as(u32, 3);
pub const IMAGE_REL_ARM64_PAGEBASE_REL21 = @as(u32, 4);
pub const IMAGE_REL_ARM64_REL21 = @as(u32, 5);
pub const IMAGE_REL_ARM64_PAGEOFFSET_12A = @as(u32, 6);
pub const IMAGE_REL_ARM64_PAGEOFFSET_12L = @as(u32, 7);
pub const IMAGE_REL_ARM64_SECREL = @as(u32, 8);
pub const IMAGE_REL_ARM64_SECREL_LOW12A = @as(u32, 9);
pub const IMAGE_REL_ARM64_SECREL_HIGH12A = @as(u32, 10);
pub const IMAGE_REL_ARM64_SECREL_LOW12L = @as(u32, 11);
pub const IMAGE_REL_ARM64_TOKEN = @as(u32, 12);
pub const IMAGE_REL_ARM64_SECTION = @as(u32, 13);
pub const IMAGE_REL_ARM64_ADDR64 = @as(u32, 14);
pub const IMAGE_REL_ARM64_BRANCH19 = @as(u32, 15);
pub const IMAGE_REL_AMD64_ABSOLUTE = @as(u32, 0);
pub const IMAGE_REL_AMD64_ADDR64 = @as(u32, 1);
pub const IMAGE_REL_AMD64_ADDR32 = @as(u32, 2);
pub const IMAGE_REL_AMD64_ADDR32NB = @as(u32, 3);
pub const IMAGE_REL_AMD64_REL32 = @as(u32, 4);
pub const IMAGE_REL_AMD64_REL32_1 = @as(u32, 5);
pub const IMAGE_REL_AMD64_REL32_2 = @as(u32, 6);
pub const IMAGE_REL_AMD64_REL32_3 = @as(u32, 7);
pub const IMAGE_REL_AMD64_REL32_4 = @as(u32, 8);
pub const IMAGE_REL_AMD64_REL32_5 = @as(u32, 9);
pub const IMAGE_REL_AMD64_SECTION = @as(u32, 10);
pub const IMAGE_REL_AMD64_SECREL = @as(u32, 11);
pub const IMAGE_REL_AMD64_SECREL7 = @as(u32, 12);
pub const IMAGE_REL_AMD64_TOKEN = @as(u32, 13);
pub const IMAGE_REL_AMD64_SREL32 = @as(u32, 14);
pub const IMAGE_REL_AMD64_PAIR = @as(u32, 15);
pub const IMAGE_REL_AMD64_SSPAN32 = @as(u32, 16);
pub const IMAGE_REL_AMD64_EHANDLER = @as(u32, 17);
pub const IMAGE_REL_AMD64_IMPORT_BR = @as(u32, 18);
pub const IMAGE_REL_AMD64_IMPORT_CALL = @as(u32, 19);
pub const IMAGE_REL_AMD64_CFG_BR = @as(u32, 20);
pub const IMAGE_REL_AMD64_CFG_BR_REX = @as(u32, 21);
pub const IMAGE_REL_AMD64_CFG_CALL = @as(u32, 22);
pub const IMAGE_REL_AMD64_INDIR_BR = @as(u32, 23);
pub const IMAGE_REL_AMD64_INDIR_BR_REX = @as(u32, 24);
pub const IMAGE_REL_AMD64_INDIR_CALL = @as(u32, 25);
pub const IMAGE_REL_AMD64_INDIR_BR_SWITCHTABLE_FIRST = @as(u32, 32);
pub const IMAGE_REL_AMD64_INDIR_BR_SWITCHTABLE_LAST = @as(u32, 47);
pub const IMAGE_REL_IA64_ABSOLUTE = @as(u32, 0);
pub const IMAGE_REL_IA64_IMM14 = @as(u32, 1);
pub const IMAGE_REL_IA64_IMM22 = @as(u32, 2);
pub const IMAGE_REL_IA64_IMM64 = @as(u32, 3);
pub const IMAGE_REL_IA64_DIR32 = @as(u32, 4);
pub const IMAGE_REL_IA64_DIR64 = @as(u32, 5);
pub const IMAGE_REL_IA64_PCREL21B = @as(u32, 6);
pub const IMAGE_REL_IA64_PCREL21M = @as(u32, 7);
pub const IMAGE_REL_IA64_PCREL21F = @as(u32, 8);
pub const IMAGE_REL_IA64_GPREL22 = @as(u32, 9);
pub const IMAGE_REL_IA64_LTOFF22 = @as(u32, 10);
pub const IMAGE_REL_IA64_SECTION = @as(u32, 11);
pub const IMAGE_REL_IA64_SECREL22 = @as(u32, 12);
pub const IMAGE_REL_IA64_SECREL64I = @as(u32, 13);
pub const IMAGE_REL_IA64_SECREL32 = @as(u32, 14);
pub const IMAGE_REL_IA64_DIR32NB = @as(u32, 16);
pub const IMAGE_REL_IA64_SREL14 = @as(u32, 17);
pub const IMAGE_REL_IA64_SREL22 = @as(u32, 18);
pub const IMAGE_REL_IA64_SREL32 = @as(u32, 19);
pub const IMAGE_REL_IA64_UREL32 = @as(u32, 20);
pub const IMAGE_REL_IA64_PCREL60X = @as(u32, 21);
pub const IMAGE_REL_IA64_PCREL60B = @as(u32, 22);
pub const IMAGE_REL_IA64_PCREL60F = @as(u32, 23);
pub const IMAGE_REL_IA64_PCREL60I = @as(u32, 24);
pub const IMAGE_REL_IA64_PCREL60M = @as(u32, 25);
pub const IMAGE_REL_IA64_IMMGPREL64 = @as(u32, 26);
pub const IMAGE_REL_IA64_TOKEN = @as(u32, 27);
pub const IMAGE_REL_IA64_GPREL32 = @as(u32, 28);
pub const IMAGE_REL_IA64_ADDEND = @as(u32, 31);
pub const IMAGE_REL_CEF_ABSOLUTE = @as(u32, 0);
pub const IMAGE_REL_CEF_ADDR32 = @as(u32, 1);
pub const IMAGE_REL_CEF_ADDR64 = @as(u32, 2);
pub const IMAGE_REL_CEF_ADDR32NB = @as(u32, 3);
pub const IMAGE_REL_CEF_SECTION = @as(u32, 4);
pub const IMAGE_REL_CEF_SECREL = @as(u32, 5);
pub const IMAGE_REL_CEF_TOKEN = @as(u32, 6);
pub const IMAGE_REL_CEE_ABSOLUTE = @as(u32, 0);
pub const IMAGE_REL_CEE_ADDR32 = @as(u32, 1);
pub const IMAGE_REL_CEE_ADDR64 = @as(u32, 2);
pub const IMAGE_REL_CEE_ADDR32NB = @as(u32, 3);
pub const IMAGE_REL_CEE_SECTION = @as(u32, 4);
pub const IMAGE_REL_CEE_SECREL = @as(u32, 5);
pub const IMAGE_REL_CEE_TOKEN = @as(u32, 6);
pub const IMAGE_REL_M32R_ABSOLUTE = @as(u32, 0);
pub const IMAGE_REL_M32R_ADDR32 = @as(u32, 1);
pub const IMAGE_REL_M32R_ADDR32NB = @as(u32, 2);
pub const IMAGE_REL_M32R_ADDR24 = @as(u32, 3);
pub const IMAGE_REL_M32R_GPREL16 = @as(u32, 4);
pub const IMAGE_REL_M32R_PCREL24 = @as(u32, 5);
pub const IMAGE_REL_M32R_PCREL16 = @as(u32, 6);
pub const IMAGE_REL_M32R_PCREL8 = @as(u32, 7);
pub const IMAGE_REL_M32R_REFHALF = @as(u32, 8);
pub const IMAGE_REL_M32R_REFHI = @as(u32, 9);
pub const IMAGE_REL_M32R_REFLO = @as(u32, 10);
pub const IMAGE_REL_M32R_PAIR = @as(u32, 11);
pub const IMAGE_REL_M32R_SECTION = @as(u32, 12);
pub const IMAGE_REL_M32R_SECREL32 = @as(u32, 13);
pub const IMAGE_REL_M32R_TOKEN = @as(u32, 14);
pub const IMAGE_REL_EBC_ABSOLUTE = @as(u32, 0);
pub const IMAGE_REL_EBC_ADDR32NB = @as(u32, 1);
pub const IMAGE_REL_EBC_REL32 = @as(u32, 2);
pub const IMAGE_REL_EBC_SECTION = @as(u32, 3);
pub const IMAGE_REL_EBC_SECREL = @as(u32, 4);
pub const EMARCH_ENC_I17_IMM7B_INST_WORD_X = @as(u32, 3);
pub const EMARCH_ENC_I17_IMM7B_SIZE_X = @as(u32, 7);
pub const EMARCH_ENC_I17_IMM7B_INST_WORD_POS_X = @as(u32, 4);
pub const EMARCH_ENC_I17_IMM7B_VAL_POS_X = @as(u32, 0);
pub const EMARCH_ENC_I17_IMM9D_INST_WORD_X = @as(u32, 3);
pub const EMARCH_ENC_I17_IMM9D_SIZE_X = @as(u32, 9);
pub const EMARCH_ENC_I17_IMM9D_INST_WORD_POS_X = @as(u32, 18);
pub const EMARCH_ENC_I17_IMM9D_VAL_POS_X = @as(u32, 7);
pub const EMARCH_ENC_I17_IMM5C_INST_WORD_X = @as(u32, 3);
pub const EMARCH_ENC_I17_IMM5C_SIZE_X = @as(u32, 5);
pub const EMARCH_ENC_I17_IMM5C_INST_WORD_POS_X = @as(u32, 13);
pub const EMARCH_ENC_I17_IMM5C_VAL_POS_X = @as(u32, 16);
pub const EMARCH_ENC_I17_IC_INST_WORD_X = @as(u32, 3);
pub const EMARCH_ENC_I17_IC_SIZE_X = @as(u32, 1);
pub const EMARCH_ENC_I17_IC_INST_WORD_POS_X = @as(u32, 12);
pub const EMARCH_ENC_I17_IC_VAL_POS_X = @as(u32, 21);
pub const EMARCH_ENC_I17_IMM41a_INST_WORD_X = @as(u32, 1);
pub const EMARCH_ENC_I17_IMM41a_SIZE_X = @as(u32, 10);
pub const EMARCH_ENC_I17_IMM41a_INST_WORD_POS_X = @as(u32, 14);
pub const EMARCH_ENC_I17_IMM41a_VAL_POS_X = @as(u32, 22);
pub const EMARCH_ENC_I17_IMM41b_INST_WORD_X = @as(u32, 1);
pub const EMARCH_ENC_I17_IMM41b_SIZE_X = @as(u32, 8);
pub const EMARCH_ENC_I17_IMM41b_INST_WORD_POS_X = @as(u32, 24);
pub const EMARCH_ENC_I17_IMM41b_VAL_POS_X = @as(u32, 32);
pub const EMARCH_ENC_I17_IMM41c_INST_WORD_X = @as(u32, 2);
pub const EMARCH_ENC_I17_IMM41c_SIZE_X = @as(u32, 23);
pub const EMARCH_ENC_I17_IMM41c_INST_WORD_POS_X = @as(u32, 0);
pub const EMARCH_ENC_I17_IMM41c_VAL_POS_X = @as(u32, 40);
pub const EMARCH_ENC_I17_SIGN_INST_WORD_X = @as(u32, 3);
pub const EMARCH_ENC_I17_SIGN_SIZE_X = @as(u32, 1);
pub const EMARCH_ENC_I17_SIGN_INST_WORD_POS_X = @as(u32, 27);
pub const EMARCH_ENC_I17_SIGN_VAL_POS_X = @as(u32, 63);
pub const X3_OPCODE_INST_WORD_X = @as(u32, 3);
pub const X3_OPCODE_SIZE_X = @as(u32, 4);
pub const X3_OPCODE_INST_WORD_POS_X = @as(u32, 28);
pub const X3_OPCODE_SIGN_VAL_POS_X = @as(u32, 0);
pub const X3_I_INST_WORD_X = @as(u32, 3);
pub const X3_I_SIZE_X = @as(u32, 1);
pub const X3_I_INST_WORD_POS_X = @as(u32, 27);
pub const X3_I_SIGN_VAL_POS_X = @as(u32, 59);
pub const X3_D_WH_INST_WORD_X = @as(u32, 3);
pub const X3_D_WH_SIZE_X = @as(u32, 3);
pub const X3_D_WH_INST_WORD_POS_X = @as(u32, 24);
pub const X3_D_WH_SIGN_VAL_POS_X = @as(u32, 0);
pub const X3_IMM20_INST_WORD_X = @as(u32, 3);
pub const X3_IMM20_SIZE_X = @as(u32, 20);
pub const X3_IMM20_INST_WORD_POS_X = @as(u32, 4);
pub const X3_IMM20_SIGN_VAL_POS_X = @as(u32, 0);
pub const X3_IMM39_1_INST_WORD_X = @as(u32, 2);
pub const X3_IMM39_1_SIZE_X = @as(u32, 23);
pub const X3_IMM39_1_INST_WORD_POS_X = @as(u32, 0);
pub const X3_IMM39_1_SIGN_VAL_POS_X = @as(u32, 36);
pub const X3_IMM39_2_INST_WORD_X = @as(u32, 1);
pub const X3_IMM39_2_SIZE_X = @as(u32, 16);
pub const X3_IMM39_2_INST_WORD_POS_X = @as(u32, 16);
pub const X3_IMM39_2_SIGN_VAL_POS_X = @as(u32, 20);
pub const X3_P_INST_WORD_X = @as(u32, 3);
pub const X3_P_SIZE_X = @as(u32, 4);
pub const X3_P_INST_WORD_POS_X = @as(u32, 0);
pub const X3_P_SIGN_VAL_POS_X = @as(u32, 0);
pub const X3_TMPLT_INST_WORD_X = @as(u32, 0);
pub const X3_TMPLT_SIZE_X = @as(u32, 4);
pub const X3_TMPLT_INST_WORD_POS_X = @as(u32, 0);
pub const X3_TMPLT_SIGN_VAL_POS_X = @as(u32, 0);
pub const X3_BTYPE_QP_INST_WORD_X = @as(u32, 2);
pub const X3_BTYPE_QP_SIZE_X = @as(u32, 9);
pub const X3_BTYPE_QP_INST_WORD_POS_X = @as(u32, 23);
pub const X3_BTYPE_QP_INST_VAL_POS_X = @as(u32, 0);
pub const X3_EMPTY_INST_WORD_X = @as(u32, 1);
pub const X3_EMPTY_SIZE_X = @as(u32, 2);
pub const X3_EMPTY_INST_WORD_POS_X = @as(u32, 14);
pub const X3_EMPTY_INST_VAL_POS_X = @as(u32, 0);
pub const IMAGE_REL_BASED_ABSOLUTE = @as(u32, 0);
pub const IMAGE_REL_BASED_HIGH = @as(u32, 1);
pub const IMAGE_REL_BASED_LOW = @as(u32, 2);
pub const IMAGE_REL_BASED_HIGHLOW = @as(u32, 3);
pub const IMAGE_REL_BASED_HIGHADJ = @as(u32, 4);
pub const IMAGE_REL_BASED_MACHINE_SPECIFIC_5 = @as(u32, 5);
pub const IMAGE_REL_BASED_RESERVED = @as(u32, 6);
pub const IMAGE_REL_BASED_MACHINE_SPECIFIC_7 = @as(u32, 7);
pub const IMAGE_REL_BASED_MACHINE_SPECIFIC_8 = @as(u32, 8);
pub const IMAGE_REL_BASED_MACHINE_SPECIFIC_9 = @as(u32, 9);
pub const IMAGE_REL_BASED_DIR64 = @as(u32, 10);
pub const IMAGE_REL_BASED_IA64_IMM64 = @as(u32, 9);
pub const IMAGE_REL_BASED_MIPS_JMPADDR = @as(u32, 5);
pub const IMAGE_REL_BASED_MIPS_JMPADDR16 = @as(u32, 9);
pub const IMAGE_REL_BASED_ARM_MOV32 = @as(u32, 5);
pub const IMAGE_REL_BASED_THUMB_MOV32 = @as(u32, 7);
pub const IMAGE_ARCHIVE_START_SIZE = @as(u32, 8);
pub const IMAGE_SIZEOF_ARCHIVE_MEMBER_HDR = @as(u32, 60);
pub const IMAGE_ORDINAL_FLAG64 = @as(u64, 9223372036854775808);
pub const IMAGE_ORDINAL_FLAG32 = @as(u32, 2147483648);
pub const IMAGE_RESOURCE_NAME_IS_STRING = @as(u32, 2147483648);
pub const IMAGE_RESOURCE_DATA_IS_DIRECTORY = @as(u32, 2147483648);
pub const IMAGE_DYNAMIC_RELOCATION_GUARD_RF_PROLOGUE = @as(u32, 1);
pub const IMAGE_DYNAMIC_RELOCATION_GUARD_RF_EPILOGUE = @as(u32, 2);
pub const IMAGE_DYNAMIC_RELOCATION_GUARD_IMPORT_CONTROL_TRANSFER = @as(u32, 3);
pub const IMAGE_DYNAMIC_RELOCATION_GUARD_INDIR_CONTROL_TRANSFER = @as(u32, 4);
pub const IMAGE_DYNAMIC_RELOCATION_GUARD_SWITCHTABLE_BRANCH = @as(u32, 5);
pub const IMAGE_HOT_PATCH_BASE_OBLIGATORY = @as(u32, 1);
pub const IMAGE_HOT_PATCH_BASE_CAN_ROLL_BACK = @as(u32, 2);
pub const IMAGE_HOT_PATCH_CHUNK_INVERSE = @as(u32, 2147483648);
pub const IMAGE_HOT_PATCH_CHUNK_OBLIGATORY = @as(u32, 1073741824);
pub const IMAGE_HOT_PATCH_CHUNK_RESERVED = @as(u32, 1072705536);
pub const IMAGE_HOT_PATCH_CHUNK_TYPE = @as(u32, 1032192);
pub const IMAGE_HOT_PATCH_CHUNK_SOURCE_RVA = @as(u32, 32768);
pub const IMAGE_HOT_PATCH_CHUNK_TARGET_RVA = @as(u32, 16384);
pub const IMAGE_HOT_PATCH_CHUNK_SIZE = @as(u32, 4095);
pub const IMAGE_HOT_PATCH_NONE = @as(u32, 0);
pub const IMAGE_HOT_PATCH_FUNCTION = @as(u32, 114688);
pub const IMAGE_HOT_PATCH_ABSOLUTE = @as(u32, 180224);
pub const IMAGE_HOT_PATCH_REL32 = @as(u32, 245760);
pub const IMAGE_HOT_PATCH_CALL_TARGET = @as(u32, 278528);
pub const IMAGE_HOT_PATCH_INDIRECT = @as(u32, 376832);
pub const IMAGE_HOT_PATCH_NO_CALL_TARGET = @as(u32, 409600);
pub const IMAGE_HOT_PATCH_DYNAMIC_VALUE = @as(u32, 491520);
pub const IMAGE_GUARD_CF_INSTRUMENTED = @as(u32, 256);
pub const IMAGE_GUARD_CFW_INSTRUMENTED = @as(u32, 512);
pub const IMAGE_GUARD_CF_FUNCTION_TABLE_PRESENT = @as(u32, 1024);
pub const IMAGE_GUARD_SECURITY_COOKIE_UNUSED = @as(u32, 2048);
pub const IMAGE_GUARD_PROTECT_DELAYLOAD_IAT = @as(u32, 4096);
pub const IMAGE_GUARD_DELAYLOAD_IAT_IN_ITS_OWN_SECTION = @as(u32, 8192);
pub const IMAGE_GUARD_CF_EXPORT_SUPPRESSION_INFO_PRESENT = @as(u32, 16384);
pub const IMAGE_GUARD_CF_ENABLE_EXPORT_SUPPRESSION = @as(u32, 32768);
pub const IMAGE_GUARD_CF_LONGJUMP_TABLE_PRESENT = @as(u32, 65536);
pub const IMAGE_GUARD_RF_INSTRUMENTED = @as(u32, 131072);
pub const IMAGE_GUARD_RF_ENABLE = @as(u32, 262144);
pub const IMAGE_GUARD_RF_STRICT = @as(u32, 524288);
pub const IMAGE_GUARD_RETPOLINE_PRESENT = @as(u32, 1048576);
pub const IMAGE_GUARD_EH_CONTINUATION_TABLE_PRESENT = @as(u32, 2097152);
pub const IMAGE_GUARD_CF_FUNCTION_TABLE_SIZE_MASK = @as(u32, 4026531840);
pub const IMAGE_GUARD_CF_FUNCTION_TABLE_SIZE_SHIFT = @as(u32, 28);
pub const IMAGE_GUARD_FLAG_FID_SUPPRESSED = @as(u32, 1);
pub const IMAGE_GUARD_FLAG_EXPORT_SUPPRESSED = @as(u32, 2);
pub const IMAGE_ENCLAVE_POLICY_DEBUGGABLE = @as(u32, 1);
pub const IMAGE_ENCLAVE_FLAG_PRIMARY_IMAGE = @as(u32, 1);
pub const IMAGE_ENCLAVE_IMPORT_MATCH_NONE = @as(u32, 0);
pub const IMAGE_ENCLAVE_IMPORT_MATCH_UNIQUE_ID = @as(u32, 1);
pub const IMAGE_ENCLAVE_IMPORT_MATCH_AUTHOR_ID = @as(u32, 2);
pub const IMAGE_ENCLAVE_IMPORT_MATCH_FAMILY_ID = @as(u32, 3);
pub const IMAGE_ENCLAVE_IMPORT_MATCH_IMAGE_ID = @as(u32, 4);
pub const IMAGE_DEBUG_TYPE_OMAP_TO_SRC = @as(u32, 7);
pub const IMAGE_DEBUG_TYPE_OMAP_FROM_SRC = @as(u32, 8);
pub const IMAGE_DEBUG_TYPE_RESERVED10 = @as(u32, 10);
pub const IMAGE_DEBUG_TYPE_CLSID = @as(u32, 11);
pub const IMAGE_DEBUG_TYPE_VC_FEATURE = @as(u32, 12);
pub const IMAGE_DEBUG_TYPE_POGO = @as(u32, 13);
pub const IMAGE_DEBUG_TYPE_ILTCG = @as(u32, 14);
pub const IMAGE_DEBUG_TYPE_MPX = @as(u32, 15);
pub const IMAGE_DEBUG_TYPE_REPRO = @as(u32, 16);
pub const IMAGE_DEBUG_TYPE_EX_DLLCHARACTERISTICS = @as(u32, 20);
pub const FRAME_FPO = @as(u32, 0);
pub const FRAME_TRAP = @as(u32, 1);
pub const FRAME_TSS = @as(u32, 2);
pub const FRAME_NONFPO = @as(u32, 3);
pub const SIZEOF_RFPO_DATA = @as(u32, 16);
pub const IMAGE_DEBUG_MISC_EXENAME = @as(u32, 1);
pub const IMAGE_SEPARATE_DEBUG_SIGNATURE = @as(u32, 18756);
pub const NON_PAGED_DEBUG_SIGNATURE = @as(u32, 18766);
pub const IMAGE_SEPARATE_DEBUG_FLAGS_MASK = @as(u32, 32768);
pub const IMAGE_SEPARATE_DEBUG_MISMATCH = @as(u32, 32768);
pub const IMPORT_OBJECT_HDR_SIG2 = @as(u32, 65535);
pub const RTL_RUN_ONCE_CHECK_ONLY = @as(u32, 1);
pub const RTL_RUN_ONCE_ASYNC = @as(u32, 2);
pub const RTL_RUN_ONCE_INIT_FAILED = @as(u32, 4);
pub const RTL_RUN_ONCE_CTX_RESERVED_BITS = @as(u32, 2);
pub const FAST_FAIL_LEGACY_GS_VIOLATION = @as(u32, 0);
pub const FAST_FAIL_VTGUARD_CHECK_FAILURE = @as(u32, 1);
pub const FAST_FAIL_STACK_COOKIE_CHECK_FAILURE = @as(u32, 2);
pub const FAST_FAIL_CORRUPT_LIST_ENTRY = @as(u32, 3);
pub const FAST_FAIL_INCORRECT_STACK = @as(u32, 4);
pub const FAST_FAIL_INVALID_ARG = @as(u32, 5);
pub const FAST_FAIL_GS_COOKIE_INIT = @as(u32, 6);
pub const FAST_FAIL_FATAL_APP_EXIT = @as(u32, 7);
pub const FAST_FAIL_RANGE_CHECK_FAILURE = @as(u32, 8);
pub const FAST_FAIL_UNSAFE_REGISTRY_ACCESS = @as(u32, 9);
pub const FAST_FAIL_GUARD_ICALL_CHECK_FAILURE = @as(u32, 10);
pub const FAST_FAIL_GUARD_WRITE_CHECK_FAILURE = @as(u32, 11);
pub const FAST_FAIL_INVALID_FIBER_SWITCH = @as(u32, 12);
pub const FAST_FAIL_INVALID_SET_OF_CONTEXT = @as(u32, 13);
pub const FAST_FAIL_INVALID_REFERENCE_COUNT = @as(u32, 14);
pub const FAST_FAIL_INVALID_JUMP_BUFFER = @as(u32, 18);
pub const FAST_FAIL_MRDATA_MODIFIED = @as(u32, 19);
pub const FAST_FAIL_CERTIFICATION_FAILURE = @as(u32, 20);
pub const FAST_FAIL_INVALID_EXCEPTION_CHAIN = @as(u32, 21);
pub const FAST_FAIL_CRYPTO_LIBRARY = @as(u32, 22);
pub const FAST_FAIL_INVALID_CALL_IN_DLL_CALLOUT = @as(u32, 23);
pub const FAST_FAIL_INVALID_IMAGE_BASE = @as(u32, 24);
pub const FAST_FAIL_DLOAD_PROTECTION_FAILURE = @as(u32, 25);
pub const FAST_FAIL_UNSAFE_EXTENSION_CALL = @as(u32, 26);
pub const FAST_FAIL_DEPRECATED_SERVICE_INVOKED = @as(u32, 27);
pub const FAST_FAIL_INVALID_BUFFER_ACCESS = @as(u32, 28);
pub const FAST_FAIL_INVALID_BALANCED_TREE = @as(u32, 29);
pub const FAST_FAIL_INVALID_NEXT_THREAD = @as(u32, 30);
pub const FAST_FAIL_GUARD_ICALL_CHECK_SUPPRESSED = @as(u32, 31);
pub const FAST_FAIL_APCS_DISABLED = @as(u32, 32);
pub const FAST_FAIL_INVALID_IDLE_STATE = @as(u32, 33);
pub const FAST_FAIL_MRDATA_PROTECTION_FAILURE = @as(u32, 34);
pub const FAST_FAIL_UNEXPECTED_HEAP_EXCEPTION = @as(u32, 35);
pub const FAST_FAIL_INVALID_LOCK_STATE = @as(u32, 36);
pub const FAST_FAIL_GUARD_JUMPTABLE = @as(u32, 37);
pub const FAST_FAIL_INVALID_LONGJUMP_TARGET = @as(u32, 38);
pub const FAST_FAIL_INVALID_DISPATCH_CONTEXT = @as(u32, 39);
pub const FAST_FAIL_INVALID_THREAD = @as(u32, 40);
pub const FAST_FAIL_INVALID_SYSCALL_NUMBER = @as(u32, 41);
pub const FAST_FAIL_INVALID_FILE_OPERATION = @as(u32, 42);
pub const FAST_FAIL_LPAC_ACCESS_DENIED = @as(u32, 43);
pub const FAST_FAIL_GUARD_SS_FAILURE = @as(u32, 44);
pub const FAST_FAIL_LOADER_CONTINUITY_FAILURE = @as(u32, 45);
pub const FAST_FAIL_GUARD_EXPORT_SUPPRESSION_FAILURE = @as(u32, 46);
pub const FAST_FAIL_INVALID_CONTROL_STACK = @as(u32, 47);
pub const FAST_FAIL_SET_CONTEXT_DENIED = @as(u32, 48);
pub const FAST_FAIL_INVALID_IAT = @as(u32, 49);
pub const FAST_FAIL_HEAP_METADATA_CORRUPTION = @as(u32, 50);
pub const FAST_FAIL_PAYLOAD_RESTRICTION_VIOLATION = @as(u32, 51);
pub const FAST_FAIL_LOW_LABEL_ACCESS_DENIED = @as(u32, 52);
pub const FAST_FAIL_ENCLAVE_CALL_FAILURE = @as(u32, 53);
pub const FAST_FAIL_UNHANDLED_LSS_EXCEPTON = @as(u32, 54);
pub const FAST_FAIL_ADMINLESS_ACCESS_DENIED = @as(u32, 55);
pub const FAST_FAIL_UNEXPECTED_CALL = @as(u32, 56);
pub const FAST_FAIL_CONTROL_INVALID_RETURN_ADDRESS = @as(u32, 57);
pub const FAST_FAIL_UNEXPECTED_HOST_BEHAVIOR = @as(u32, 58);
pub const FAST_FAIL_FLAGS_CORRUPTION = @as(u32, 59);
pub const FAST_FAIL_VEH_CORRUPTION = @as(u32, 60);
pub const FAST_FAIL_ETW_CORRUPTION = @as(u32, 61);
pub const FAST_FAIL_RIO_ABORT = @as(u32, 62);
pub const FAST_FAIL_INVALID_PFN = @as(u32, 63);
pub const FAST_FAIL_INVALID_FAST_FAIL_CODE = @as(u32, 4294967295);
pub const IS_TEXT_UNICODE_DBCS_LEADBYTE = @as(u32, 1024);
pub const COMPRESSION_FORMAT_NONE = @as(u32, 0);
pub const COMPRESSION_FORMAT_DEFAULT = @as(u32, 1);
pub const COMPRESSION_FORMAT_LZNT1 = @as(u32, 2);
pub const COMPRESSION_FORMAT_XPRESS = @as(u32, 3);
pub const COMPRESSION_FORMAT_XPRESS_HUFF = @as(u32, 4);
pub const COMPRESSION_ENGINE_STANDARD = @as(u32, 0);
pub const COMPRESSION_ENGINE_MAXIMUM = @as(u32, 256);
pub const COMPRESSION_ENGINE_HIBER = @as(u32, 512);
pub const SEF_AI_USE_EXTRA_PARAMS = @as(u32, 2048);
pub const SEF_FORCE_USER_MODE = @as(u32, 8192);
pub const MESSAGE_RESOURCE_UNICODE = @as(u32, 1);
pub const MESSAGE_RESOURCE_UTF8 = @as(u32, 2);
pub const VER_EQUAL = @as(u32, 1);
pub const VER_GREATER = @as(u32, 2);
pub const VER_GREATER_EQUAL = @as(u32, 3);
pub const VER_LESS = @as(u32, 4);
pub const VER_LESS_EQUAL = @as(u32, 5);
pub const VER_AND = @as(u32, 6);
pub const VER_OR = @as(u32, 7);
pub const VER_CONDITION_MASK = @as(u32, 7);
pub const VER_NUM_BITS_PER_CONDITION_MASK = @as(u32, 3);
pub const VER_NT_WORKSTATION = @as(u32, 1);
pub const VER_NT_DOMAIN_CONTROLLER = @as(u32, 2);
pub const VER_NT_SERVER = @as(u32, 3);
pub const RTL_UMS_VERSION = @as(u32, 256);
pub const VRL_PREDEFINED_CLASS_BEGIN = @as(u32, 1);
pub const VRL_CUSTOM_CLASS_BEGIN = @as(u32, 256);
pub const VRL_ENABLE_KERNEL_BREAKS = @as(u32, 2147483648);
pub const CTMF_INCLUDE_APPCONTAINER = @as(u32, 1);
pub const CTMF_INCLUDE_LPAC = @as(u32, 2);
pub const FLUSH_NV_MEMORY_IN_FLAG_NO_DRAIN = @as(u32, 1);
pub const WRITE_NV_MEMORY_FLAG_FLUSH = @as(u32, 1);
pub const WRITE_NV_MEMORY_FLAG_NON_TEMPORAL = @as(u32, 2);
pub const WRITE_NV_MEMORY_FLAG_NO_DRAIN = @as(u32, 256);
pub const FILL_NV_MEMORY_FLAG_FLUSH = @as(u32, 1);
pub const FILL_NV_MEMORY_FLAG_NON_TEMPORAL = @as(u32, 2);
pub const FILL_NV_MEMORY_FLAG_NO_DRAIN = @as(u32, 256);
pub const RTL_CORRELATION_VECTOR_STRING_LENGTH = @as(u32, 129);
pub const RTL_CORRELATION_VECTOR_V1_PREFIX_LENGTH = @as(u32, 16);
pub const RTL_CORRELATION_VECTOR_V1_LENGTH = @as(u32, 64);
pub const RTL_CORRELATION_VECTOR_V2_PREFIX_LENGTH = @as(u32, 22);
pub const RTL_CORRELATION_VECTOR_V2_LENGTH = @as(u32, 128);
pub const IMAGE_POLICY_METADATA_VERSION = @as(u32, 1);
pub const RTL_CRITICAL_SECTION_FLAG_NO_DEBUG_INFO = @as(u32, 16777216);
pub const RTL_CRITICAL_SECTION_FLAG_DYNAMIC_SPIN = @as(u32, 33554432);
pub const RTL_CRITICAL_SECTION_FLAG_STATIC_INIT = @as(u32, 67108864);
pub const RTL_CRITICAL_SECTION_FLAG_RESOURCE_TYPE = @as(u32, 134217728);
pub const RTL_CRITICAL_SECTION_FLAG_FORCE_DEBUG_INFO = @as(u32, 268435456);
pub const RTL_CRITICAL_SECTION_ALL_FLAG_BITS = @as(u32, 4278190080);
pub const RTL_CRITICAL_SECTION_DEBUG_FLAG_STATIC_INIT = @as(u32, 1);
pub const RTL_CONDITION_VARIABLE_LOCKMODE_SHARED = @as(u32, 1);
pub const HEAP_OPTIMIZE_RESOURCES_CURRENT_VERSION = @as(u32, 1);
pub const WT_EXECUTEINUITHREAD = @as(u32, 2);
pub const WT_EXECUTEINPERSISTENTIOTHREAD = @as(u32, 64);
pub const WT_EXECUTEINLONGTHREAD = @as(u32, 16);
pub const WT_EXECUTEDELETEWAIT = @as(u32, 8);
pub const ACTIVATION_CONTEXT_PATH_TYPE_NONE = @as(u32, 1);
pub const ACTIVATION_CONTEXT_PATH_TYPE_WIN32_FILE = @as(u32, 2);
pub const ACTIVATION_CONTEXT_PATH_TYPE_URL = @as(u32, 3);
pub const ACTIVATION_CONTEXT_PATH_TYPE_ASSEMBLYREF = @as(u32, 4);
pub const CREATE_BOUNDARY_DESCRIPTOR_ADD_APPCONTAINER_SID = @as(u32, 1);
pub const PERFORMANCE_DATA_VERSION = @as(u32, 1);
pub const READ_THREAD_PROFILING_FLAG_DISPATCHING = @as(u32, 1);
pub const READ_THREAD_PROFILING_FLAG_HARDWARE_COUNTERS = @as(u32, 2);
pub const UNIFIEDBUILDREVISION_MIN = @as(u32, 0);
pub const DEVICEFAMILYINFOENUM_UAP = @as(u32, 0);
pub const DEVICEFAMILYINFOENUM_WINDOWS_8X = @as(u32, 1);
pub const DEVICEFAMILYINFOENUM_WINDOWS_PHONE_8X = @as(u32, 2);
pub const DEVICEFAMILYINFOENUM_DESKTOP = @as(u32, 3);
pub const DEVICEFAMILYINFOENUM_MOBILE = @as(u32, 4);
pub const DEVICEFAMILYINFOENUM_XBOX = @as(u32, 5);
pub const DEVICEFAMILYINFOENUM_TEAM = @as(u32, 6);
pub const DEVICEFAMILYINFOENUM_IOT = @as(u32, 7);
pub const DEVICEFAMILYINFOENUM_IOT_HEADLESS = @as(u32, 8);
pub const DEVICEFAMILYINFOENUM_SERVER = @as(u32, 9);
pub const DEVICEFAMILYINFOENUM_HOLOGRAPHIC = @as(u32, 10);
pub const DEVICEFAMILYINFOENUM_XBOXSRA = @as(u32, 11);
pub const DEVICEFAMILYINFOENUM_XBOXERA = @as(u32, 12);
pub const DEVICEFAMILYINFOENUM_SERVER_NANO = @as(u32, 13);
pub const DEVICEFAMILYINFOENUM_8828080 = @as(u32, 14);
pub const DEVICEFAMILYINFOENUM_7067329 = @as(u32, 15);
pub const DEVICEFAMILYINFOENUM_WINDOWS_CORE = @as(u32, 16);
pub const DEVICEFAMILYINFOENUM_WINDOWS_CORE_HEADLESS = @as(u32, 17);
pub const DEVICEFAMILYINFOENUM_MAX = @as(u32, 17);
pub const DEVICEFAMILYDEVICEFORM_UNKNOWN = @as(u32, 0);
pub const DEVICEFAMILYDEVICEFORM_PHONE = @as(u32, 1);
pub const DEVICEFAMILYDEVICEFORM_TABLET = @as(u32, 2);
pub const DEVICEFAMILYDEVICEFORM_DESKTOP = @as(u32, 3);
pub const DEVICEFAMILYDEVICEFORM_NOTEBOOK = @as(u32, 4);
pub const DEVICEFAMILYDEVICEFORM_CONVERTIBLE = @as(u32, 5);
pub const DEVICEFAMILYDEVICEFORM_DETACHABLE = @as(u32, 6);
pub const DEVICEFAMILYDEVICEFORM_ALLINONE = @as(u32, 7);
pub const DEVICEFAMILYDEVICEFORM_STICKPC = @as(u32, 8);
pub const DEVICEFAMILYDEVICEFORM_PUCK = @as(u32, 9);
pub const DEVICEFAMILYDEVICEFORM_LARGESCREEN = @as(u32, 10);
pub const DEVICEFAMILYDEVICEFORM_HMD = @as(u32, 11);
pub const DEVICEFAMILYDEVICEFORM_INDUSTRY_HANDHELD = @as(u32, 12);
pub const DEVICEFAMILYDEVICEFORM_INDUSTRY_TABLET = @as(u32, 13);
pub const DEVICEFAMILYDEVICEFORM_BANKING = @as(u32, 14);
pub const DEVICEFAMILYDEVICEFORM_BUILDING_AUTOMATION = @as(u32, 15);
pub const DEVICEFAMILYDEVICEFORM_DIGITAL_SIGNAGE = @as(u32, 16);
pub const DEVICEFAMILYDEVICEFORM_GAMING = @as(u32, 17);
pub const DEVICEFAMILYDEVICEFORM_HOME_AUTOMATION = @as(u32, 18);
pub const DEVICEFAMILYDEVICEFORM_INDUSTRIAL_AUTOMATION = @as(u32, 19);
pub const DEVICEFAMILYDEVICEFORM_KIOSK = @as(u32, 20);
pub const DEVICEFAMILYDEVICEFORM_MAKER_BOARD = @as(u32, 21);
pub const DEVICEFAMILYDEVICEFORM_MEDICAL = @as(u32, 22);
pub const DEVICEFAMILYDEVICEFORM_NETWORKING = @as(u32, 23);
pub const DEVICEFAMILYDEVICEFORM_POINT_OF_SERVICE = @as(u32, 24);
pub const DEVICEFAMILYDEVICEFORM_PRINTING = @as(u32, 25);
pub const DEVICEFAMILYDEVICEFORM_THIN_CLIENT = @as(u32, 26);
pub const DEVICEFAMILYDEVICEFORM_TOY = @as(u32, 27);
pub const DEVICEFAMILYDEVICEFORM_VENDING = @as(u32, 28);
pub const DEVICEFAMILYDEVICEFORM_INDUSTRY_OTHER = @as(u32, 29);
pub const DEVICEFAMILYDEVICEFORM_XBOX_ONE = @as(u32, 30);
pub const DEVICEFAMILYDEVICEFORM_XBOX_ONE_S = @as(u32, 31);
pub const DEVICEFAMILYDEVICEFORM_XBOX_ONE_X = @as(u32, 32);
pub const DEVICEFAMILYDEVICEFORM_XBOX_ONE_X_DEVKIT = @as(u32, 33);
pub const DEVICEFAMILYDEVICEFORM_MAX = @as(u32, 33);
pub const DLL_PROCESS_ATTACH = @as(u32, 1);
pub const DLL_THREAD_ATTACH = @as(u32, 2);
pub const DLL_THREAD_DETACH = @as(u32, 3);
pub const DLL_PROCESS_DETACH = @as(u32, 0);
pub const EVENTLOG_FORWARDS_READ = @as(u32, 4);
pub const EVENTLOG_BACKWARDS_READ = @as(u32, 8);
pub const EVENTLOG_START_PAIRED_EVENT = @as(u32, 1);
pub const EVENTLOG_END_PAIRED_EVENT = @as(u32, 2);
pub const EVENTLOG_END_ALL_PAIRED_EVENTS = @as(u32, 4);
pub const EVENTLOG_PAIRED_EVENT_ACTIVE = @as(u32, 8);
pub const EVENTLOG_PAIRED_EVENT_INACTIVE = @as(u32, 16);
pub const MAXLOGICALLOGNAMESIZE = @as(u32, 256);
pub const REG_REFRESH_HIVE = @as(i32, 2);
pub const REG_NO_LAZY_FLUSH = @as(i32, 4);
pub const REG_APP_HIVE = @as(i32, 16);
pub const REG_PROCESS_PRIVATE = @as(i32, 32);
pub const REG_START_JOURNAL = @as(i32, 64);
pub const REG_HIVE_EXACT_FILE_GROWTH = @as(i32, 128);
pub const REG_HIVE_NO_RM = @as(i32, 256);
pub const REG_HIVE_SINGLE_LOG = @as(i32, 512);
pub const REG_BOOT_HIVE = @as(i32, 1024);
pub const REG_LOAD_HIVE_OPEN_HANDLE = @as(i32, 2048);
pub const REG_FLUSH_HIVE_FILE_GROWTH = @as(i32, 4096);
pub const REG_OPEN_READ_ONLY = @as(i32, 8192);
pub const REG_IMMUTABLE = @as(i32, 16384);
pub const REG_NO_IMPERSONATION_FALLBACK = @as(i32, 32768);
pub const REG_FORCE_UNLOAD = @as(u32, 1);
pub const SERVICE_USER_SERVICE = @as(u32, 64);
pub const SERVICE_USERSERVICE_INSTANCE = @as(u32, 128);
pub const SERVICE_INTERACTIVE_PROCESS = @as(u32, 256);
pub const SERVICE_PKG_SERVICE = @as(u32, 512);
pub const CM_SERVICE_NETWORK_BOOT_LOAD = @as(u32, 1);
pub const CM_SERVICE_VIRTUAL_DISK_BOOT_LOAD = @as(u32, 2);
pub const CM_SERVICE_USB_DISK_BOOT_LOAD = @as(u32, 4);
pub const CM_SERVICE_SD_DISK_BOOT_LOAD = @as(u32, 8);
pub const CM_SERVICE_USB3_DISK_BOOT_LOAD = @as(u32, 16);
pub const CM_SERVICE_MEASURED_BOOT_LOAD = @as(u32, 32);
pub const CM_SERVICE_VERIFIER_BOOT_LOAD = @as(u32, 64);
pub const CM_SERVICE_WINPE_BOOT_LOAD = @as(u32, 128);
pub const CM_SERVICE_RAM_DISK_BOOT_LOAD = @as(u32, 256);
pub const TAPE_PSEUDO_LOGICAL_POSITION = @as(i32, 2);
pub const TAPE_PSEUDO_LOGICAL_BLOCK = @as(i32, 3);
pub const TAPE_DRIVE_FIXED = @as(u32, 1);
pub const TAPE_DRIVE_SELECT = @as(u32, 2);
pub const TAPE_DRIVE_INITIATOR = @as(u32, 4);
pub const TAPE_DRIVE_ERASE_SHORT = @as(u32, 16);
pub const TAPE_DRIVE_ERASE_LONG = @as(u32, 32);
pub const TAPE_DRIVE_ERASE_BOP_ONLY = @as(u32, 64);
pub const TAPE_DRIVE_ERASE_IMMEDIATE = @as(u32, 128);
pub const TAPE_DRIVE_TAPE_CAPACITY = @as(u32, 256);
pub const TAPE_DRIVE_TAPE_REMAINING = @as(u32, 512);
pub const TAPE_DRIVE_FIXED_BLOCK = @as(u32, 1024);
pub const TAPE_DRIVE_VARIABLE_BLOCK = @as(u32, 2048);
pub const TAPE_DRIVE_WRITE_PROTECT = @as(u32, 4096);
pub const TAPE_DRIVE_EOT_WZ_SIZE = @as(u32, 8192);
pub const TAPE_DRIVE_ECC = @as(u32, 65536);
pub const TAPE_DRIVE_COMPRESSION = @as(u32, 131072);
pub const TAPE_DRIVE_PADDING = @as(u32, 262144);
pub const TAPE_DRIVE_REPORT_SMKS = @as(u32, 524288);
pub const TAPE_DRIVE_GET_ABSOLUTE_BLK = @as(u32, 1048576);
pub const TAPE_DRIVE_GET_LOGICAL_BLK = @as(u32, 2097152);
pub const TAPE_DRIVE_SET_EOT_WZ_SIZE = @as(u32, 4194304);
pub const TAPE_DRIVE_EJECT_MEDIA = @as(u32, 16777216);
pub const TAPE_DRIVE_CLEAN_REQUESTS = @as(u32, 33554432);
pub const TAPE_DRIVE_SET_CMP_BOP_ONLY = @as(u32, 67108864);
pub const TAPE_DRIVE_RESERVED_BIT = @as(u32, 2147483648);
pub const TAPE_DRIVE_FORMAT = @as(u32, 2684354560);
pub const TAPE_DRIVE_FORMAT_IMMEDIATE = @as(u32, 3221225472);
pub const TAPE_DRIVE_HIGH_FEATURES = @as(u32, 2147483648);
pub const TAPE_QUERY_DRIVE_PARAMETERS = @as(i32, 0);
pub const TAPE_QUERY_MEDIA_CAPACITY = @as(i32, 1);
pub const TAPE_CHECK_FOR_DRIVE_PROBLEM = @as(i32, 2);
pub const TAPE_QUERY_IO_ERROR_DATA = @as(i32, 3);
pub const TAPE_QUERY_DEVICE_ERROR_DATA = @as(i32, 4);
pub const TRANSACTIONMANAGER_QUERY_INFORMATION = @as(u32, 1);
pub const TRANSACTIONMANAGER_SET_INFORMATION = @as(u32, 2);
pub const TRANSACTIONMANAGER_RECOVER = @as(u32, 4);
pub const TRANSACTIONMANAGER_RENAME = @as(u32, 8);
pub const TRANSACTIONMANAGER_CREATE_RM = @as(u32, 16);
pub const TRANSACTIONMANAGER_BIND_TRANSACTION = @as(u32, 32);
pub const TRANSACTION_QUERY_INFORMATION = @as(u32, 1);
pub const TRANSACTION_SET_INFORMATION = @as(u32, 2);
pub const TRANSACTION_ENLIST = @as(u32, 4);
pub const TRANSACTION_COMMIT = @as(u32, 8);
pub const TRANSACTION_ROLLBACK = @as(u32, 16);
pub const TRANSACTION_PROPAGATE = @as(u32, 32);
pub const TRANSACTION_RIGHT_RESERVED1 = @as(u32, 64);
pub const RESOURCEMANAGER_QUERY_INFORMATION = @as(u32, 1);
pub const RESOURCEMANAGER_SET_INFORMATION = @as(u32, 2);
pub const RESOURCEMANAGER_RECOVER = @as(u32, 4);
pub const RESOURCEMANAGER_ENLIST = @as(u32, 8);
pub const RESOURCEMANAGER_GET_NOTIFICATION = @as(u32, 16);
pub const RESOURCEMANAGER_REGISTER_PROTOCOL = @as(u32, 32);
pub const RESOURCEMANAGER_COMPLETE_PROPAGATION = @as(u32, 64);
pub const ENLISTMENT_QUERY_INFORMATION = @as(u32, 1);
pub const ENLISTMENT_SET_INFORMATION = @as(u32, 2);
pub const ENLISTMENT_RECOVER = @as(u32, 4);
pub const ENLISTMENT_SUBORDINATE_RIGHTS = @as(u32, 8);
pub const ENLISTMENT_SUPERIOR_RIGHTS = @as(u32, 16);
pub const PcTeb = @as(u32, 24);
pub const ACTIVATION_CONTEXT_SECTION_ASSEMBLY_INFORMATION = @as(u32, 1);
pub const ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION = @as(u32, 2);
pub const ACTIVATION_CONTEXT_SECTION_WINDOW_CLASS_REDIRECTION = @as(u32, 3);
pub const ACTIVATION_CONTEXT_SECTION_COM_SERVER_REDIRECTION = @as(u32, 4);
pub const ACTIVATION_CONTEXT_SECTION_COM_INTERFACE_REDIRECTION = @as(u32, 5);
pub const ACTIVATION_CONTEXT_SECTION_COM_TYPE_LIBRARY_REDIRECTION = @as(u32, 6);
pub const ACTIVATION_CONTEXT_SECTION_COM_PROGID_REDIRECTION = @as(u32, 7);
pub const ACTIVATION_CONTEXT_SECTION_GLOBAL_OBJECT_RENAME_TABLE = @as(u32, 8);
pub const ACTIVATION_CONTEXT_SECTION_CLR_SURROGATES = @as(u32, 9);
pub const ACTIVATION_CONTEXT_SECTION_APPLICATION_SETTINGS = @as(u32, 10);
pub const ACTIVATION_CONTEXT_SECTION_COMPATIBILITY_INFO = @as(u32, 11);
pub const ACTIVATION_CONTEXT_SECTION_WINRT_ACTIVATABLE_CLASSES = @as(u32, 12);
pub const DEVPKEY_NAME = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("b725f130-47ef-101a-a5f1-02608c9eebac"), .pid = 10 };
pub const DEVPKEY_Device_DeviceDesc = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a45c254e-df1c-4efd-8020-67d146a850e0"), .pid = 2 };
pub const DEVPKEY_Device_HardwareIds = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a45c254e-df1c-4efd-8020-67d146a850e0"), .pid = 3 };
pub const DEVPKEY_Device_CompatibleIds = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a45c254e-df1c-4efd-8020-67d146a850e0"), .pid = 4 };
pub const DEVPKEY_Device_Service = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a45c254e-df1c-4efd-8020-67d146a850e0"), .pid = 6 };
pub const DEVPKEY_Device_Class = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a45c254e-df1c-4efd-8020-67d146a850e0"), .pid = 9 };
pub const DEVPKEY_Device_ClassGuid = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a45c254e-df1c-4efd-8020-67d146a850e0"), .pid = 10 };
pub const DEVPKEY_Device_Driver = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a45c254e-df1c-4efd-8020-67d146a850e0"), .pid = 11 };
pub const DEVPKEY_Device_ConfigFlags = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a45c254e-df1c-4efd-8020-67d146a850e0"), .pid = 12 };
pub const DEVPKEY_Device_Manufacturer = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a45c254e-df1c-4efd-8020-67d146a850e0"), .pid = 13 };
pub const DEVPKEY_Device_FriendlyName = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a45c254e-df1c-4efd-8020-67d146a850e0"), .pid = 14 };
pub const DEVPKEY_Device_LocationInfo = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a45c254e-df1c-4efd-8020-67d146a850e0"), .pid = 15 };
pub const DEVPKEY_Device_PDOName = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a45c254e-df1c-4efd-8020-67d146a850e0"), .pid = 16 };
pub const DEVPKEY_Device_Capabilities = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a45c254e-df1c-4efd-8020-67d146a850e0"), .pid = 17 };
pub const DEVPKEY_Device_UINumber = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a45c254e-df1c-4efd-8020-67d146a850e0"), .pid = 18 };
pub const DEVPKEY_Device_UpperFilters = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a45c254e-df1c-4efd-8020-67d146a850e0"), .pid = 19 };
pub const DEVPKEY_Device_LowerFilters = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a45c254e-df1c-4efd-8020-67d146a850e0"), .pid = 20 };
pub const DEVPKEY_Device_BusTypeGuid = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a45c254e-df1c-4efd-8020-67d146a850e0"), .pid = 21 };
pub const DEVPKEY_Device_LegacyBusType = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a45c254e-df1c-4efd-8020-67d146a850e0"), .pid = 22 };
pub const DEVPKEY_Device_BusNumber = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a45c254e-df1c-4efd-8020-67d146a850e0"), .pid = 23 };
pub const DEVPKEY_Device_EnumeratorName = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a45c254e-df1c-4efd-8020-67d146a850e0"), .pid = 24 };
pub const DEVPKEY_Device_Security = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a45c254e-df1c-4efd-8020-67d146a850e0"), .pid = 25 };
pub const DEVPKEY_Device_SecuritySDS = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a45c254e-df1c-4efd-8020-67d146a850e0"), .pid = 26 };
pub const DEVPKEY_Device_DevType = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a45c254e-df1c-4efd-8020-67d146a850e0"), .pid = 27 };
pub const DEVPKEY_Device_Exclusive = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a45c254e-df1c-4efd-8020-67d146a850e0"), .pid = 28 };
pub const DEVPKEY_Device_Characteristics = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a45c254e-df1c-4efd-8020-67d146a850e0"), .pid = 29 };
pub const DEVPKEY_Device_Address = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a45c254e-df1c-4efd-8020-67d146a850e0"), .pid = 30 };
pub const DEVPKEY_Device_UINumberDescFormat = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a45c254e-df1c-4efd-8020-67d146a850e0"), .pid = 31 };
pub const DEVPKEY_Device_PowerData = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a45c254e-df1c-4efd-8020-<KEY>"), .pid = 32 };
pub const DEVPKEY_Device_RemovalPolicy = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a45c254e-df1c-4efd-8020-67d146a850e0"), .pid = 33 };
pub const DEVPKEY_Device_RemovalPolicyDefault = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a45c254e-df1c-4efd-8020-67d146a850e0"), .pid = 34 };
pub const DEVPKEY_Device_RemovalPolicyOverride = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a45c254e-df1c-4efd-8020-67d146a850e0"), .pid = 35 };
pub const DEVPKEY_Device_InstallState = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a45c254e-df1c-4efd-8020-67d146a850e0"), .pid = 36 };
pub const DEVPKEY_Device_LocationPaths = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a45c254e-df1c-4efd-8020-67d146a850e0"), .pid = 37 };
pub const DEVPKEY_Device_BaseContainerId = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a45c254e-df1c-4efd-8020-67d146a850e0"), .pid = 38 };
pub const DEVPKEY_Device_InstanceId = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 256 };
pub const DEVPKEY_Device_DevNodeStatus = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("4340a6c5-93fa-4706-972c-7b648008a5a7"), .pid = 2 };
pub const DEVPKEY_Device_ProblemCode = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("4340a6c5-93fa-4706-972c-7b648008a5a7"), .pid = 3 };
pub const DEVPKEY_Device_EjectionRelations = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("4340a6c5-93fa-4706-972c-7b648008a5a7"), .pid = 4 };
pub const DEVPKEY_Device_RemovalRelations = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("4340a6c5-93fa-4706-972c-7b648008a5a7"), .pid = 5 };
pub const DEVPKEY_Device_PowerRelations = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("4340a6c5-93fa-4706-972c-7b648008a5a7"), .pid = 6 };
pub const DEVPKEY_Device_BusRelations = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("4340a6c5-93fa-4706-972c-7b648008a5a7"), .pid = 7 };
pub const DEVPKEY_Device_Parent = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("4340a6c5-93fa-4706-972c-<KEY>7"), .pid = 8 };
pub const DEVPKEY_Device_Children = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("4340a6c5-93fa-4706-972c-7b648008a5a7"), .pid = 9 };
pub const DEVPKEY_Device_Siblings = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("4340a6c5-93fa-4706-972c-7b648008a5a7"), .pid = 10 };
pub const DEVPKEY_Device_TransportRelations = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("4340a6c5-93fa-4706-972c-7b648008a5a7"), .pid = 11 };
pub const DEVPKEY_Device_ProblemStatus = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("4340a6c5-93fa-4706-972c-7b648008a5a7"), .pid = 12 };
pub const DEVPKEY_Device_Reported = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("80497100-8c73-48b9-aad9-ce387e19c56e"), .pid = 2 };
pub const DEVPKEY_Device_Legacy = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("80497100-8c73-48b9-aad9-ce387e19c56e"), .pid = 3 };
pub const DEVPKEY_Device_ContainerId = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("8c7ed206-3f8a-4827-b3ab-ae9e1faefc6c"), .pid = 2 };
pub const DEVPKEY_Device_InLocalMachineContainer = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("8c7ed206-3f8a-4827-b3ab-ae9e1faefc6c"), .pid = 4 };
pub const DEVPKEY_Device_Model = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 39 };
pub const DEVPKEY_Device_ModelId = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("80d81ea6-7473-4b0c-8216-efc11a2c4c8b"), .pid = 2 };
pub const DEVPKEY_Device_FriendlyNameAttributes = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("80d81ea6-7473-4b0c-8216-efc11a2c4c8b"), .pid = 3 };
pub const DEVPKEY_Device_ManufacturerAttributes = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("80d81ea6-7473-4b0c-8216-efc11a2c4c8b"), .pid = 4 };
pub const DEVPKEY_Device_PresenceNotForDevice = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("80d81ea6-7473-4b0c-8216-efc11a2c4c8b"), .pid = 5 };
pub const DEVPKEY_Device_SignalStrength = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("80d81ea6-7473-4b0c-8216-efc11a2c4c8b"), .pid = 6 };
pub const DEVPKEY_Device_IsAssociateableByUserAction = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("80d81ea6-7473-4b0c-8216-efc11a2c4c8b"), .pid = 7 };
pub const DEVPKEY_Device_ShowInUninstallUI = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("80d81ea6-7473-4b0c-8216-efc11a2c4c8b"), .pid = 8 };
pub const DEVPKEY_Device_Numa_Proximity_Domain = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("540b947e-8b40-45bc-a8a2-6a0b894cbda2"), .pid = 1 };
pub const DEVPKEY_Device_DHP_Rebalance_Policy = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("540b947e-8b40-45bc-a8a2-6a0b894cbda2"), .pid = 2 };
pub const DEVPKEY_Device_Numa_Node = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("540b947e-8b40-45bc-a8a2-6a0b894cbda2"), .pid = 3 };
pub const DEVPKEY_Device_BusReportedDeviceDesc = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("540b947e-8b40-<KEY>"), .pid = 4 };
pub const DEVPKEY_Device_IsPresent = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("540b947e-8b40-<KEY>"), .pid = 5 };
pub const DEVPKEY_Device_HasProblem = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("540b947e-8b40-45bc-a8a2-6a0b894cbda2"), .pid = 6 };
pub const DEVPKEY_Device_ConfigurationId = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("540b947e-8b40-45bc-a8a2-6a0b894cbda2"), .pid = 7 };
pub const DEVPKEY_Device_ReportedDeviceIdsHash = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("540b947e-8b40-45bc-a8a2-6a0b894cbda2"), .pid = 8 };
pub const DEVPKEY_Device_PhysicalDeviceLocation = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("540b947e-8b40-45bc-a8a2-6a0b894cbda2"), .pid = 9 };
pub const DEVPKEY_Device_BiosDeviceName = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("540b947e-8b40-45bc-a8a2-6a0b894cbda2"), .pid = 10 };
pub const DEVPKEY_Device_DriverProblemDesc = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("540b947e-8b40-45bc-a8a2-6a0b894cbda2"), .pid = 11 };
pub const DEVPKEY_Device_DebuggerSafe = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("540b947e-8b40-45bc-a8a2-6a0b894cbda2"), .pid = 12 };
pub const DEVPKEY_Device_PostInstallInProgress = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("540b947e-8b40-45bc-a8a2-6a0b894cbda2"), .pid = 13 };
pub const DEVPKEY_Device_Stack = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("540b947e-8b40-45bc-a8a2-6a0b894cbda2"), .pid = 14 };
pub const DEVPKEY_Device_ExtendedConfigurationIds = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("540b947e-8b40-45bc-a8a2-6a0b894cbda2"), .pid = 15 };
pub const DEVPKEY_Device_IsRebootRequired = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("540b947e-8b40-45bc-a8a2-6a0b894cbda2"), .pid = 16 };
pub const DEVPKEY_Device_FirmwareDate = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("540b947e-8b40-45bc-a8a2-6a0b894cbda2"), .pid = 17 };
pub const DEVPKEY_Device_FirmwareVersion = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("540b947e-8b40-45bc-a8a2-6a0b894cbda2"), .pid = 18 };
pub const DEVPKEY_Device_FirmwareRevision = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("540b947e-8b40-45bc-a8a2-6a0b894cbda2"), .pid = 19 };
pub const DEVPKEY_Device_DependencyProviders = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("540b947e-8b40-45bc-a8a2-6a0b894cbda2"), .pid = 20 };
pub const DEVPKEY_Device_DependencyDependents = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("540b947e-8b40-45bc-a8a2-6a0b894cbda2"), .pid = 21 };
pub const DEVPKEY_Device_SoftRestartSupported = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("540b947e-8b40-45bc-a8a2-6a0b894cbda2"), .pid = 22 };
pub const DEVPKEY_Device_ExtendedAddress = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("540b947e-8b40-45bc-a8a2-6a0b894cbda2"), .pid = 23 };
pub const DEVPKEY_Device_AssignedToGuest = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("540b947e-8b40-45bc-a8a2-6a0b894cbda2"), .pid = 24 };
pub const DEVPKEY_Device_SessionId = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("83da6326-97a6-4088-9453-a1923f573b29"), .pid = 6 };
pub const DEVPKEY_Device_InstallDate = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("83da6326-97a6-4088-9453-a1923f573b29"), .pid = 100 };
pub const DEVPKEY_Device_FirstInstallDate = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("83da6326-97a6-4088-9453-a1923f573b29"), .pid = 101 };
pub const DEVPKEY_Device_LastArrivalDate = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("83da6326-97a6-4088-9453-a1923f573b29"), .pid = 102 };
pub const DEVPKEY_Device_LastRemovalDate = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("83da6326-97a6-4088-9453-a1923f573b29"), .pid = 103 };
pub const DEVPKEY_Device_DriverDate = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a8b865dd-2e3d-4094-ad97-e593a70c75d6"), .pid = 2 };
pub const DEVPKEY_Device_DriverVersion = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a8b865dd-2e3d-4094-ad97-e593a70c75d6"), .pid = 3 };
pub const DEVPKEY_Device_DriverDesc = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a8b865dd-2e3d-4094-ad97-e593a70c75d6"), .pid = 4 };
pub const DEVPKEY_Device_DriverInfPath = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a8b865dd-2e3d-4094-ad97-e593a70c75d6"), .pid = 5 };
pub const DEVPKEY_Device_DriverInfSection = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a8b865dd-2e3d-4094-ad97-e593a70c75d6"), .pid = 6 };
pub const DEVPKEY_Device_DriverInfSectionExt = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a8b865dd-2e3d-4094-ad97-e593a70c75d6"), .pid = 7 };
pub const DEVPKEY_Device_MatchingDeviceId = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a8b865dd-2e3d-4094-ad97-e593a70c75d6"), .pid = 8 };
pub const DEVPKEY_Device_DriverProvider = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a8b865dd-2e3d-4094-ad97-e593a70c75d6"), .pid = 9 };
pub const DEVPKEY_Device_DriverPropPageProvider = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a8b865dd-2e3d-4094-ad97-e593a70c75d6"), .pid = 10 };
pub const DEVPKEY_Device_DriverCoInstallers = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a8b865dd-2e3d-4094-ad97-e593a70c75d6"), .pid = 11 };
pub const DEVPKEY_Device_ResourcePickerTags = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a8b865dd-2e3d-4094-ad97-e593a70c75d6"), .pid = 12 };
pub const DEVPKEY_Device_ResourcePickerExceptions = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a8b865dd-2e3d-4094-ad97-e593a70c75d6"), .pid = 13 };
pub const DEVPKEY_Device_DriverRank = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a8b865dd-2e3d-4094-ad97-e593a70c75d6"), .pid = 14 };
pub const DEVPKEY_Device_DriverLogoLevel = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a8b865dd-2e3d-4094-ad97-e593a70c75d6"), .pid = 15 };
pub const DEVPKEY_Device_NoConnectSound = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a8b865dd-2e3d-4094-ad97-e593a70c75d6"), .pid = 17 };
pub const DEVPKEY_Device_GenericDriverInstalled = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a8b865dd-2e3d-4094-ad97-e593a70c75d6"), .pid = 18 };
pub const DEVPKEY_Device_AdditionalSoftwareRequested = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("a8b865dd-2e3d-4094-ad97-e593a70c75d6"), .pid = 19 };
pub const DEVPKEY_Device_SafeRemovalRequired = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("afd97640-86a3-4210-b67c-289c41aabe55"), .pid = 2 };
pub const DEVPKEY_Device_SafeRemovalRequiredOverride = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("afd97640-86a3-4210-b67c-289c41aabe55"), .pid = 3 };
pub const DEVPKEY_DrvPkg_Model = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("cf73bb51-3abf-44a2-85e0-9a3dc7a12132"), .pid = 2 };
pub const DEVPKEY_DrvPkg_VendorWebSite = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("cf73bb51-3abf-44a2-85e0-9a3dc7a12132"), .pid = 3 };
pub const DEVPKEY_DrvPkg_DetailedDescription = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("cf73bb51-3abf-44a2-85e0-9a3dc7a12132"), .pid = 4 };
pub const DEVPKEY_DrvPkg_DocumentationLink = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("cf73bb51-3abf-44a2-85e0-9a3dc7a12132"), .pid = 5 };
pub const DEVPKEY_DrvPkg_Icon = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("cf73bb51-3abf-44a2-85e0-9a3dc7a12132"), .pid = 6 };
pub const DEVPKEY_DrvPkg_BrandingIcon = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("cf73bb51-3abf-44a2-85e0-9a3dc7a12132"), .pid = 7 };
pub const DEVPKEY_DeviceClass_UpperFilters = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("4321918b-f69e-470d-a5de-4d88c75ad24b"), .pid = 19 };
pub const DEVPKEY_DeviceClass_LowerFilters = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("4321918b-f69e-470d-a5de-4d88c75ad24b"), .pid = 20 };
pub const DEVPKEY_DeviceClass_Security = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("4321918b-f69e-470d-a5de-4d88c75ad24b"), .pid = 25 };
pub const DEVPKEY_DeviceClass_SecuritySDS = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("4321918b-f69e-470d-a5de-4d88c75ad24b"), .pid = 26 };
pub const DEVPKEY_DeviceClass_DevType = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("4321918b-f69e-470d-a5de-4d88c75ad24b"), .pid = 27 };
pub const DEVPKEY_DeviceClass_Exclusive = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("4321918b-f69e-470d-a5de-4d88c75ad24b"), .pid = 28 };
pub const DEVPKEY_DeviceClass_Characteristics = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("4321918b-f69e-470d-a5de-4d88c75ad24b"), .pid = 29 };
pub const DEVPKEY_DeviceClass_Name = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("259abffc-50a7-47ce-af08-68c9a7d73366"), .pid = 2 };
pub const DEVPKEY_DeviceClass_ClassName = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("259abffc-50a7-47ce-af08-68c9a7d73366"), .pid = 3 };
pub const DEVPKEY_DeviceClass_Icon = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("259abffc-50a7-47ce-af08-68c9a7d73366"), .pid = 4 };
pub const DEVPKEY_DeviceClass_ClassInstaller = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("259abffc-50a7-47ce-af08-68c9a7d73366"), .pid = 5 };
pub const DEVPKEY_DeviceClass_PropPageProvider = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("259abffc-50a7-47ce-af08-68c9a7d73366"), .pid = 6 };
pub const DEVPKEY_DeviceClass_NoInstallClass = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("259abffc-50a7-47ce-af08-68c9a7d73366"), .pid = 7 };
pub const DEVPKEY_DeviceClass_NoDisplayClass = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("259abffc-50a7-47ce-af08-68c9a7d73366"), .pid = 8 };
pub const DEVPKEY_DeviceClass_SilentInstall = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("259abffc-50a7-47ce-af08-68c9a7d73366"), .pid = 9 };
pub const DEVPKEY_DeviceClass_NoUseClass = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("259abffc-50a7-47ce-af08-68c9a7d73366"), .pid = 10 };
pub const DEVPKEY_DeviceClass_DefaultService = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("259abffc-50a7-47ce-af08-68c9a7d73366"), .pid = 11 };
pub const DEVPKEY_DeviceClass_IconPath = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("259abffc-50a7-47ce-af08-68c9a7d73366"), .pid = 12 };
pub const DEVPKEY_DeviceClass_DHPRebalanceOptOut = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("d14d3ef3-66cf-4ba2-9d38-0ddb37ab4701"), .pid = 2 };
pub const DEVPKEY_DeviceClass_ClassCoInstallers = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("713d1703-a2e2-49f5-9214-56472ef3da5c"), .pid = 2 };
pub const DEVPKEY_DeviceInterface_FriendlyName = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("026e516e-b814-414b-83cd-856d6fef4822"), .pid = 2 };
pub const DEVPKEY_DeviceInterface_Enabled = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("026e516e-b814-414b-83cd-856d6fef4822"), .pid = 3 };
pub const DEVPKEY_DeviceInterface_ClassGuid = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("026e516e-b814-414b-83cd-856d6fef4822"), .pid = 4 };
pub const DEVPKEY_DeviceInterface_ReferenceString = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("026e516e-b814-414b-83cd-856d6fef4822"), .pid = 5 };
pub const DEVPKEY_DeviceInterface_Restricted = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("026e516e-b814-414b-83cd-856d6fef4822"), .pid = 6 };
pub const DEVPKEY_DeviceInterface_UnrestrictedAppCapabilities = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("026e516e-b814-414b-83cd-856d6fef4822"), .pid = 8 };
pub const DEVPKEY_DeviceInterface_SchematicName = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("026e516e-b814-414b-83cd-856d6fef4822"), .pid = 9 };
pub const DEVPKEY_DeviceInterfaceClass_DefaultInterface = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("14c83a99-0b3f-44b7-be4c-a178d3990564"), .pid = 2 };
pub const DEVPKEY_DeviceInterfaceClass_Name = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("14c83a99-0b3f-44b7-be4c-a178d3990564"), .pid = 3 };
pub const DEVPKEY_DeviceContainer_Address = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 51 };
pub const DEVPKEY_DeviceContainer_DiscoveryMethod = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 52 };
pub const DEVPKEY_DeviceContainer_IsEncrypted = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 53 };
pub const DEVPKEY_DeviceContainer_IsAuthenticated = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 54 };
pub const DEVPKEY_DeviceContainer_IsConnected = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 55 };
pub const DEVPKEY_DeviceContainer_IsPaired = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 56 };
pub const DEVPKEY_DeviceContainer_Icon = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 57 };
pub const DEVPKEY_DeviceContainer_Version = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 65 };
pub const DEVPKEY_DeviceContainer_Last_Seen = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 66 };
pub const DEVPKEY_DeviceContainer_Last_Connected = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 67 };
pub const DEVPKEY_DeviceContainer_IsShowInDisconnectedState = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 68 };
pub const DEVPKEY_DeviceContainer_IsLocalMachine = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 70 };
pub const DEVPKEY_DeviceContainer_MetadataPath = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 71 };
pub const DEVPKEY_DeviceContainer_IsMetadataSearchInProgress = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 72 };
pub const DEVPKEY_DeviceContainer_MetadataChecksum = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 73 };
pub const DEVPKEY_DeviceContainer_IsNotInterestingForDisplay = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 74 };
pub const DEVPKEY_DeviceContainer_LaunchDeviceStageOnDeviceConnect = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 76 };
pub const DEVPKEY_DeviceContainer_LaunchDeviceStageFromExplorer = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 77 };
pub const DEVPKEY_DeviceContainer_BaselineExperienceId = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 78 };
pub const DEVPKEY_DeviceContainer_IsDeviceUniquelyIdentifiable = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 79 };
pub const DEVPKEY_DeviceContainer_AssociationArray = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 80 };
pub const DEVPKEY_DeviceContainer_DeviceDescription1 = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 81 };
pub const DEVPKEY_DeviceContainer_DeviceDescription2 = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 82 };
pub const DEVPKEY_DeviceContainer_HasProblem = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 83 };
pub const DEVPKEY_DeviceContainer_IsSharedDevice = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 84 };
pub const DEVPKEY_DeviceContainer_IsNetworkDevice = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 85 };
pub const DEVPKEY_DeviceContainer_IsDefaultDevice = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 86 };
pub const DEVPKEY_DeviceContainer_MetadataCabinet = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 87 };
pub const DEVPKEY_DeviceContainer_RequiresPairingElevation = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 88 };
pub const DEVPKEY_DeviceContainer_ExperienceId = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 89 };
pub const DEVPKEY_DeviceContainer_Category = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 90 };
pub const DEVPKEY_DeviceContainer_Category_Desc_Singular = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 91 };
pub const DEVPKEY_DeviceContainer_Category_Desc_Plural = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 92 };
pub const DEVPKEY_DeviceContainer_Category_Icon = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 93 };
pub const DEVPKEY_DeviceContainer_CategoryGroup_Desc = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 94 };
pub const DEVPKEY_DeviceContainer_CategoryGroup_Icon = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 95 };
pub const DEVPKEY_DeviceContainer_PrimaryCategory = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 97 };
pub const DEVPKEY_DeviceContainer_UnpairUninstall = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 98 };
pub const DEVPKEY_DeviceContainer_RequiresUninstallElevation = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 99 };
pub const DEVPKEY_DeviceContainer_DeviceFunctionSubRank = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 100 };
pub const DEVPKEY_DeviceContainer_AlwaysShowDeviceAsConnected = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 101 };
pub const DEVPKEY_DeviceContainer_ConfigFlags = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 105 };
pub const DEVPKEY_DeviceContainer_PrivilegedPackageFamilyNames = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 106 };
pub const DEVPKEY_DeviceContainer_CustomPrivilegedPackageFamilyNames = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 107 };
pub const DEVPKEY_DeviceContainer_IsRebootRequired = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("78c34fc8-104a-4aca-9ea4-524d52996e57"), .pid = 108 };
pub const DEVPKEY_DeviceContainer_FriendlyName = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("656a3bb3-ecc0-43fd-8477-4ae0404a96cd"), .pid = 12288 };
pub const DEVPKEY_DeviceContainer_Manufacturer = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("656a3bb3-ecc0-43fd-8477-4ae0404a96cd"), .pid = 8192 };
pub const DEVPKEY_DeviceContainer_ModelName = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("656a3bb3-ecc0-43fd-8477-4ae0404a96cd"), .pid = 8194 };
pub const DEVPKEY_DeviceContainer_ModelNumber = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("656a3bb3-ecc0-43fd-8477-4ae0404a96cd"), .pid = 8195 };
pub const DEVPKEY_DeviceContainer_InstallInProgress = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("83da6326-97a6-4088-9453-a1923f573b29"), .pid = 9 };
pub const DEVPKEY_DevQuery_ObjectType = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("13673f42-a3d6-49f6-b4da-ae46e0c5237c"), .pid = 2 };
pub const GUID_DEVINTERFACE_DISK = Guid.initString("53f56307-b6bf-11d0-94f2-00a0c91efb8b");
pub const GUID_DEVINTERFACE_CDROM = Guid.initString("53f56308-b6bf-11d0-94f2-00a0c91efb8b");
pub const GUID_DEVINTERFACE_PARTITION = Guid.initString("53f5630a-b6bf-11d0-94f2-00a0c91efb8b");
pub const GUID_DEVINTERFACE_TAPE = Guid.initString("53f5630b-b6bf-11d0-94f2-00a0c91efb8b");
pub const GUID_DEVINTERFACE_WRITEONCEDISK = Guid.initString("53f5630c-b6bf-11d0-94f2-00a0c91efb8b");
pub const GUID_DEVINTERFACE_VOLUME = Guid.initString("53f5630d-b6bf-11d0-94f2-00a0c91efb8b");
pub const GUID_DEVINTERFACE_MEDIUMCHANGER = Guid.initString("53f56310-b6bf-11d0-94f2-00a0c91efb8b");
pub const GUID_DEVINTERFACE_FLOPPY = Guid.initString("53f56311-b6bf-11d0-94f2-00a0c91efb8b");
pub const GUID_DEVINTERFACE_CDCHANGER = Guid.initString("53f56312-b6bf-11d0-94f2-00a0c91efb8b");
pub const GUID_DEVINTERFACE_STORAGEPORT = Guid.initString("2accfe60-c130-11d2-b082-00a0c91efb8b");
pub const GUID_DEVINTERFACE_VMLUN = Guid.initString("6f416619-9f29-42a5-b20b-37e219ca02b0");
pub const GUID_DEVINTERFACE_SES = Guid.initString("1790c9ec-47d5-4df3-b5af-9adf3cf23e48");
pub const GUID_DEVINTERFACE_SERVICE_VOLUME = Guid.initString("6ead3d82-25ec-46bc-b7fd-c1f0df8f5037");
pub const GUID_DEVINTERFACE_HIDDEN_VOLUME = Guid.initString("7f108a28-9833-4b3b-b780-2c6b5fa5c062");
pub const GUID_DEVINTERFACE_UNIFIED_ACCESS_RPMB = Guid.initString("27447c21-bcc3-4d07-a05b-a3395bb4eee7");
pub const GUID_DEVICEDUMP_STORAGE_DEVICE = Guid.initString("d8e2592f-1aab-4d56-a746-1f7585df40f4");
pub const GUID_DEVICEDUMP_DRIVER_STORAGE_PORT = Guid.initString("da82441d-7142-4bc1-b844-0807c5a4b67f");
pub const DEVPKEY_Storage_Portable = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("4d1ebee8-0803-4774-9842-b77db50265e9"), .pid = 2 };
pub const DEVPKEY_Storage_Removable_Media = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("4d1ebee8-0803-4774-9842-b77db50265e9"), .pid = 3 };
pub const DEVPKEY_Storage_System_Critical = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("4d1ebee8-0803-4774-9842-b77db50265e9"), .pid = 4 };
pub const DEVPKEY_Storage_Disk_Number = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("4d1ebee8-0803-4774-9842-b77db50265e9"), .pid = 5 };
pub const DEVPKEY_Storage_Partition_Number = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("4d1ebee8-0803-4774-9842-b77db50265e9"), .pid = 6 };
pub const DEVPKEY_Storage_Mbr_Type = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("4d1ebee8-0803-4774-9842-b77db50265e9"), .pid = 7 };
pub const DEVPKEY_Storage_Gpt_Type = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("4d1ebee8-0803-4774-9842-b77db50265e9"), .pid = 8 };
pub const DEVPKEY_Storage_Gpt_Name = PROPERTYKEY { .fmtid = @import("../zig.zig").Guid.initString("4d1ebee8-0803-4774-9842-b77db50265e9"), .pid = 9 };
pub const IOCTL_STORAGE_CHECK_VERIFY = @as(u32, 2967552);
pub const IOCTL_STORAGE_CHECK_VERIFY2 = @as(u32, 2951168);
pub const IOCTL_STORAGE_MEDIA_REMOVAL = @as(u32, 2967556);
pub const IOCTL_STORAGE_EJECT_MEDIA = @as(u32, 2967560);
pub const IOCTL_STORAGE_LOAD_MEDIA = @as(u32, 2967564);
pub const IOCTL_STORAGE_LOAD_MEDIA2 = @as(u32, 2951180);
pub const IOCTL_STORAGE_RESERVE = @as(u32, 2967568);
pub const IOCTL_STORAGE_RELEASE = @as(u32, 2967572);
pub const IOCTL_STORAGE_FIND_NEW_DEVICES = @as(u32, 2967576);
pub const IOCTL_STORAGE_EJECTION_CONTROL = @as(u32, 2951488);
pub const IOCTL_STORAGE_MCN_CONTROL = @as(u32, 2951492);
pub const IOCTL_STORAGE_GET_MEDIA_TYPES = @as(u32, 2952192);
pub const IOCTL_STORAGE_GET_MEDIA_TYPES_EX = @as(u32, 2952196);
pub const IOCTL_STORAGE_GET_MEDIA_SERIAL_NUMBER = @as(u32, 2952208);
pub const IOCTL_STORAGE_GET_HOTPLUG_INFO = @as(u32, 2952212);
pub const IOCTL_STORAGE_SET_HOTPLUG_INFO = @as(u32, 3001368);
pub const IOCTL_STORAGE_RESET_BUS = @as(u32, 2969600);
pub const IOCTL_STORAGE_RESET_DEVICE = @as(u32, 2969604);
pub const IOCTL_STORAGE_BREAK_RESERVATION = @as(u32, 2969620);
pub const IOCTL_STORAGE_PERSISTENT_RESERVE_IN = @as(u32, 2969624);
pub const IOCTL_STORAGE_PERSISTENT_RESERVE_OUT = @as(u32, 3002396);
pub const IOCTL_STORAGE_GET_DEVICE_NUMBER = @as(u32, 2953344);
pub const IOCTL_STORAGE_GET_DEVICE_NUMBER_EX = @as(u32, 2953348);
pub const IOCTL_STORAGE_PREDICT_FAILURE = @as(u32, 2953472);
pub const IOCTL_STORAGE_FAILURE_PREDICTION_CONFIG = @as(u32, 2953476);
pub const IOCTL_STORAGE_GET_COUNTERS = @as(u32, 2953480);
pub const IOCTL_STORAGE_READ_CAPACITY = @as(u32, 2969920);
pub const IOCTL_STORAGE_GET_DEVICE_TELEMETRY = @as(u32, 3002816);
pub const IOCTL_STORAGE_DEVICE_TELEMETRY_NOTIFY = @as(u32, 3002820);
pub const IOCTL_STORAGE_DEVICE_TELEMETRY_QUERY_CAPS = @as(u32, 3002824);
pub const IOCTL_STORAGE_GET_DEVICE_TELEMETRY_RAW = @as(u32, 3002828);
pub const IOCTL_STORAGE_SET_TEMPERATURE_THRESHOLD = @as(u32, 3002880);
pub const IOCTL_STORAGE_PROTOCOL_COMMAND = @as(u32, 3003328);
pub const IOCTL_STORAGE_QUERY_PROPERTY = @as(u32, 2954240);
pub const IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES = @as(u32, 2987012);
pub const IOCTL_STORAGE_GET_LB_PROVISIONING_MAP_RESOURCES = @as(u32, 2970632);
pub const IOCTL_STORAGE_SET_PROPERTY = @as(u32, 2987020);
pub const IOCTL_STORAGE_REINITIALIZE_MEDIA = @as(u32, 2987584);
pub const IOCTL_STORAGE_GET_BC_PROPERTIES = @as(u32, 2971648);
pub const IOCTL_STORAGE_ALLOCATE_BC_STREAM = @as(u32, 3004420);
pub const IOCTL_STORAGE_FREE_BC_STREAM = @as(u32, 3004424);
pub const IOCTL_STORAGE_CHECK_PRIORITY_HINT_SUPPORT = @as(u32, 2955392);
pub const IOCTL_STORAGE_START_DATA_INTEGRITY_CHECK = @as(u32, 3004548);
pub const IOCTL_STORAGE_STOP_DATA_INTEGRITY_CHECK = @as(u32, 3004552);
pub const OBSOLETE_IOCTL_STORAGE_RESET_BUS = @as(u32, 3002368);
pub const OBSOLETE_IOCTL_STORAGE_RESET_DEVICE = @as(u32, 3002372);
pub const IOCTL_STORAGE_FIRMWARE_GET_INFO = @as(u32, 2956288);
pub const IOCTL_STORAGE_FIRMWARE_DOWNLOAD = @as(u32, 3005444);
pub const IOCTL_STORAGE_FIRMWARE_ACTIVATE = @as(u32, 3005448);
pub const IOCTL_STORAGE_ENABLE_IDLE_POWER = @as(u32, 2956416);
pub const IOCTL_STORAGE_GET_IDLE_POWERUP_REASON = @as(u32, 2956420);
pub const IOCTL_STORAGE_POWER_ACTIVE = @as(u32, 2956424);
pub const IOCTL_STORAGE_POWER_IDLE = @as(u32, 2956428);
pub const IOCTL_STORAGE_EVENT_NOTIFICATION = @as(u32, 2956432);
pub const IOCTL_STORAGE_DEVICE_POWER_CAP = @as(u32, 2956436);
pub const IOCTL_STORAGE_RPMB_COMMAND = @as(u32, 2956440);
pub const IOCTL_STORAGE_ATTRIBUTE_MANAGEMENT = @as(u32, 3005596);
pub const IOCTL_STORAGE_DIAGNOSTIC = @as(u32, 2956448);
pub const IOCTL_STORAGE_GET_PHYSICAL_ELEMENT_STATUS = @as(u32, 2956452);
pub const IOCTL_STORAGE_REMOVE_ELEMENT_AND_TRUNCATE = @as(u32, 2956480);
pub const IOCTL_STORAGE_GET_DEVICE_INTERNAL_LOG = @as(u32, 2956484);
pub const STORAGE_DEVICE_FLAGS_RANDOM_DEVICEGUID_REASON_CONFLICT = @as(u32, 1);
pub const STORAGE_DEVICE_FLAGS_RANDOM_DEVICEGUID_REASON_NOHWID = @as(u32, 2);
pub const STORAGE_DEVICE_FLAGS_PAGE_83_DEVICEGUID = @as(u32, 4);
pub const RECOVERED_WRITES_VALID = @as(u32, 1);
pub const UNRECOVERED_WRITES_VALID = @as(u32, 2);
pub const RECOVERED_READS_VALID = @as(u32, 4);
pub const UNRECOVERED_READS_VALID = @as(u32, 8);
pub const WRITE_COMPRESSION_INFO_VALID = @as(u32, 16);
pub const READ_COMPRESSION_INFO_VALID = @as(u32, 32);
pub const TAPE_RETURN_STATISTICS = @as(i32, 0);
pub const TAPE_RETURN_ENV_INFO = @as(i32, 1);
pub const TAPE_RESET_STATISTICS = @as(i32, 2);
pub const MEDIA_ERASEABLE = @as(u32, 1);
pub const MEDIA_WRITE_ONCE = @as(u32, 2);
pub const MEDIA_READ_ONLY = @as(u32, 4);
pub const MEDIA_READ_WRITE = @as(u32, 8);
pub const MEDIA_WRITE_PROTECTED = @as(u32, 256);
pub const MEDIA_CURRENTLY_MOUNTED = @as(u32, 2147483648);
pub const STORAGE_FAILURE_PREDICTION_CONFIG_V1 = @as(u32, 1);
pub const SRB_TYPE_SCSI_REQUEST_BLOCK = @as(u32, 0);
pub const SRB_TYPE_STORAGE_REQUEST_BLOCK = @as(u32, 1);
pub const STORAGE_ADDRESS_TYPE_BTL8 = @as(u32, 0);
pub const STORAGE_RPMB_DESCRIPTOR_VERSION_1 = @as(u32, 1);
pub const STORAGE_RPMB_MINIMUM_RELIABLE_WRITE_SIZE = @as(u32, 512);
pub const STORAGE_CRYPTO_CAPABILITY_VERSION_1 = @as(u32, 1);
pub const STORAGE_CRYPTO_DESCRIPTOR_VERSION_1 = @as(u32, 1);
pub const STORAGE_TIER_NAME_LENGTH = @as(u32, 256);
pub const STORAGE_TIER_DESCRIPTION_LENGTH = @as(u32, 512);
pub const STORAGE_TIER_FLAG_NO_SEEK_PENALTY = @as(u32, 131072);
pub const STORAGE_TIER_FLAG_WRITE_BACK_CACHE = @as(u32, 2097152);
pub const STORAGE_TIER_FLAG_READ_CACHE = @as(u32, 4194304);
pub const STORAGE_TIER_FLAG_PARITY = @as(u32, 8388608);
pub const STORAGE_TIER_FLAG_SMR = @as(u32, 16777216);
pub const STORAGE_TEMPERATURE_VALUE_NOT_REPORTED = @as(u32, 32768);
pub const STORAGE_TEMPERATURE_THRESHOLD_FLAG_ADAPTER_REQUEST = @as(u32, 1);
pub const STORAGE_COMPONENT_ROLE_CACHE = @as(u32, 1);
pub const STORAGE_COMPONENT_ROLE_TIERING = @as(u32, 2);
pub const STORAGE_COMPONENT_ROLE_DATA = @as(u32, 4);
pub const STORAGE_ATTRIBUTE_BYTE_ADDRESSABLE_IO = @as(u32, 1);
pub const STORAGE_ATTRIBUTE_BLOCK_IO = @as(u32, 2);
pub const STORAGE_ATTRIBUTE_DYNAMIC_PERSISTENCE = @as(u32, 4);
pub const STORAGE_ATTRIBUTE_VOLATILE = @as(u32, 8);
pub const STORAGE_ATTRIBUTE_ASYNC_EVENT_NOTIFICATION = @as(u32, 16);
pub const STORAGE_ATTRIBUTE_PERF_SIZE_INDEPENDENT = @as(u32, 32);
pub const STORAGE_DEVICE_MAX_OPERATIONAL_STATUS = @as(u32, 16);
pub const STORAGE_ADAPTER_SERIAL_NUMBER_V1_MAX_LENGTH = @as(u32, 128);
pub const DeviceDsmActionFlag_NonDestructive = @as(u32, 2147483648);
pub const DEVICE_DSM_FLAG_ENTIRE_DATA_SET_RANGE = @as(u32, 1);
pub const DEVICE_DSM_FLAG_TRIM_NOT_FS_ALLOCATED = @as(u32, 2147483648);
pub const DEVICE_DSM_FLAG_TRIM_BYPASS_RZAT = @as(u32, 1073741824);
pub const DEVICE_DSM_NOTIFY_FLAG_BEGIN = @as(u32, 1);
pub const DEVICE_DSM_NOTIFY_FLAG_END = @as(u32, 2);
pub const STORAGE_OFFLOAD_MAX_TOKEN_LENGTH = @as(u32, 512);
pub const STORAGE_OFFLOAD_TOKEN_ID_LENGTH = @as(u32, 504);
pub const STORAGE_OFFLOAD_TOKEN_TYPE_ZERO_DATA = @as(u32, 4294901761);
pub const STORAGE_OFFLOAD_READ_RANGE_TRUNCATED = @as(u32, 1);
pub const STORAGE_OFFLOAD_WRITE_RANGE_TRUNCATED = @as(u32, 1);
pub const STORAGE_OFFLOAD_TOKEN_INVALID = @as(u32, 2);
pub const DEVICE_DSM_FLAG_ALLOCATION_CONSOLIDATEABLE_ONLY = @as(u32, 1073741824);
pub const DEVICE_DSM_PARAMETERS_V1 = @as(u32, 1);
pub const DEVICE_DSM_FLAG_REPAIR_INPUT_TOPOLOGY_ID_PRESENT = @as(u32, 1073741824);
pub const DEVICE_DSM_FLAG_REPAIR_OUTPUT_PARITY_EXTENT = @as(u32, 536870912);
pub const DEVICE_DSM_FLAG_SCRUB_SKIP_IN_SYNC = @as(u32, 268435456);
pub const DEVICE_DSM_FLAG_SCRUB_OUTPUT_PARITY_EXTENT = @as(u32, 536870912);
pub const DEVICE_DSM_FLAG_PHYSICAL_ADDRESSES_OMIT_TOTAL_RANGES = @as(u32, 268435456);
pub const DEVICE_DSM_PHYSICAL_ADDRESSES_OUTPUT_V1 = @as(u32, 1);
pub const DEVICE_STORAGE_NO_ERRORS = @as(u32, 1);
pub const DEVICE_DSM_RANGE_ERROR_OUTPUT_V1 = @as(u32, 1);
pub const IOCTL_STORAGE_BC_VERSION = @as(u32, 1);
pub const STORAGE_PRIORITY_HINT_SUPPORTED = @as(u32, 1);
pub const ERROR_HISTORY_DIRECTORY_ENTRY_DEFAULT_COUNT = @as(u32, 8);
pub const DEVICEDUMP_STRUCTURE_VERSION_V1 = @as(u32, 1);
pub const DEVICEDUMP_MAX_IDSTRING = @as(u32, 32);
pub const MAX_FW_BUCKET_ID_LENGTH = @as(u32, 132);
pub const DDUMP_FLAG_DATA_READ_FROM_DEVICE = @as(u32, 1);
pub const FW_ISSUEID_NO_ISSUE = @as(u32, 0);
pub const FW_ISSUEID_UNKNOWN = @as(u32, 4294967295);
pub const TC_PUBLIC_DEVICEDUMP_CONTENT_SMART = @as(u32, 1);
pub const TC_PUBLIC_DEVICEDUMP_CONTENT_GPLOG = @as(u32, 2);
pub const TC_PUBLIC_DEVICEDUMP_CONTENT_GPLOG_MAX = @as(u32, 16);
pub const TC_DEVICEDUMP_SUBSECTION_DESC_LENGTH = @as(u32, 16);
pub const CDB_SIZE = @as(u32, 16);
pub const TELEMETRY_COMMAND_SIZE = @as(u32, 16);
pub const DEVICEDUMP_CAP_PRIVATE_SECTION = @as(u32, 1);
pub const DEVICEDUMP_CAP_RESTRICTED_SECTION = @as(u32, 2);
pub const STORAGE_IDLE_POWERUP_REASON_VERSION_V1 = @as(u32, 1);
pub const STORAGE_DEVICE_POWER_CAP_VERSION_V1 = @as(u32, 1);
pub const STORAGE_EVENT_NOTIFICATION_VERSION_V1 = @as(u32, 1);
pub const STORAGE_EVENT_MEDIA_STATUS = @as(u64, 1);
pub const STORAGE_EVENT_DEVICE_STATUS = @as(u64, 2);
pub const STORAGE_EVENT_DEVICE_OPERATION = @as(u64, 4);
pub const READ_COPY_NUMBER_KEY = @as(u32, 1380142592);
pub const READ_COPY_NUMBER_BYPASS_CACHE_FLAG = @as(u32, 256);
pub const STORAGE_HW_FIRMWARE_REQUEST_FLAG_CONTROLLER = @as(u32, 1);
pub const STORAGE_HW_FIRMWARE_REQUEST_FLAG_LAST_SEGMENT = @as(u32, 2);
pub const STORAGE_HW_FIRMWARE_REQUEST_FLAG_FIRST_SEGMENT = @as(u32, 4);
pub const STORAGE_HW_FIRMWARE_REQUEST_FLAG_SWITCH_TO_EXISTING_FIRMWARE = @as(u32, 2147483648);
pub const STORAGE_HW_FIRMWARE_INVALID_SLOT = @as(u32, 255);
pub const STORAGE_HW_FIRMWARE_REVISION_LENGTH = @as(u32, 16);
pub const STORAGE_PROTOCOL_STRUCTURE_VERSION = @as(u32, 1);
pub const STORAGE_PROTOCOL_COMMAND_FLAG_ADAPTER_REQUEST = @as(u32, 2147483648);
pub const STORAGE_PROTOCOL_STATUS_PENDING = @as(u32, 0);
pub const STORAGE_PROTOCOL_STATUS_SUCCESS = @as(u32, 1);
pub const STORAGE_PROTOCOL_STATUS_ERROR = @as(u32, 2);
pub const STORAGE_PROTOCOL_STATUS_INVALID_REQUEST = @as(u32, 3);
pub const STORAGE_PROTOCOL_STATUS_NO_DEVICE = @as(u32, 4);
pub const STORAGE_PROTOCOL_STATUS_BUSY = @as(u32, 5);
pub const STORAGE_PROTOCOL_STATUS_DATA_OVERRUN = @as(u32, 6);
pub const STORAGE_PROTOCOL_STATUS_INSUFFICIENT_RESOURCES = @as(u32, 7);
pub const STORAGE_PROTOCOL_STATUS_THROTTLED_REQUEST = @as(u32, 8);
pub const STORAGE_PROTOCOL_STATUS_NOT_SUPPORTED = @as(u32, 255);
pub const STORAGE_PROTOCOL_COMMAND_LENGTH_NVME = @as(u32, 64);
pub const STORAGE_PROTOCOL_SPECIFIC_NVME_ADMIN_COMMAND = @as(u32, 1);
pub const STORAGE_PROTOCOL_SPECIFIC_NVME_NVM_COMMAND = @as(u32, 2);
pub const STORATTRIBUTE_NONE = @as(u32, 0);
pub const STORATTRIBUTE_MANAGEMENT_STATE = @as(u32, 1);
pub const BSF_MSGSRV32ISOK = @as(u32, 2147483648);
pub const BSF_MSGSRV32ISOK_BIT = @as(u32, 31);
pub const DBT_APPYBEGIN = @as(u32, 0);
pub const DBT_APPYEND = @as(u32, 1);
pub const DBT_DEVNODES_CHANGED = @as(u32, 7);
pub const DBT_QUERYCHANGECONFIG = @as(u32, 23);
pub const DBT_CONFIGCHANGED = @as(u32, 24);
pub const DBT_CONFIGCHANGECANCELED = @as(u32, 25);
pub const DBT_MONITORCHANGE = @as(u32, 27);
pub const DBT_SHELLLOGGEDON = @as(u32, 32);
pub const DBT_CONFIGMGAPI32 = @as(u32, 34);
pub const DBT_VXDINITCOMPLETE = @as(u32, 35);
pub const DBT_VOLLOCKQUERYLOCK = @as(u32, 32833);
pub const DBT_VOLLOCKLOCKTAKEN = @as(u32, 32834);
pub const DBT_VOLLOCKLOCKFAILED = @as(u32, 32835);
pub const DBT_VOLLOCKQUERYUNLOCK = @as(u32, 32836);
pub const DBT_VOLLOCKLOCKRELEASED = @as(u32, 32837);
pub const DBT_VOLLOCKUNLOCKFAILED = @as(u32, 32838);
pub const LOCKP_ALLOW_WRITES = @as(u32, 1);
pub const LOCKP_FAIL_WRITES = @as(u32, 0);
pub const LOCKP_FAIL_MEM_MAPPING = @as(u32, 2);
pub const LOCKP_ALLOW_MEM_MAPPING = @as(u32, 0);
pub const LOCKP_USER_MASK = @as(u32, 3);
pub const LOCKP_LOCK_FOR_FORMAT = @as(u32, 4);
pub const LOCKF_LOGICAL_LOCK = @as(u32, 0);
pub const LOCKF_PHYSICAL_LOCK = @as(u32, 1);
pub const DBT_NO_DISK_SPACE = @as(u32, 71);
pub const DBT_LOW_DISK_SPACE = @as(u32, 72);
pub const DBT_CONFIGMGPRIVATE = @as(u32, 32767);
pub const DBT_DEVICEARRIVAL = @as(u32, 32768);
pub const DBT_DEVICEQUERYREMOVE = @as(u32, 32769);
pub const DBT_DEVICEQUERYREMOVEFAILED = @as(u32, 32770);
pub const DBT_DEVICEREMOVEPENDING = @as(u32, 32771);
pub const DBT_DEVICEREMOVECOMPLETE = @as(u32, 32772);
pub const DBT_DEVICETYPESPECIFIC = @as(u32, 32773);
pub const DBT_CUSTOMEVENT = @as(u32, 32774);
pub const DBT_DEVTYP_DEVNODE = @as(u32, 1);
pub const DBT_DEVTYP_NET = @as(u32, 4);
pub const DBTF_RESOURCE = @as(u32, 1);
pub const DBTF_XPORT = @as(u32, 2);
pub const DBTF_SLOWNET = @as(u32, 4);
pub const DBT_VPOWERDAPI = @as(u32, 33024);
pub const DBT_USERDEFINED = @as(u32, 65535);
pub const DEVPROP_TYPEMOD_ARRAY = @as(u32, 4096);
pub const DEVPROP_TYPEMOD_LIST = @as(u32, 8192);
pub const DEVPROP_TYPE_EMPTY = @as(u32, 0);
pub const DEVPROP_TYPE_NULL = @as(u32, 1);
pub const DEVPROP_TYPE_SBYTE = @as(u32, 2);
pub const DEVPROP_TYPE_BYTE = @as(u32, 3);
pub const DEVPROP_TYPE_INT16 = @as(u32, 4);
pub const DEVPROP_TYPE_UINT16 = @as(u32, 5);
pub const DEVPROP_TYPE_INT32 = @as(u32, 6);
pub const DEVPROP_TYPE_UINT32 = @as(u32, 7);
pub const DEVPROP_TYPE_INT64 = @as(u32, 8);
pub const DEVPROP_TYPE_UINT64 = @as(u32, 9);
pub const DEVPROP_TYPE_FLOAT = @as(u32, 10);
pub const DEVPROP_TYPE_DOUBLE = @as(u32, 11);
pub const DEVPROP_TYPE_DECIMAL = @as(u32, 12);
pub const DEVPROP_TYPE_GUID = @as(u32, 13);
pub const DEVPROP_TYPE_CURRENCY = @as(u32, 14);
pub const DEVPROP_TYPE_DATE = @as(u32, 15);
pub const DEVPROP_TYPE_FILETIME = @as(u32, 16);
pub const DEVPROP_TYPE_BOOLEAN = @as(u32, 17);
pub const DEVPROP_TYPE_STRING = @as(u32, 18);
pub const DEVPROP_TYPE_SECURITY_DESCRIPTOR = @as(u32, 19);
pub const DEVPROP_TYPE_SECURITY_DESCRIPTOR_STRING = @as(u32, 20);
pub const DEVPROP_TYPE_DEVPROPKEY = @as(u32, 21);
pub const DEVPROP_TYPE_DEVPROPTYPE = @as(u32, 22);
pub const DEVPROP_TYPE_ERROR = @as(u32, 23);
pub const DEVPROP_TYPE_NTSTATUS = @as(u32, 24);
pub const DEVPROP_TYPE_STRING_INDIRECT = @as(u32, 25);
pub const MAX_DEVPROP_TYPE = @as(u32, 25);
pub const MAX_DEVPROP_TYPEMOD = @as(u32, 8192);
pub const DEVPROP_MASK_TYPE = @as(u32, 4095);
pub const DEVPROP_MASK_TYPEMOD = @as(u32, 61440);
pub const DEVPROPID_FIRST_USABLE = @as(u32, 2);
pub const GUID_IO_VOLUME_CHANGE = Guid.initString("7373654a-812a-11d0-bec7-08002be2092f");
pub const GUID_IO_VOLUME_DISMOUNT = Guid.initString("d16a55e8-1059-11d2-8ffd-00a0c9a06d32");
pub const GUID_IO_VOLUME_DISMOUNT_FAILED = Guid.initString("e3c5b178-105d-11d2-8ffd-00a0c9a06d32");
pub const GUID_IO_VOLUME_MOUNT = Guid.initString("b5804878-1a96-11d2-8ffd-00a0c9a06d32");
pub const GUID_IO_VOLUME_LOCK = Guid.initString("50708874-c9af-11d1-8fef-00a0c9a06d32");
pub const GUID_IO_VOLUME_LOCK_FAILED = Guid.initString("ae2eed10-0ba8-11d2-8ffb-00a0c9a06d32");
pub const GUID_IO_VOLUME_UNLOCK = Guid.initString("9a8c3d68-d0cb-11d1-8fef-00a0c9a06d32");
pub const GUID_IO_VOLUME_NAME_CHANGE = Guid.initString("2de97f83-4c06-11d2-a532-00609713055a");
pub const GUID_IO_VOLUME_NEED_CHKDSK = Guid.initString("799a0960-0a0b-4e03-ad88-2fa7c6ce748a");
pub const GUID_IO_VOLUME_WORM_NEAR_FULL = Guid.initString("f3bfff82-f3de-48d2-af95-457f80b763f2");
pub const GUID_IO_VOLUME_WEARING_OUT = Guid.initString("873113ca-1486-4508-82ac-c3b2e5297aaa");
pub const GUID_IO_VOLUME_FORCE_CLOSED = Guid.initString("411ad84f-433e-4dc2-a5ae-4a2d1a2de654");
pub const GUID_IO_VOLUME_INFO_MAKE_COMPAT = Guid.initString("3ab9a0d2-ef80-45cf-8cdc-cbe02a212906");
pub const GUID_IO_VOLUME_PREPARING_EJECT = Guid.initString("c79eb16e-0dac-4e7a-a86c-b25ceeaa88f6");
pub const GUID_IO_VOLUME_BACKGROUND_FORMAT = Guid.initString("a2e5fc86-d5cd-4038-b2e3-4445065c2377");
pub const GUID_IO_VOLUME_PHYSICAL_CONFIGURATION_CHANGE = Guid.initString("2de97f84-4c06-11d2-a532-00609713055a");
pub const GUID_IO_VOLUME_UNIQUE_ID_CHANGE = Guid.initString("af39da42-6622-41f5-970b-139d092fa3d9");
pub const GUID_IO_VOLUME_FVE_STATUS_CHANGE = Guid.initString("062998b2-ee1f-4b6a-b857-e76cbbe9a6da");
pub const GUID_IO_VOLUME_DEVICE_INTERFACE = Guid.initString("53f5630d-b6bf-11d0-94f2-00a0c91efb8b");
pub const GUID_IO_VOLUME_CHANGE_SIZE = Guid.initString("3a1625be-ad03-49f1-8ef8-6bbac182d1fd");
pub const GUID_IO_MEDIA_ARRIVAL = Guid.initString("d07433c0-a98e-11d2-917a-00a0c9068ff3");
pub const GUID_IO_MEDIA_REMOVAL = Guid.initString("d07433c1-a98e-11d2-917a-00a0c9068ff3");
pub const GUID_IO_CDROM_EXCLUSIVE_LOCK = Guid.initString("bc56c139-7a10-47ee-a294-4c6a38f0149a");
pub const GUID_IO_CDROM_EXCLUSIVE_UNLOCK = Guid.initString("a3b6d27d-5e35-4885-81e5-ee18c00ed779");
pub const GUID_IO_DEVICE_BECOMING_READY = Guid.initString("d07433f0-a98e-11d2-917a-00a0c9068ff3");
pub const GUID_IO_DEVICE_EXTERNAL_REQUEST = Guid.initString("d07433d0-a98e-11d2-917a-00a0c9068ff3");
pub const GUID_IO_MEDIA_EJECT_REQUEST = Guid.initString("d07433d1-a98e-11d2-917a-00a0c9068ff3");
pub const GUID_IO_DRIVE_REQUIRES_CLEANING = Guid.initString("7207877c-90ed-44e5-a000-81428d4c79bb");
pub const GUID_IO_TAPE_ERASE = Guid.initString("852d11eb-4bb8-4507-9d9b-417cc2b1b438");
pub const GUID_DEVICE_EVENT_RBC = Guid.initString("d0744792-a98e-11d2-917a-00a0c9068ff3");
pub const GUID_IO_DISK_CLONE_ARRIVAL = Guid.initString("6a61885b-7c39-43dd-9b56-b8ac22a549aa");
pub const GUID_IO_DISK_LAYOUT_CHANGE = Guid.initString("11dff54c-8469-41f9-b3de-ef836487c54a");
pub const GUID_IO_DISK_HEALTH_NOTIFICATION = Guid.initString("0f1bd644-3916-49c5-b063-991940118fb2");
pub const D3DNTHAL_NUMCLIPVERTICES = @as(u32, 20);
pub const D3DNTHAL_SCENE_CAPTURE_START = @as(i32, 0);
pub const D3DNTHAL_SCENE_CAPTURE_END = @as(i32, 1);
pub const D3DNTHAL_CONTEXT_BAD = @as(i64, 512);
pub const D3DNTHAL_OUTOFCONTEXTS = @as(i64, 513);
pub const D3DNTHAL2_CB32_SETRENDERTARGET = @as(i32, 1);
pub const D3DHAL_STATESETBEGIN = @as(u32, 0);
pub const D3DHAL_STATESETEND = @as(u32, 1);
pub const D3DHAL_STATESETDELETE = @as(u32, 2);
pub const D3DHAL_STATESETEXECUTE = @as(u32, 3);
pub const D3DHAL_STATESETCAPTURE = @as(u32, 4);
pub const D3DNTHALDP2_USERMEMVERTICES = @as(i32, 1);
pub const D3DNTHALDP2_EXECUTEBUFFER = @as(i32, 2);
pub const D3DNTHALDP2_SWAPVERTEXBUFFER = @as(i32, 4);
pub const D3DNTHALDP2_SWAPCOMMANDBUFFER = @as(i32, 8);
pub const D3DNTHALDP2_REQVERTEXBUFSIZE = @as(i32, 16);
pub const D3DNTHALDP2_REQCOMMANDBUFSIZE = @as(i32, 32);
pub const D3DNTHALDP2_VIDMEMVERTEXBUF = @as(i32, 64);
pub const D3DNTHALDP2_VIDMEMCOMMANDBUF = @as(i32, 128);
pub const D3DNTHAL3_CB32_CLEAR2 = @as(i32, 1);
pub const D3DNTHAL3_CB32_RESERVED = @as(i32, 2);
pub const D3DNTHAL3_CB32_VALIDATETEXTURESTAGESTATE = @as(i32, 4);
pub const D3DNTHAL3_CB32_DRAWPRIMITIVES2 = @as(i32, 8);
pub const D3DNTHAL_TSS_RENDERSTATEBASE = @as(u32, 256);
pub const D3DNTHAL_TSS_MAXSTAGES = @as(u32, 8);
pub const D3DNTHAL_TSS_STATESPERSTAGE = @as(u32, 64);
pub const D3DTSS_TEXTUREMAP = @as(u32, 0);
pub const D3DHAL_SAMPLER_MAXSAMP = @as(u32, 16);
pub const D3DHAL_SAMPLER_MAXVERTEXSAMP = @as(u32, 4);
pub const D3DPMISCCAPS_LINEPATTERNREP = @as(i32, 4);
pub const D3DRS_MAXVERTEXSHADERINST = @as(u32, 196);
pub const D3DRS_MAXPIXELSHADERINST = @as(u32, 197);
pub const D3DRENDERSTATE_EVICTMANAGEDTEXTURES = @as(u32, 61);
pub const D3DRENDERSTATE_SCENECAPTURE = @as(u32, 62);
pub const _NT_D3DRS_DELETERTPATCH = @as(u32, 169);
pub const D3DINFINITEINSTRUCTIONS = @as(u32, 4294967295);
pub const D3DNTHAL_STATESETCREATE = @as(u32, 5);
pub const D3DNTCLEAR_COMPUTERECTS = @as(i32, 8);
pub const _NT_RTPATCHFLAG_HASSEGS = @as(i32, 1);
pub const _NT_RTPATCHFLAG_HASINFO = @as(i32, 2);
pub const D3DNTHAL_ROW_WEIGHTS = @as(u32, 1);
pub const D3DNTHAL_COL_WEIGHTS = @as(u32, 2);
pub const DP2BLT_POINT = @as(i32, 1);
pub const DP2BLT_LINEAR = @as(i32, 2);
pub const DDBLT_EXTENDED_PRESENTATION_STRETCHFACTOR = @as(i32, 16);
pub const _NT_D3DGDI2_MAGIC = @as(u32, 4294967295);
pub const _NT_D3DGDI2_TYPE_GETD3DCAPS8 = @as(u32, 1);
pub const _NT_D3DGDI2_TYPE_GETFORMATCOUNT = @as(u32, 2);
pub const _NT_D3DGDI2_TYPE_GETFORMAT = @as(u32, 3);
pub const _NT_D3DGDI2_TYPE_DXVERSION = @as(u32, 4);
pub const _NT_D3DGDI2_TYPE_DEFERRED_AGP_AWARE = @as(u32, 24);
pub const _NT_D3DGDI2_TYPE_FREE_DEFERRED_AGP = @as(u32, 25);
pub const _NT_D3DGDI2_TYPE_DEFER_AGP_FREES = @as(u32, 32);
pub const _NT_D3DGDI2_TYPE_GETD3DCAPS9 = @as(u32, 16);
pub const _NT_D3DGDI2_TYPE_GETEXTENDEDMODECOUNT = @as(u32, 17);
pub const _NT_D3DGDI2_TYPE_GETEXTENDEDMODE = @as(u32, 18);
pub const _NT_D3DGDI2_TYPE_GETADAPTERGROUP = @as(u32, 19);
pub const _NT_D3DGDI2_TYPE_GETMULTISAMPLEQUALITYLEVELS = @as(u32, 22);
pub const _NT_D3DGDI2_TYPE_GETD3DQUERYCOUNT = @as(u32, 33);
pub const _NT_D3DGDI2_TYPE_GETD3DQUERY = @as(u32, 34);
pub const _NT_D3DGDI2_TYPE_GETDDIVERSION = @as(u32, 35);
pub const DX9_DDI_VERSION = @as(u32, 4);
pub const _NT_D3DDEVCAPS_HWVERTEXBUFFER = @as(i32, 33554432);
pub const _NT_D3DDEVCAPS_HWINDEXBUFFER = @as(i32, 67108864);
pub const _NT_D3DDEVCAPS_SUBVOLUMELOCK = @as(i32, 134217728);
pub const _NT_D3DPMISCCAPS_FOGINFVF = @as(i32, 8192);
pub const _NT_D3DFVF_FOG = @as(i32, 8192);
pub const D3DPRASTERCAPS_STRETCHBLTMULTISAMPLE = @as(i32, 8388608);
pub const _NT_D3DVS_MAXINSTRUCTIONCOUNT_V1_1 = @as(u32, 128);
pub const _NT_D3DVS_LABEL_MAX_V3_0 = @as(u32, 2048);
pub const _NT_D3DVS_TCRDOUTREG_MAX_V1_1 = @as(u32, 8);
pub const _NT_D3DVS_TCRDOUTREG_MAX_V2_0 = @as(u32, 8);
pub const _NT_D3DVS_TCRDOUTREG_MAX_V2_1 = @as(u32, 8);
pub const _NT_D3DVS_OUTPUTREG_MAX_V3_0 = @as(u32, 12);
pub const _NT_D3DVS_OUTPUTREG_MAX_SW_DX9 = @as(u32, 16);
pub const _NT_D3DVS_ATTROUTREG_MAX_V1_1 = @as(u32, 2);
pub const _NT_D3DVS_ATTROUTREG_MAX_V2_0 = @as(u32, 2);
pub const _NT_D3DVS_ATTROUTREG_MAX_V2_1 = @as(u32, 2);
pub const _NT_D3DVS_INPUTREG_MAX_V1_1 = @as(u32, 16);
pub const _NT_D3DVS_INPUTREG_MAX_V2_0 = @as(u32, 16);
pub const _NT_D3DVS_INPUTREG_MAX_V2_1 = @as(u32, 16);
pub const _NT_D3DVS_INPUTREG_MAX_V3_0 = @as(u32, 16);
pub const _NT_D3DVS_TEMPREG_MAX_V1_1 = @as(u32, 12);
pub const _NT_D3DVS_TEMPREG_MAX_V2_0 = @as(u32, 12);
pub const _NT_D3DVS_TEMPREG_MAX_V2_1 = @as(u32, 32);
pub const _NT_D3DVS_TEMPREG_MAX_V3_0 = @as(u32, 32);
pub const _NT_D3DVS_CONSTREG_MAX_V1_1 = @as(u32, 96);
pub const _NT_D3DVS_CONSTREG_MAX_V2_0 = @as(u32, 8192);
pub const _NT_D3DVS_CONSTREG_MAX_V2_1 = @as(u32, 8192);
pub const _NT_D3DVS_CONSTREG_MAX_V3_0 = @as(u32, 8192);
pub const _NT_D3DVS_CONSTINTREG_MAX_SW_DX9 = @as(u32, 2048);
pub const _NT_D3DVS_CONSTINTREG_MAX_V2_0 = @as(u32, 16);
pub const _NT_D3DVS_CONSTINTREG_MAX_V2_1 = @as(u32, 16);
pub const _NT_D3DVS_CONSTINTREG_MAX_V3_0 = @as(u32, 16);
pub const _NT_D3DVS_CONSTBOOLREG_MAX_SW_DX9 = @as(u32, 2048);
pub const _NT_D3DVS_CONSTBOOLREG_MAX_V2_0 = @as(u32, 16);
pub const _NT_D3DVS_CONSTBOOLREG_MAX_V2_1 = @as(u32, 16);
pub const _NT_D3DVS_CONSTBOOLREG_MAX_V3_0 = @as(u32, 16);
pub const _NT_D3DVS_ADDRREG_MAX_V1_1 = @as(u32, 1);
pub const _NT_D3DVS_ADDRREG_MAX_V2_0 = @as(u32, 1);
pub const _NT_D3DVS_ADDRREG_MAX_V2_1 = @as(u32, 1);
pub const _NT_D3DVS_ADDRREG_MAX_V3_0 = @as(u32, 1);
pub const _NT_D3DVS_MAXLOOPSTEP_V2_0 = @as(u32, 128);
pub const _NT_D3DVS_MAXLOOPSTEP_V2_1 = @as(u32, 128);
pub const _NT_D3DVS_MAXLOOPSTEP_V3_0 = @as(u32, 128);
pub const _NT_D3DVS_MAXLOOPINITVALUE_V2_0 = @as(u32, 255);
pub const _NT_D3DVS_MAXLOOPINITVALUE_V2_1 = @as(u32, 255);
pub const _NT_D3DVS_MAXLOOPINITVALUE_V3_0 = @as(u32, 255);
pub const _NT_D3DVS_MAXLOOPITERATIONCOUNT_V2_0 = @as(u32, 255);
pub const _NT_D3DVS_MAXLOOPITERATIONCOUNT_V2_1 = @as(u32, 255);
pub const _NT_D3DVS_MAXLOOPITERATIONCOUNT_V3_0 = @as(u32, 255);
pub const _NT_D3DVS_PREDICATE_MAX_V2_1 = @as(u32, 1);
pub const _NT_D3DVS_PREDICATE_MAX_V3_0 = @as(u32, 1);
pub const _NT_D3DPS_INPUTREG_MAX_V1_1 = @as(u32, 2);
pub const _NT_D3DPS_INPUTREG_MAX_V1_2 = @as(u32, 2);
pub const _NT_D3DPS_INPUTREG_MAX_V1_3 = @as(u32, 2);
pub const _NT_D3DPS_INPUTREG_MAX_V1_4 = @as(u32, 2);
pub const _NT_D3DPS_INPUTREG_MAX_V2_0 = @as(u32, 2);
pub const _NT_D3DPS_INPUTREG_MAX_V2_1 = @as(u32, 2);
pub const _NT_D3DPS_INPUTREG_MAX_V3_0 = @as(u32, 12);
pub const _NT_D3DPS_TEMPREG_MAX_V1_1 = @as(u32, 2);
pub const _NT_D3DPS_TEMPREG_MAX_V1_2 = @as(u32, 2);
pub const _NT_D3DPS_TEMPREG_MAX_V1_3 = @as(u32, 2);
pub const _NT_D3DPS_TEMPREG_MAX_V1_4 = @as(u32, 6);
pub const _NT_D3DPS_TEMPREG_MAX_V2_0 = @as(u32, 12);
pub const _NT_D3DPS_TEMPREG_MAX_V2_1 = @as(u32, 32);
pub const _NT_D3DPS_TEMPREG_MAX_V3_0 = @as(u32, 32);
pub const _NT_D3DPS_TEXTUREREG_MAX_V1_1 = @as(u32, 4);
pub const _NT_D3DPS_TEXTUREREG_MAX_V1_2 = @as(u32, 4);
pub const _NT_D3DPS_TEXTUREREG_MAX_V1_3 = @as(u32, 4);
pub const _NT_D3DPS_TEXTUREREG_MAX_V1_4 = @as(u32, 6);
pub const _NT_D3DPS_TEXTUREREG_MAX_V2_0 = @as(u32, 8);
pub const _NT_D3DPS_TEXTUREREG_MAX_V2_1 = @as(u32, 8);
pub const _NT_D3DPS_TEXTUREREG_MAX_V3_0 = @as(u32, 0);
pub const _NT_D3DPS_COLOROUT_MAX_V2_0 = @as(u32, 4);
pub const _NT_D3DPS_COLOROUT_MAX_V2_1 = @as(u32, 4);
pub const _NT_D3DPS_COLOROUT_MAX_V3_0 = @as(u32, 4);
pub const _NT_D3DPS_PREDICATE_MAX_V2_1 = @as(u32, 1);
pub const _NT_D3DPS_PREDICATE_MAX_V3_0 = @as(u32, 1);
pub const _NT_D3DPS_CONSTREG_MAX_SW_DX9 = @as(u32, 8192);
pub const _NT_D3DPS_CONSTREG_MAX_V1_1 = @as(u32, 8);
pub const _NT_D3DPS_CONSTREG_MAX_V1_2 = @as(u32, 8);
pub const _NT_D3DPS_CONSTREG_MAX_V1_3 = @as(u32, 8);
pub const _NT_D3DPS_CONSTREG_MAX_V1_4 = @as(u32, 8);
pub const _NT_D3DPS_CONSTREG_MAX_V2_0 = @as(u32, 32);
pub const _NT_D3DPS_CONSTREG_MAX_V2_1 = @as(u32, 32);
pub const _NT_D3DPS_CONSTREG_MAX_V3_0 = @as(u32, 224);
pub const _NT_D3DPS_CONSTBOOLREG_MAX_SW_DX9 = @as(u32, 2048);
pub const _NT_D3DPS_CONSTBOOLREG_MAX_V2_1 = @as(u32, 16);
pub const _NT_D3DPS_CONSTBOOLREG_MAX_V3_0 = @as(u32, 16);
pub const _NT_D3DPS_CONSTINTREG_MAX_SW_DX9 = @as(u32, 2048);
pub const _NT_D3DPS_CONSTINTREG_MAX_V2_1 = @as(u32, 16);
pub const _NT_D3DPS_CONSTINTREG_MAX_V3_0 = @as(u32, 16);
pub const _NT_D3DPS_MAXLOOPSTEP_V2_1 = @as(u32, 128);
pub const _NT_D3DPS_MAXLOOPSTEP_V3_0 = @as(u32, 128);
pub const _NT_D3DPS_MAXLOOPINITVALUE_V2_1 = @as(u32, 255);
pub const _NT_D3DPS_MAXLOOPINITVALUE_V3_0 = @as(u32, 255);
pub const _NT_D3DPS_MAXLOOPITERATIONCOUNT_V2_1 = @as(u32, 255);
pub const _NT_D3DPS_MAXLOOPITERATIONCOUNT_V3_0 = @as(u32, 255);
pub const _NT_D3DPS_INPUTREG_MAX_DX8 = @as(u32, 8);
pub const _NT_D3DPS_TEMPREG_MAX_DX8 = @as(u32, 8);
pub const _NT_D3DPS_CONSTREG_MAX_DX8 = @as(u32, 8);
pub const _NT_D3DPS_TEXTUREREG_MAX_DX8 = @as(u32, 8);
pub const D3DVSDT_FLOAT1 = @as(u32, 0);
pub const D3DVSDT_FLOAT2 = @as(u32, 1);
pub const D3DVSDT_FLOAT3 = @as(u32, 2);
pub const D3DVSDT_FLOAT4 = @as(u32, 3);
pub const D3DVSDT_D3DCOLOR = @as(u32, 4);
pub const D3DVSDT_UBYTE4 = @as(u32, 5);
pub const D3DVSDT_SHORT2 = @as(u32, 6);
pub const D3DVSDT_SHORT4 = @as(u32, 7);
pub const D3DVSDE_POSITION = @as(u32, 0);
pub const D3DVSDE_BLENDWEIGHT = @as(u32, 1);
pub const D3DVSDE_BLENDINDICES = @as(u32, 2);
pub const D3DVSDE_NORMAL = @as(u32, 3);
pub const D3DVSDE_PSIZE = @as(u32, 4);
pub const D3DVSDE_DIFFUSE = @as(u32, 5);
pub const D3DVSDE_SPECULAR = @as(u32, 6);
pub const D3DVSDE_TEXCOORD0 = @as(u32, 7);
pub const D3DVSDE_TEXCOORD1 = @as(u32, 8);
pub const D3DVSDE_TEXCOORD2 = @as(u32, 9);
pub const D3DVSDE_TEXCOORD3 = @as(u32, 10);
pub const D3DVSDE_TEXCOORD4 = @as(u32, 11);
pub const D3DVSDE_TEXCOORD5 = @as(u32, 12);
pub const D3DVSDE_TEXCOORD6 = @as(u32, 13);
pub const D3DVSDE_TEXCOORD7 = @as(u32, 14);
pub const D3DVSDE_POSITION2 = @as(u32, 15);
pub const D3DVSDE_NORMAL2 = @as(u32, 16);
pub const D3DVSD_TOKENTYPESHIFT = @as(u32, 29);
pub const D3DVSD_STREAMNUMBERSHIFT = @as(u32, 0);
pub const D3DVSD_DATALOADTYPESHIFT = @as(u32, 28);
pub const D3DVSD_DATATYPESHIFT = @as(u32, 16);
pub const D3DVSD_SKIPCOUNTSHIFT = @as(u32, 16);
pub const D3DVSD_VERTEXREGSHIFT = @as(u32, 0);
pub const D3DVSD_VERTEXREGINSHIFT = @as(u32, 20);
pub const D3DVSD_CONSTCOUNTSHIFT = @as(u32, 25);
pub const D3DVSD_CONSTADDRESSSHIFT = @as(u32, 0);
pub const D3DVSD_CONSTRSSHIFT = @as(u32, 16);
pub const D3DVSD_EXTCOUNTSHIFT = @as(u32, 24);
pub const D3DVSD_EXTINFOSHIFT = @as(u32, 0);
pub const D3DVSD_STREAMTESSSHIFT = @as(u32, 28);
pub const DIRECT3D_VERSION = @as(u32, 1792);
pub const D3DTRANSFORMCAPS_CLIP = @as(i32, 1);
pub const D3DLIGHTINGMODEL_RGB = @as(i32, 1);
pub const D3DLIGHTINGMODEL_MONO = @as(i32, 2);
pub const D3DLIGHTCAPS_POINT = @as(i32, 1);
pub const D3DLIGHTCAPS_SPOT = @as(i32, 2);
pub const D3DLIGHTCAPS_DIRECTIONAL = @as(i32, 4);
pub const D3DLIGHTCAPS_PARALLELPOINT = @as(i32, 8);
pub const D3DLIGHTCAPS_GLSPOT = @as(i32, 16);
pub const D3DPMISCCAPS_MASKPLANES = @as(i32, 1);
pub const D3DPMISCCAPS_MASKZ = @as(i32, 2);
pub const D3DPMISCCAPS_CONFORMANT = @as(i32, 8);
pub const D3DPMISCCAPS_CULLNONE = @as(i32, 16);
pub const D3DPMISCCAPS_CULLCW = @as(i32, 32);
pub const D3DPMISCCAPS_CULLCCW = @as(i32, 64);
pub const D3DPRASTERCAPS_DITHER = @as(i32, 1);
pub const D3DPRASTERCAPS_ROP2 = @as(i32, 2);
pub const D3DPRASTERCAPS_XOR = @as(i32, 4);
pub const D3DPRASTERCAPS_PAT = @as(i32, 8);
pub const D3DPRASTERCAPS_ZTEST = @as(i32, 16);
pub const D3DPRASTERCAPS_SUBPIXEL = @as(i32, 32);
pub const D3DPRASTERCAPS_SUBPIXELX = @as(i32, 64);
pub const D3DPRASTERCAPS_FOGVERTEX = @as(i32, 128);
pub const D3DPRASTERCAPS_FOGTABLE = @as(i32, 256);
pub const D3DPRASTERCAPS_STIPPLE = @as(i32, 512);
pub const D3DPRASTERCAPS_ANTIALIASSORTDEPENDENT = @as(i32, 1024);
pub const D3DPRASTERCAPS_ANTIALIASSORTINDEPENDENT = @as(i32, 2048);
pub const D3DPRASTERCAPS_ANTIALIASEDGES = @as(i32, 4096);
pub const D3DPRASTERCAPS_MIPMAPLODBIAS = @as(i32, 8192);
pub const D3DPRASTERCAPS_ZBIAS = @as(i32, 16384);
pub const D3DPRASTERCAPS_ZBUFFERLESSHSR = @as(i32, 32768);
pub const D3DPRASTERCAPS_FOGRANGE = @as(i32, 65536);
pub const D3DPRASTERCAPS_ANISOTROPY = @as(i32, 131072);
pub const D3DPRASTERCAPS_WBUFFER = @as(i32, 262144);
pub const D3DPRASTERCAPS_TRANSLUCENTSORTINDEPENDENT = @as(i32, 524288);
pub const D3DPRASTERCAPS_WFOG = @as(i32, 1048576);
pub const D3DPRASTERCAPS_ZFOG = @as(i32, 2097152);
pub const D3DPCMPCAPS_NEVER = @as(i32, 1);
pub const D3DPCMPCAPS_LESS = @as(i32, 2);
pub const D3DPCMPCAPS_EQUAL = @as(i32, 4);
pub const D3DPCMPCAPS_LESSEQUAL = @as(i32, 8);
pub const D3DPCMPCAPS_GREATER = @as(i32, 16);
pub const D3DPCMPCAPS_NOTEQUAL = @as(i32, 32);
pub const D3DPCMPCAPS_GREATEREQUAL = @as(i32, 64);
pub const D3DPCMPCAPS_ALWAYS = @as(i32, 128);
pub const D3DPBLENDCAPS_ZERO = @as(i32, 1);
pub const D3DPBLENDCAPS_ONE = @as(i32, 2);
pub const D3DPBLENDCAPS_SRCCOLOR = @as(i32, 4);
pub const D3DPBLENDCAPS_INVSRCCOLOR = @as(i32, 8);
pub const D3DPBLENDCAPS_SRCALPHA = @as(i32, 16);
pub const D3DPBLENDCAPS_INVSRCALPHA = @as(i32, 32);
pub const D3DPBLENDCAPS_DESTALPHA = @as(i32, 64);
pub const D3DPBLENDCAPS_INVDESTALPHA = @as(i32, 128);
pub const D3DPBLENDCAPS_DESTCOLOR = @as(i32, 256);
pub const D3DPBLENDCAPS_INVDESTCOLOR = @as(i32, 512);
pub const D3DPBLENDCAPS_SRCALPHASAT = @as(i32, 1024);
pub const D3DPBLENDCAPS_BOTHSRCALPHA = @as(i32, 2048);
pub const D3DPBLENDCAPS_BOTHINVSRCALPHA = @as(i32, 4096);
pub const D3DPSHADECAPS_COLORFLATMONO = @as(i32, 1);
pub const D3DPSHADECAPS_COLORFLATRGB = @as(i32, 2);
pub const D3DPSHADECAPS_COLORGOURAUDMONO = @as(i32, 4);
pub const D3DPSHADECAPS_COLORGOURAUDRGB = @as(i32, 8);
pub const D3DPSHADECAPS_COLORPHONGMONO = @as(i32, 16);
pub const D3DPSHADECAPS_COLORPHONGRGB = @as(i32, 32);
pub const D3DPSHADECAPS_SPECULARFLATMONO = @as(i32, 64);
pub const D3DPSHADECAPS_SPECULARFLATRGB = @as(i32, 128);
pub const D3DPSHADECAPS_SPECULARGOURAUDMONO = @as(i32, 256);
pub const D3DPSHADECAPS_SPECULARGOURAUDRGB = @as(i32, 512);
pub const D3DPSHADECAPS_SPECULARPHONGMONO = @as(i32, 1024);
pub const D3DPSHADECAPS_SPECULARPHONGRGB = @as(i32, 2048);
pub const D3DPSHADECAPS_ALPHAFLATBLEND = @as(i32, 4096);
pub const D3DPSHADECAPS_ALPHAFLATSTIPPLED = @as(i32, 8192);
pub const D3DPSHADECAPS_ALPHAGOURAUDBLEND = @as(i32, 16384);
pub const D3DPSHADECAPS_ALPHAGOURAUDSTIPPLED = @as(i32, 32768);
pub const D3DPSHADECAPS_ALPHAPHONGBLEND = @as(i32, 65536);
pub const D3DPSHADECAPS_ALPHAPHONGSTIPPLED = @as(i32, 131072);
pub const D3DPSHADECAPS_FOGFLAT = @as(i32, 262144);
pub const D3DPSHADECAPS_FOGGOURAUD = @as(i32, 524288);
pub const D3DPSHADECAPS_FOGPHONG = @as(i32, 1048576);
pub const D3DPTEXTURECAPS_PERSPECTIVE = @as(i32, 1);
pub const D3DPTEXTURECAPS_POW2 = @as(i32, 2);
pub const D3DPTEXTURECAPS_ALPHA = @as(i32, 4);
pub const D3DPTEXTURECAPS_TRANSPARENCY = @as(i32, 8);
pub const D3DPTEXTURECAPS_BORDER = @as(i32, 16);
pub const D3DPTEXTURECAPS_SQUAREONLY = @as(i32, 32);
pub const D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE = @as(i32, 64);
pub const D3DPTEXTURECAPS_ALPHAPALETTE = @as(i32, 128);
pub const D3DPTEXTURECAPS_NONPOW2CONDITIONAL = @as(i32, 256);
pub const D3DPTEXTURECAPS_PROJECTED = @as(i32, 1024);
pub const D3DPTEXTURECAPS_CUBEMAP = @as(i32, 2048);
pub const D3DPTEXTURECAPS_COLORKEYBLEND = @as(i32, 4096);
pub const D3DPTFILTERCAPS_NEAREST = @as(i32, 1);
pub const D3DPTFILTERCAPS_LINEAR = @as(i32, 2);
pub const D3DPTFILTERCAPS_MIPNEAREST = @as(i32, 4);
pub const D3DPTFILTERCAPS_MIPLINEAR = @as(i32, 8);
pub const D3DPTFILTERCAPS_LINEARMIPNEAREST = @as(i32, 16);
pub const D3DPTFILTERCAPS_LINEARMIPLINEAR = @as(i32, 32);
pub const D3DPTFILTERCAPS_MINFPOINT = @as(i32, 256);
pub const D3DPTFILTERCAPS_MINFLINEAR = @as(i32, 512);
pub const D3DPTFILTERCAPS_MINFANISOTROPIC = @as(i32, 1024);
pub const D3DPTFILTERCAPS_MIPFPOINT = @as(i32, 65536);
pub const D3DPTFILTERCAPS_MIPFLINEAR = @as(i32, 131072);
pub const D3DPTFILTERCAPS_MAGFPOINT = @as(i32, 16777216);
pub const D3DPTFILTERCAPS_MAGFLINEAR = @as(i32, 33554432);
pub const D3DPTFILTERCAPS_MAGFANISOTROPIC = @as(i32, 67108864);
pub const D3DPTFILTERCAPS_MAGFAFLATCUBIC = @as(i32, 134217728);
pub const D3DPTFILTERCAPS_MAGFGAUSSIANCUBIC = @as(i32, 268435456);
pub const D3DPTBLENDCAPS_DECAL = @as(i32, 1);
pub const D3DPTBLENDCAPS_MODULATE = @as(i32, 2);
pub const D3DPTBLENDCAPS_DECALALPHA = @as(i32, 4);
pub const D3DPTBLENDCAPS_MODULATEALPHA = @as(i32, 8);
pub const D3DPTBLENDCAPS_DECALMASK = @as(i32, 16);
pub const D3DPTBLENDCAPS_MODULATEMASK = @as(i32, 32);
pub const D3DPTBLENDCAPS_COPY = @as(i32, 64);
pub const D3DPTBLENDCAPS_ADD = @as(i32, 128);
pub const D3DPTADDRESSCAPS_WRAP = @as(i32, 1);
pub const D3DPTADDRESSCAPS_MIRROR = @as(i32, 2);
pub const D3DPTADDRESSCAPS_CLAMP = @as(i32, 4);
pub const D3DPTADDRESSCAPS_BORDER = @as(i32, 8);
pub const D3DPTADDRESSCAPS_INDEPENDENTUV = @as(i32, 16);
pub const D3DSTENCILCAPS_KEEP = @as(i32, 1);
pub const D3DSTENCILCAPS_ZERO = @as(i32, 2);
pub const D3DSTENCILCAPS_REPLACE = @as(i32, 4);
pub const D3DSTENCILCAPS_INCRSAT = @as(i32, 8);
pub const D3DSTENCILCAPS_DECRSAT = @as(i32, 16);
pub const D3DSTENCILCAPS_INVERT = @as(i32, 32);
pub const D3DSTENCILCAPS_INCR = @as(i32, 64);
pub const D3DSTENCILCAPS_DECR = @as(i32, 128);
pub const D3DTEXOPCAPS_DISABLE = @as(i32, 1);
pub const D3DTEXOPCAPS_SELECTARG1 = @as(i32, 2);
pub const D3DTEXOPCAPS_SELECTARG2 = @as(i32, 4);
pub const D3DTEXOPCAPS_MODULATE = @as(i32, 8);
pub const D3DTEXOPCAPS_MODULATE2X = @as(i32, 16);
pub const D3DTEXOPCAPS_MODULATE4X = @as(i32, 32);
pub const D3DTEXOPCAPS_ADD = @as(i32, 64);
pub const D3DTEXOPCAPS_ADDSIGNED = @as(i32, 128);
pub const D3DTEXOPCAPS_ADDSIGNED2X = @as(i32, 256);
pub const D3DTEXOPCAPS_SUBTRACT = @as(i32, 512);
pub const D3DTEXOPCAPS_ADDSMOOTH = @as(i32, 1024);
pub const D3DTEXOPCAPS_BLENDDIFFUSEALPHA = @as(i32, 2048);
pub const D3DTEXOPCAPS_BLENDTEXTUREALPHA = @as(i32, 4096);
pub const D3DTEXOPCAPS_BLENDFACTORALPHA = @as(i32, 8192);
pub const D3DTEXOPCAPS_BLENDTEXTUREALPHAPM = @as(i32, 16384);
pub const D3DTEXOPCAPS_BLENDCURRENTALPHA = @as(i32, 32768);
pub const D3DTEXOPCAPS_PREMODULATE = @as(i32, 65536);
pub const D3DTEXOPCAPS_MODULATEALPHA_ADDCOLOR = @as(i32, 131072);
pub const D3DTEXOPCAPS_MODULATECOLOR_ADDALPHA = @as(i32, 262144);
pub const D3DTEXOPCAPS_MODULATEINVALPHA_ADDCOLOR = @as(i32, 524288);
pub const D3DTEXOPCAPS_MODULATEINVCOLOR_ADDALPHA = @as(i32, 1048576);
pub const D3DTEXOPCAPS_BUMPENVMAP = @as(i32, 2097152);
pub const D3DTEXOPCAPS_BUMPENVMAPLUMINANCE = @as(i32, 4194304);
pub const D3DTEXOPCAPS_DOTPRODUCT3 = @as(i32, 8388608);
pub const D3DFVFCAPS_TEXCOORDCOUNTMASK = @as(i32, 65535);
pub const D3DFVFCAPS_DONOTSTRIPELEMENTS = @as(i32, 524288);
pub const D3DDD_COLORMODEL = @as(i32, 1);
pub const D3DDD_DEVCAPS = @as(i32, 2);
pub const D3DDD_TRANSFORMCAPS = @as(i32, 4);
pub const D3DDD_LIGHTINGCAPS = @as(i32, 8);
pub const D3DDD_BCLIPPING = @as(i32, 16);
pub const D3DDD_LINECAPS = @as(i32, 32);
pub const D3DDD_TRICAPS = @as(i32, 64);
pub const D3DDD_DEVICERENDERBITDEPTH = @as(i32, 128);
pub const D3DDD_DEVICEZBUFFERBITDEPTH = @as(i32, 256);
pub const D3DDD_MAXBUFFERSIZE = @as(i32, 512);
pub const D3DDD_MAXVERTEXCOUNT = @as(i32, 1024);
pub const D3DDEVCAPS_FLOATTLVERTEX = @as(i32, 1);
pub const D3DDEVCAPS_SORTINCREASINGZ = @as(i32, 2);
pub const D3DDEVCAPS_SORTDECREASINGZ = @as(i32, 4);
pub const D3DDEVCAPS_SORTEXACT = @as(i32, 8);
pub const D3DDEVCAPS_EXECUTESYSTEMMEMORY = @as(i32, 16);
pub const D3DDEVCAPS_EXECUTEVIDEOMEMORY = @as(i32, 32);
pub const D3DDEVCAPS_TLVERTEXSYSTEMMEMORY = @as(i32, 64);
pub const D3DDEVCAPS_TLVERTEXVIDEOMEMORY = @as(i32, 128);
pub const D3DDEVCAPS_TEXTURESYSTEMMEMORY = @as(i32, 256);
pub const D3DDEVCAPS_TEXTUREVIDEOMEMORY = @as(i32, 512);
pub const D3DDEVCAPS_DRAWPRIMTLVERTEX = @as(i32, 1024);
pub const D3DDEVCAPS_CANRENDERAFTERFLIP = @as(i32, 2048);
pub const D3DDEVCAPS_TEXTURENONLOCALVIDMEM = @as(i32, 4096);
pub const D3DDEVCAPS_DRAWPRIMITIVES2 = @as(i32, 8192);
pub const D3DDEVCAPS_SEPARATETEXTUREMEMORIES = @as(i32, 16384);
pub const D3DDEVCAPS_DRAWPRIMITIVES2EX = @as(i32, 32768);
pub const D3DDEVCAPS_HWTRANSFORMANDLIGHT = @as(i32, 65536);
pub const D3DDEVCAPS_CANBLTSYSTONONLOCAL = @as(i32, 131072);
pub const D3DDEVCAPS_HWRASTERIZATION = @as(i32, 524288);
pub const D3DVTXPCAPS_TEXGEN = @as(i32, 1);
pub const D3DVTXPCAPS_MATERIALSOURCE7 = @as(i32, 2);
pub const D3DVTXPCAPS_VERTEXFOG = @as(i32, 4);
pub const D3DVTXPCAPS_DIRECTIONALLIGHTS = @as(i32, 8);
pub const D3DVTXPCAPS_POSITIONALLIGHTS = @as(i32, 16);
pub const D3DVTXPCAPS_LOCALVIEWER = @as(i32, 32);
pub const D3DFDS_COLORMODEL = @as(i32, 1);
pub const D3DFDS_GUID = @as(i32, 2);
pub const D3DFDS_HARDWARE = @as(i32, 4);
pub const D3DFDS_TRIANGLES = @as(i32, 8);
pub const D3DFDS_LINES = @as(i32, 16);
pub const D3DFDS_MISCCAPS = @as(i32, 32);
pub const D3DFDS_RASTERCAPS = @as(i32, 64);
pub const D3DFDS_ZCMPCAPS = @as(i32, 128);
pub const D3DFDS_ALPHACMPCAPS = @as(i32, 256);
pub const D3DFDS_SRCBLENDCAPS = @as(i32, 512);
pub const D3DFDS_DSTBLENDCAPS = @as(i32, 1024);
pub const D3DFDS_SHADECAPS = @as(i32, 2048);
pub const D3DFDS_TEXTURECAPS = @as(i32, 4096);
pub const D3DFDS_TEXTUREFILTERCAPS = @as(i32, 8192);
pub const D3DFDS_TEXTUREBLENDCAPS = @as(i32, 16384);
pub const D3DFDS_TEXTUREADDRESSCAPS = @as(i32, 32768);
pub const D3DDEB_BUFSIZE = @as(i32, 1);
pub const D3DDEB_CAPS = @as(i32, 2);
pub const D3DDEB_LPDATA = @as(i32, 4);
pub const D3DDEBCAPS_SYSTEMMEMORY = @as(i32, 1);
pub const D3DDEBCAPS_VIDEOMEMORY = @as(i32, 2);
pub const D3DMAXUSERCLIPPLANES = @as(u32, 32);
pub const D3DCLIPPLANE0 = @as(u32, 1);
pub const D3DCLIPPLANE1 = @as(u32, 2);
pub const D3DCLIPPLANE2 = @as(u32, 4);
pub const D3DCLIPPLANE3 = @as(u32, 8);
pub const D3DCLIPPLANE4 = @as(u32, 16);
pub const D3DCLIPPLANE5 = @as(u32, 32);
pub const D3DCLIP_LEFT = @as(i32, 1);
pub const D3DCLIP_RIGHT = @as(i32, 2);
pub const D3DCLIP_TOP = @as(i32, 4);
pub const D3DCLIP_BOTTOM = @as(i32, 8);
pub const D3DCLIP_FRONT = @as(i32, 16);
pub const D3DCLIP_BACK = @as(i32, 32);
pub const D3DCLIP_GEN0 = @as(i32, 64);
pub const D3DCLIP_GEN1 = @as(i32, 128);
pub const D3DCLIP_GEN2 = @as(i32, 256);
pub const D3DCLIP_GEN3 = @as(i32, 512);
pub const D3DCLIP_GEN4 = @as(i32, 1024);
pub const D3DCLIP_GEN5 = @as(i32, 2048);
pub const D3DSTATUS_CLIPINTERSECTIONLEFT = @as(i32, 4096);
pub const D3DSTATUS_CLIPINTERSECTIONRIGHT = @as(i32, 8192);
pub const D3DSTATUS_CLIPINTERSECTIONTOP = @as(i32, 16384);
pub const D3DSTATUS_CLIPINTERSECTIONBOTTOM = @as(i32, 32768);
pub const D3DSTATUS_CLIPINTERSECTIONFRONT = @as(i32, 65536);
pub const D3DSTATUS_CLIPINTERSECTIONBACK = @as(i32, 131072);
pub const D3DSTATUS_CLIPINTERSECTIONGEN0 = @as(i32, 262144);
pub const D3DSTATUS_CLIPINTERSECTIONGEN1 = @as(i32, 524288);
pub const D3DSTATUS_CLIPINTERSECTIONGEN2 = @as(i32, 1048576);
pub const D3DSTATUS_CLIPINTERSECTIONGEN3 = @as(i32, 2097152);
pub const D3DSTATUS_CLIPINTERSECTIONGEN4 = @as(i32, 4194304);
pub const D3DSTATUS_CLIPINTERSECTIONGEN5 = @as(i32, 8388608);
pub const D3DSTATUS_ZNOTVISIBLE = @as(i32, 16777216);
pub const D3DTRANSFORM_CLIPPED = @as(i32, 1);
pub const D3DTRANSFORM_UNCLIPPED = @as(i32, 2);
pub const D3DLIGHT_ACTIVE = @as(u32, 1);
pub const D3DLIGHT_NO_SPECULAR = @as(u32, 2);
pub const D3DCOLOR_MONO = @as(u32, 1);
pub const D3DCOLOR_RGB = @as(u32, 2);
pub const D3DCLEAR_TARGET = @as(i32, 1);
pub const D3DCLEAR_ZBUFFER = @as(i32, 2);
pub const D3DCLEAR_STENCIL = @as(i32, 4);
pub const D3DSTATE_OVERRIDE_BIAS = @as(u32, 256);
pub const D3DRENDERSTATE_WRAPBIAS = @as(u32, 128);
pub const D3DWRAP_U = @as(i32, 1);
pub const D3DWRAP_V = @as(i32, 2);
pub const D3DWRAPCOORD_0 = @as(i32, 1);
pub const D3DWRAPCOORD_1 = @as(i32, 2);
pub const D3DWRAPCOORD_2 = @as(i32, 4);
pub const D3DWRAPCOORD_3 = @as(i32, 8);
pub const D3DPROCESSVERTICES_TRANSFORMLIGHT = @as(i32, 0);
pub const D3DPROCESSVERTICES_TRANSFORM = @as(i32, 1);
pub const D3DPROCESSVERTICES_COPY = @as(i32, 2);
pub const D3DPROCESSVERTICES_OPMASK = @as(i32, 7);
pub const D3DPROCESSVERTICES_UPDATEEXTENTS = @as(i32, 8);
pub const D3DPROCESSVERTICES_NOCOLOR = @as(i32, 16);
pub const D3DTSS_TCI_PASSTHRU = @as(u32, 0);
pub const D3DTSS_TCI_CAMERASPACENORMAL = @as(u32, 65536);
pub const D3DTSS_TCI_CAMERASPACEPOSITION = @as(u32, 131072);
pub const D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR = @as(u32, 196608);
pub const D3DTA_SELECTMASK = @as(u32, 15);
pub const D3DTA_DIFFUSE = @as(u32, 0);
pub const D3DTA_CURRENT = @as(u32, 1);
pub const D3DTA_TEXTURE = @as(u32, 2);
pub const D3DTA_TFACTOR = @as(u32, 3);
pub const D3DTA_SPECULAR = @as(u32, 4);
pub const D3DTA_COMPLEMENT = @as(u32, 16);
pub const D3DTA_ALPHAREPLICATE = @as(u32, 32);
pub const D3DTRIFLAG_START = @as(i32, 0);
pub const D3DTRIFLAG_ODD = @as(i32, 30);
pub const D3DTRIFLAG_EVEN = @as(i32, 31);
pub const D3DTRIFLAG_EDGEENABLE1 = @as(i32, 256);
pub const D3DTRIFLAG_EDGEENABLE2 = @as(i32, 512);
pub const D3DTRIFLAG_EDGEENABLE3 = @as(i32, 1024);
pub const D3DSETSTATUS_STATUS = @as(i32, 1);
pub const D3DSETSTATUS_EXTENTS = @as(i32, 2);
pub const D3DCLIPSTATUS_STATUS = @as(i32, 1);
pub const D3DCLIPSTATUS_EXTENTS2 = @as(i32, 2);
pub const D3DCLIPSTATUS_EXTENTS3 = @as(i32, 4);
pub const D3DEXECUTE_CLIPPED = @as(i32, 1);
pub const D3DEXECUTE_UNCLIPPED = @as(i32, 2);
pub const D3DPAL_FREE = @as(u32, 0);
pub const D3DPAL_READONLY = @as(u32, 64);
pub const D3DPAL_RESERVED = @as(u32, 128);
pub const D3DVBCAPS_SYSTEMMEMORY = @as(i32, 2048);
pub const D3DVBCAPS_WRITEONLY = @as(i32, 65536);
pub const D3DVBCAPS_OPTIMIZED = @as(i32, -2147483648);
pub const D3DVBCAPS_DONOTCLIP = @as(i32, 1);
pub const D3DVOP_LIGHT = @as(u32, 1024);
pub const D3DVOP_TRANSFORM = @as(u32, 1);
pub const D3DVOP_CLIP = @as(u32, 4);
pub const D3DVOP_EXTENTS = @as(u32, 8);
pub const D3DPV_DONOTCOPYDATA = @as(u32, 1);
pub const D3DFVF_RESERVED0 = @as(u32, 1);
pub const D3DFVF_POSITION_MASK = @as(u32, 14);
pub const D3DFVF_XYZ = @as(u32, 2);
pub const D3DFVF_XYZRHW = @as(u32, 4);
pub const D3DFVF_XYZB1 = @as(u32, 6);
pub const D3DFVF_XYZB2 = @as(u32, 8);
pub const D3DFVF_XYZB3 = @as(u32, 10);
pub const D3DFVF_XYZB4 = @as(u32, 12);
pub const D3DFVF_XYZB5 = @as(u32, 14);
pub const D3DFVF_NORMAL = @as(u32, 16);
pub const D3DFVF_RESERVED1 = @as(u32, 32);
pub const D3DFVF_DIFFUSE = @as(u32, 64);
pub const D3DFVF_SPECULAR = @as(u32, 128);
pub const D3DFVF_TEXCOUNT_MASK = @as(u32, 3840);
pub const D3DFVF_TEXCOUNT_SHIFT = @as(u32, 8);
pub const D3DFVF_TEX0 = @as(u32, 0);
pub const D3DFVF_TEX1 = @as(u32, 256);
pub const D3DFVF_TEX2 = @as(u32, 512);
pub const D3DFVF_TEX3 = @as(u32, 768);
pub const D3DFVF_TEX4 = @as(u32, 1024);
pub const D3DFVF_TEX5 = @as(u32, 1280);
pub const D3DFVF_TEX6 = @as(u32, 1536);
pub const D3DFVF_TEX7 = @as(u32, 1792);
pub const D3DFVF_TEX8 = @as(u32, 2048);
pub const D3DFVF_RESERVED2 = @as(u32, 61440);
pub const D3DDP_MAXTEXCOORD = @as(u32, 8);
pub const D3DVIS_INSIDE_FRUSTUM = @as(u32, 0);
pub const D3DVIS_INTERSECT_FRUSTUM = @as(u32, 1);
pub const D3DVIS_OUTSIDE_FRUSTUM = @as(u32, 2);
pub const D3DVIS_INSIDE_LEFT = @as(u32, 0);
pub const D3DVIS_INTERSECT_LEFT = @as(u32, 4);
pub const D3DVIS_OUTSIDE_LEFT = @as(u32, 8);
pub const D3DVIS_INSIDE_RIGHT = @as(u32, 0);
pub const D3DVIS_INTERSECT_RIGHT = @as(u32, 16);
pub const D3DVIS_OUTSIDE_RIGHT = @as(u32, 32);
pub const D3DVIS_INSIDE_TOP = @as(u32, 0);
pub const D3DVIS_INTERSECT_TOP = @as(u32, 64);
pub const D3DVIS_OUTSIDE_TOP = @as(u32, 128);
pub const D3DVIS_INSIDE_BOTTOM = @as(u32, 0);
pub const D3DVIS_INTERSECT_BOTTOM = @as(u32, 256);
pub const D3DVIS_OUTSIDE_BOTTOM = @as(u32, 512);
pub const D3DVIS_INSIDE_NEAR = @as(u32, 0);
pub const D3DVIS_INTERSECT_NEAR = @as(u32, 1024);
pub const D3DVIS_OUTSIDE_NEAR = @as(u32, 2048);
pub const D3DVIS_INSIDE_FAR = @as(u32, 0);
pub const D3DVIS_INTERSECT_FAR = @as(u32, 4096);
pub const D3DVIS_OUTSIDE_FAR = @as(u32, 8192);
pub const D3DVIS_MASK_FRUSTUM = @as(u32, 3);
pub const D3DVIS_MASK_LEFT = @as(u32, 12);
pub const D3DVIS_MASK_RIGHT = @as(u32, 48);
pub const D3DVIS_MASK_TOP = @as(u32, 192);
pub const D3DVIS_MASK_BOTTOM = @as(u32, 768);
pub const D3DVIS_MASK_NEAR = @as(u32, 3072);
pub const D3DVIS_MASK_FAR = @as(u32, 12288);
pub const D3DDEVINFOID_TEXTUREMANAGER = @as(u32, 1);
pub const D3DDEVINFOID_D3DTEXTUREMANAGER = @as(u32, 2);
pub const D3DDEVINFOID_TEXTURING = @as(u32, 3);
pub const D3DFVF_TEXTUREFORMAT2 = @as(u32, 0);
pub const D3DFVF_TEXTUREFORMAT1 = @as(u32, 3);
pub const D3DFVF_TEXTUREFORMAT3 = @as(u32, 1);
pub const D3DFVF_TEXTUREFORMAT4 = @as(u32, 2);
pub const FD_ERROR = @as(u32, 4294967295);
pub const DDI_ERROR = @as(u32, 4294967295);
pub const FDM_TYPE_BM_SIDE_CONST = @as(u32, 1);
pub const FDM_TYPE_MAXEXT_EQUAL_BM_SIDE = @as(u32, 2);
pub const FDM_TYPE_CHAR_INC_EQUAL_BM_BASE = @as(u32, 4);
pub const FDM_TYPE_ZERO_BEARINGS = @as(u32, 8);
pub const FDM_TYPE_CONST_BEARINGS = @as(u32, 16);
pub const GS_UNICODE_HANDLES = @as(u32, 1);
pub const GS_8BIT_HANDLES = @as(u32, 2);
pub const GS_16BIT_HANDLES = @as(u32, 4);
pub const FM_VERSION_NUMBER = @as(u32, 0);
pub const FM_TYPE_LICENSED = @as(u32, 2);
pub const FM_READONLY_EMBED = @as(u32, 4);
pub const FM_EDITABLE_EMBED = @as(u32, 8);
pub const FM_INFO_TECH_TRUETYPE = @as(u32, 1);
pub const FM_INFO_TECH_BITMAP = @as(u32, 2);
pub const FM_INFO_TECH_STROKE = @as(u32, 4);
pub const FM_INFO_TECH_OUTLINE_NOT_TRUETYPE = @as(u32, 8);
pub const FM_INFO_ARB_XFORMS = @as(u32, 16);
pub const FM_INFO_1BPP = @as(u32, 32);
pub const FM_INFO_4BPP = @as(u32, 64);
pub const FM_INFO_8BPP = @as(u32, 128);
pub const FM_INFO_16BPP = @as(u32, 256);
pub const FM_INFO_24BPP = @as(u32, 512);
pub const FM_INFO_32BPP = @as(u32, 1024);
pub const FM_INFO_INTEGER_WIDTH = @as(u32, 2048);
pub const FM_INFO_CONSTANT_WIDTH = @as(u32, 4096);
pub const FM_INFO_NOT_CONTIGUOUS = @as(u32, 8192);
pub const FM_INFO_TECH_MM = @as(u32, 16384);
pub const FM_INFO_RETURNS_OUTLINES = @as(u32, 32768);
pub const FM_INFO_RETURNS_STROKES = @as(u32, 65536);
pub const FM_INFO_RETURNS_BITMAPS = @as(u32, 131072);
pub const FM_INFO_DSIG = @as(u32, 262144);
pub const FM_INFO_RIGHT_HANDED = @as(u32, 524288);
pub const FM_INFO_INTEGRAL_SCALING = @as(u32, 1048576);
pub const FM_INFO_90DEGREE_ROTATIONS = @as(u32, 2097152);
pub const FM_INFO_OPTICALLY_FIXED_PITCH = @as(u32, 4194304);
pub const FM_INFO_DO_NOT_ENUMERATE = @as(u32, 8388608);
pub const FM_INFO_ISOTROPIC_SCALING_ONLY = @as(u32, 16777216);
pub const FM_INFO_ANISOTROPIC_SCALING_ONLY = @as(u32, 33554432);
pub const FM_INFO_TECH_CFF = @as(u32, 67108864);
pub const FM_INFO_FAMILY_EQUIV = @as(u32, 134217728);
pub const FM_INFO_DBCS_FIXED_PITCH = @as(u32, 268435456);
pub const FM_INFO_NONNEGATIVE_AC = @as(u32, 536870912);
pub const FM_INFO_IGNORE_TC_RA_ABLE = @as(u32, 1073741824);
pub const FM_INFO_TECH_TYPE1 = @as(u32, 2147483648);
pub const MAXCHARSETS = @as(u32, 16);
pub const FM_PANOSE_CULTURE_LATIN = @as(u32, 0);
pub const FM_SEL_ITALIC = @as(u32, 1);
pub const FM_SEL_UNDERSCORE = @as(u32, 2);
pub const FM_SEL_NEGATIVE = @as(u32, 4);
pub const FM_SEL_OUTLINED = @as(u32, 8);
pub const FM_SEL_STRIKEOUT = @as(u32, 16);
pub const FM_SEL_BOLD = @as(u32, 32);
pub const FM_SEL_REGULAR = @as(u32, 64);
pub const OPENGL_CMD = @as(u32, 4352);
pub const OPENGL_GETINFO = @as(u32, 4353);
pub const WNDOBJ_SETUP = @as(u32, 4354);
pub const DDI_DRIVER_VERSION_NT4 = @as(u32, 131072);
pub const DDI_DRIVER_VERSION_SP3 = @as(u32, 131075);
pub const DDI_DRIVER_VERSION_NT5 = @as(u32, 196608);
pub const DDI_DRIVER_VERSION_NT5_01 = @as(u32, 196864);
pub const DDI_DRIVER_VERSION_NT5_01_SP1 = @as(u32, 196865);
pub const GDI_DRIVER_VERSION = @as(u32, 16384);
pub const INDEX_DrvEnablePDEV = @as(i32, 0);
pub const INDEX_DrvCompletePDEV = @as(i32, 1);
pub const INDEX_DrvDisablePDEV = @as(i32, 2);
pub const INDEX_DrvEnableSurface = @as(i32, 3);
pub const INDEX_DrvDisableSurface = @as(i32, 4);
pub const INDEX_DrvAssertMode = @as(i32, 5);
pub const INDEX_DrvOffset = @as(i32, 6);
pub const INDEX_DrvResetPDEV = @as(i32, 7);
pub const INDEX_DrvDisableDriver = @as(i32, 8);
pub const INDEX_DrvCreateDeviceBitmap = @as(i32, 10);
pub const INDEX_DrvDeleteDeviceBitmap = @as(i32, 11);
pub const INDEX_DrvRealizeBrush = @as(i32, 12);
pub const INDEX_DrvDitherColor = @as(i32, 13);
pub const INDEX_DrvStrokePath = @as(i32, 14);
pub const INDEX_DrvFillPath = @as(i32, 15);
pub const INDEX_DrvStrokeAndFillPath = @as(i32, 16);
pub const INDEX_DrvPaint = @as(i32, 17);
pub const INDEX_DrvBitBlt = @as(i32, 18);
pub const INDEX_DrvCopyBits = @as(i32, 19);
pub const INDEX_DrvStretchBlt = @as(i32, 20);
pub const INDEX_DrvSetPalette = @as(i32, 22);
pub const INDEX_DrvTextOut = @as(i32, 23);
pub const INDEX_DrvEscape = @as(i32, 24);
pub const INDEX_DrvDrawEscape = @as(i32, 25);
pub const INDEX_DrvQueryFont = @as(i32, 26);
pub const INDEX_DrvQueryFontTree = @as(i32, 27);
pub const INDEX_DrvQueryFontData = @as(i32, 28);
pub const INDEX_DrvSetPointerShape = @as(i32, 29);
pub const INDEX_DrvMovePointer = @as(i32, 30);
pub const INDEX_DrvLineTo = @as(i32, 31);
pub const INDEX_DrvSendPage = @as(i32, 32);
pub const INDEX_DrvStartPage = @as(i32, 33);
pub const INDEX_DrvEndDoc = @as(i32, 34);
pub const INDEX_DrvStartDoc = @as(i32, 35);
pub const INDEX_DrvGetGlyphMode = @as(i32, 37);
pub const INDEX_DrvSynchronize = @as(i32, 38);
pub const INDEX_DrvSaveScreenBits = @as(i32, 40);
pub const INDEX_DrvGetModes = @as(i32, 41);
pub const INDEX_DrvFree = @as(i32, 42);
pub const INDEX_DrvDestroyFont = @as(i32, 43);
pub const INDEX_DrvQueryFontCaps = @as(i32, 44);
pub const INDEX_DrvLoadFontFile = @as(i32, 45);
pub const INDEX_DrvUnloadFontFile = @as(i32, 46);
pub const INDEX_DrvFontManagement = @as(i32, 47);
pub const INDEX_DrvQueryTrueTypeTable = @as(i32, 48);
pub const INDEX_DrvQueryTrueTypeOutline = @as(i32, 49);
pub const INDEX_DrvGetTrueTypeFile = @as(i32, 50);
pub const INDEX_DrvQueryFontFile = @as(i32, 51);
pub const INDEX_DrvMovePanning = @as(i32, 52);
pub const INDEX_DrvQueryAdvanceWidths = @as(i32, 53);
pub const INDEX_DrvSetPixelFormat = @as(i32, 54);
pub const INDEX_DrvDescribePixelFormat = @as(i32, 55);
pub const INDEX_DrvSwapBuffers = @as(i32, 56);
pub const INDEX_DrvStartBanding = @as(i32, 57);
pub const INDEX_DrvNextBand = @as(i32, 58);
pub const INDEX_DrvGetDirectDrawInfo = @as(i32, 59);
pub const INDEX_DrvEnableDirectDraw = @as(i32, 60);
pub const INDEX_DrvDisableDirectDraw = @as(i32, 61);
pub const INDEX_DrvQuerySpoolType = @as(i32, 62);
pub const INDEX_DrvIcmCreateColorTransform = @as(i32, 64);
pub const INDEX_DrvIcmDeleteColorTransform = @as(i32, 65);
pub const INDEX_DrvIcmCheckBitmapBits = @as(i32, 66);
pub const INDEX_DrvIcmSetDeviceGammaRamp = @as(i32, 67);
pub const INDEX_DrvGradientFill = @as(i32, 68);
pub const INDEX_DrvStretchBltROP = @as(i32, 69);
pub const INDEX_DrvPlgBlt = @as(i32, 70);
pub const INDEX_DrvAlphaBlend = @as(i32, 71);
pub const INDEX_DrvSynthesizeFont = @as(i32, 72);
pub const INDEX_DrvGetSynthesizedFontFiles = @as(i32, 73);
pub const INDEX_DrvTransparentBlt = @as(i32, 74);
pub const INDEX_DrvQueryPerBandInfo = @as(i32, 75);
pub const INDEX_DrvQueryDeviceSupport = @as(i32, 76);
pub const INDEX_DrvReserved1 = @as(i32, 77);
pub const INDEX_DrvReserved2 = @as(i32, 78);
pub const INDEX_DrvReserved3 = @as(i32, 79);
pub const INDEX_DrvReserved4 = @as(i32, 80);
pub const INDEX_DrvReserved5 = @as(i32, 81);
pub const INDEX_DrvReserved6 = @as(i32, 82);
pub const INDEX_DrvReserved7 = @as(i32, 83);
pub const INDEX_DrvReserved8 = @as(i32, 84);
pub const INDEX_DrvDeriveSurface = @as(i32, 85);
pub const INDEX_DrvQueryGlyphAttrs = @as(i32, 86);
pub const INDEX_DrvNotify = @as(i32, 87);
pub const INDEX_DrvSynchronizeSurface = @as(i32, 88);
pub const INDEX_DrvResetDevice = @as(i32, 89);
pub const INDEX_DrvReserved9 = @as(i32, 90);
pub const INDEX_DrvReserved10 = @as(i32, 91);
pub const INDEX_DrvReserved11 = @as(i32, 92);
pub const INDEX_DrvRenderHint = @as(i32, 93);
pub const INDEX_DrvCreateDeviceBitmapEx = @as(i32, 94);
pub const INDEX_DrvDeleteDeviceBitmapEx = @as(i32, 95);
pub const INDEX_DrvAssociateSharedSurface = @as(i32, 96);
pub const INDEX_DrvSynchronizeRedirectionBitmaps = @as(i32, 97);
pub const INDEX_DrvAccumulateD3DDirtyRect = @as(i32, 98);
pub const INDEX_DrvStartDxInterop = @as(i32, 99);
pub const INDEX_DrvEndDxInterop = @as(i32, 100);
pub const INDEX_DrvLockDisplayArea = @as(i32, 101);
pub const INDEX_DrvUnlockDisplayArea = @as(i32, 102);
pub const INDEX_DrvSurfaceComplete = @as(i32, 103);
pub const INDEX_LAST = @as(i32, 89);
pub const GCAPS_BEZIERS = @as(u32, 1);
pub const GCAPS_GEOMETRICWIDE = @as(u32, 2);
pub const GCAPS_ALTERNATEFILL = @as(u32, 4);
pub const GCAPS_WINDINGFILL = @as(u32, 8);
pub const GCAPS_HALFTONE = @as(u32, 16);
pub const GCAPS_COLOR_DITHER = @as(u32, 32);
pub const GCAPS_HORIZSTRIKE = @as(u32, 64);
pub const GCAPS_VERTSTRIKE = @as(u32, 128);
pub const GCAPS_OPAQUERECT = @as(u32, 256);
pub const GCAPS_VECTORFONT = @as(u32, 512);
pub const GCAPS_MONO_DITHER = @as(u32, 1024);
pub const GCAPS_ASYNCCHANGE = @as(u32, 2048);
pub const GCAPS_ASYNCMOVE = @as(u32, 4096);
pub const GCAPS_DONTJOURNAL = @as(u32, 8192);
pub const GCAPS_DIRECTDRAW = @as(u32, 16384);
pub const GCAPS_ARBRUSHOPAQUE = @as(u32, 32768);
pub const GCAPS_PANNING = @as(u32, 65536);
pub const GCAPS_HIGHRESTEXT = @as(u32, 262144);
pub const GCAPS_PALMANAGED = @as(u32, 524288);
pub const GCAPS_DITHERONREALIZE = @as(u32, 2097152);
pub const GCAPS_NO64BITMEMACCESS = @as(u32, 4194304);
pub const GCAPS_FORCEDITHER = @as(u32, 8388608);
pub const GCAPS_GRAY16 = @as(u32, 16777216);
pub const GCAPS_ICM = @as(u32, 33554432);
pub const GCAPS_CMYKCOLOR = @as(u32, 67108864);
pub const GCAPS_LAYERED = @as(u32, 134217728);
pub const GCAPS_ARBRUSHTEXT = @as(u32, 268435456);
pub const GCAPS_SCREENPRECISION = @as(u32, 536870912);
pub const GCAPS_FONT_RASTERIZER = @as(u32, 1073741824);
pub const GCAPS_NUP = @as(u32, 2147483648);
pub const GCAPS2_JPEGSRC = @as(u32, 1);
pub const GCAPS2_xxxx = @as(u32, 2);
pub const GCAPS2_PNGSRC = @as(u32, 8);
pub const GCAPS2_CHANGEGAMMARAMP = @as(u32, 16);
pub const GCAPS2_ALPHACURSOR = @as(u32, 32);
pub const GCAPS2_SYNCFLUSH = @as(u32, 64);
pub const GCAPS2_SYNCTIMER = @as(u32, 128);
pub const GCAPS2_ICD_MULTIMON = @as(u32, 256);
pub const GCAPS2_MOUSETRAILS = @as(u32, 512);
pub const GCAPS2_RESERVED1 = @as(u32, 1024);
pub const GCAPS2_REMOTEDRIVER = @as(u32, 1024);
pub const GCAPS2_EXCLUDELAYERED = @as(u32, 2048);
pub const GCAPS2_INCLUDEAPIBITMAPS = @as(u32, 4096);
pub const GCAPS2_SHOWHIDDENPOINTER = @as(u32, 8192);
pub const GCAPS2_CLEARTYPE = @as(u32, 16384);
pub const GCAPS2_ACC_DRIVER = @as(u32, 32768);
pub const GCAPS2_BITMAPEXREUSE = @as(u32, 65536);
pub const LA_GEOMETRIC = @as(u32, 1);
pub const LA_ALTERNATE = @as(u32, 2);
pub const LA_STARTGAP = @as(u32, 4);
pub const LA_STYLED = @as(u32, 8);
pub const JOIN_ROUND = @as(i32, 0);
pub const JOIN_BEVEL = @as(i32, 1);
pub const JOIN_MITER = @as(i32, 2);
pub const ENDCAP_ROUND = @as(i32, 0);
pub const ENDCAP_SQUARE = @as(i32, 1);
pub const ENDCAP_BUTT = @as(i32, 2);
pub const PRIMARY_ORDER_ABC = @as(u32, 0);
pub const PRIMARY_ORDER_ACB = @as(u32, 1);
pub const PRIMARY_ORDER_BAC = @as(u32, 2);
pub const PRIMARY_ORDER_BCA = @as(u32, 3);
pub const PRIMARY_ORDER_CBA = @as(u32, 4);
pub const PRIMARY_ORDER_CAB = @as(u32, 5);
pub const HT_PATSIZE_2x2 = @as(u32, 0);
pub const HT_PATSIZE_2x2_M = @as(u32, 1);
pub const HT_PATSIZE_4x4 = @as(u32, 2);
pub const HT_PATSIZE_4x4_M = @as(u32, 3);
pub const HT_PATSIZE_6x6 = @as(u32, 4);
pub const HT_PATSIZE_6x6_M = @as(u32, 5);
pub const HT_PATSIZE_8x8 = @as(u32, 6);
pub const HT_PATSIZE_8x8_M = @as(u32, 7);
pub const HT_PATSIZE_10x10 = @as(u32, 8);
pub const HT_PATSIZE_10x10_M = @as(u32, 9);
pub const HT_PATSIZE_12x12 = @as(u32, 10);
pub const HT_PATSIZE_12x12_M = @as(u32, 11);
pub const HT_PATSIZE_14x14 = @as(u32, 12);
pub const HT_PATSIZE_14x14_M = @as(u32, 13);
pub const HT_PATSIZE_16x16 = @as(u32, 14);
pub const HT_PATSIZE_16x16_M = @as(u32, 15);
pub const HT_PATSIZE_SUPERCELL = @as(u32, 16);
pub const HT_PATSIZE_SUPERCELL_M = @as(u32, 17);
pub const HT_PATSIZE_USER = @as(u32, 18);
pub const HT_USERPAT_CX_MIN = @as(u32, 4);
pub const HT_USERPAT_CX_MAX = @as(u32, 256);
pub const HT_USERPAT_CY_MIN = @as(u32, 4);
pub const HT_USERPAT_CY_MAX = @as(u32, 256);
pub const HT_FORMAT_1BPP = @as(u32, 0);
pub const HT_FORMAT_4BPP = @as(u32, 2);
pub const HT_FORMAT_4BPP_IRGB = @as(u32, 3);
pub const HT_FORMAT_8BPP = @as(u32, 4);
pub const HT_FORMAT_16BPP = @as(u32, 5);
pub const HT_FORMAT_24BPP = @as(u32, 6);
pub const HT_FORMAT_32BPP = @as(u32, 7);
pub const WINDDI_MAX_BROADCAST_CONTEXT = @as(u32, 64);
pub const HT_FLAG_SQUARE_DEVICE_PEL = @as(u32, 1);
pub const HT_FLAG_HAS_BLACK_DYE = @as(u32, 2);
pub const HT_FLAG_ADDITIVE_PRIMS = @as(u32, 4);
pub const HT_FLAG_USE_8BPP_BITMASK = @as(u32, 8);
pub const HT_FLAG_INK_HIGH_ABSORPTION = @as(u32, 16);
pub const HT_FLAG_INK_ABSORPTION_INDICES = @as(u32, 96);
pub const HT_FLAG_DO_DEVCLR_XFORM = @as(u32, 128);
pub const HT_FLAG_OUTPUT_CMY = @as(u32, 256);
pub const HT_FLAG_PRINT_DRAFT_MODE = @as(u32, 512);
pub const HT_FLAG_INVERT_8BPP_BITMASK_IDX = @as(u32, 1024);
pub const HT_FLAG_8BPP_CMY332_MASK = @as(u32, 4278190080);
pub const HT_FLAG_INK_ABSORPTION_IDX0 = @as(u32, 0);
pub const HT_FLAG_INK_ABSORPTION_IDX1 = @as(u32, 32);
pub const HT_FLAG_INK_ABSORPTION_IDX2 = @as(u32, 64);
pub const HT_FLAG_INK_ABSORPTION_IDX3 = @as(u32, 96);
pub const PPC_DEFAULT = @as(u32, 0);
pub const PPC_UNDEFINED = @as(u32, 1);
pub const PPC_RGB_ORDER_VERTICAL_STRIPES = @as(u32, 2);
pub const PPC_BGR_ORDER_VERTICAL_STRIPES = @as(u32, 3);
pub const PPC_RGB_ORDER_HORIZONTAL_STRIPES = @as(u32, 4);
pub const PPC_BGR_ORDER_HORIZONTAL_STRIPES = @as(u32, 5);
pub const PPG_DEFAULT = @as(u32, 0);
pub const PPG_SRGB = @as(u32, 1);
pub const BR_DEVICE_ICM = @as(u32, 1);
pub const BR_HOST_ICM = @as(u32, 2);
pub const BR_CMYKCOLOR = @as(u32, 4);
pub const BR_ORIGCOLOR = @as(u32, 8);
pub const FO_SIM_BOLD = @as(u32, 8192);
pub const FO_SIM_ITALIC = @as(u32, 16384);
pub const FO_EM_HEIGHT = @as(u32, 32768);
pub const FO_GRAY16 = @as(u32, 65536);
pub const FO_NOGRAY16 = @as(u32, 131072);
pub const FO_NOHINTS = @as(u32, 262144);
pub const FO_NO_CHOICE = @as(u32, 524288);
pub const FO_CFF = @as(u32, 1048576);
pub const FO_POSTSCRIPT = @as(u32, 2097152);
pub const FO_MULTIPLEMASTER = @as(u32, 4194304);
pub const FO_VERT_FACE = @as(u32, 8388608);
pub const FO_DBCS_FONT = @as(u32, 16777216);
pub const FO_NOCLEARTYPE = @as(u32, 33554432);
pub const FO_CLEARTYPE_X = @as(u32, 268435456);
pub const FO_CLEARTYPE_Y = @as(u32, 536870912);
pub const FO_CLEARTYPENATURAL_X = @as(u32, 1073741824);
pub const DC_TRIVIAL = @as(u32, 0);
pub const DC_RECT = @as(u32, 1);
pub const DC_COMPLEX = @as(u32, 3);
pub const FC_RECT = @as(u32, 1);
pub const FC_RECT4 = @as(u32, 2);
pub const FC_COMPLEX = @as(u32, 3);
pub const TC_RECTANGLES = @as(u32, 0);
pub const TC_PATHOBJ = @as(u32, 2);
pub const OC_BANK_CLIP = @as(u32, 1);
pub const CT_RECTANGLES = @as(i32, 0);
pub const CD_RIGHTDOWN = @as(i32, 0);
pub const CD_LEFTDOWN = @as(i32, 1);
pub const CD_RIGHTUP = @as(i32, 2);
pub const CD_LEFTUP = @as(i32, 3);
pub const CD_ANY = @as(i32, 4);
pub const CD_LEFTWARDS = @as(i32, 1);
pub const CD_UPWARDS = @as(i32, 2);
pub const FO_HGLYPHS = @as(i32, 0);
pub const FO_GLYPHBITS = @as(i32, 1);
pub const FO_PATHOBJ = @as(i32, 2);
pub const FD_NEGATIVE_FONT = @as(i32, 1);
pub const FO_DEVICE_FONT = @as(i32, 1);
pub const FO_OUTLINE_CAPABLE = @as(i32, 2);
pub const SO_FLAG_DEFAULT_PLACEMENT = @as(u32, 1);
pub const SO_HORIZONTAL = @as(u32, 2);
pub const SO_VERTICAL = @as(u32, 4);
pub const SO_REVERSED = @as(u32, 8);
pub const SO_ZERO_BEARINGS = @as(u32, 16);
pub const SO_CHAR_INC_EQUAL_BM_BASE = @as(u32, 32);
pub const SO_MAXEXT_EQUAL_BM_SIDE = @as(u32, 64);
pub const SO_DO_NOT_SUBSTITUTE_DEVICE_FONT = @as(u32, 128);
pub const SO_GLYPHINDEX_TEXTOUT = @as(u32, 256);
pub const SO_ESC_NOT_ORIENT = @as(u32, 512);
pub const SO_DXDY = @as(u32, 1024);
pub const SO_CHARACTER_EXTRA = @as(u32, 2048);
pub const SO_BREAK_EXTRA = @as(u32, 4096);
pub const FO_ATTR_MODE_ROTATE = @as(u32, 1);
pub const PAL_INDEXED = @as(u32, 1);
pub const PAL_BITFIELDS = @as(u32, 2);
pub const PAL_RGB = @as(u32, 4);
pub const PAL_BGR = @as(u32, 8);
pub const PAL_CMYK = @as(u32, 16);
pub const PO_BEZIERS = @as(u32, 1);
pub const PO_ELLIPSE = @as(u32, 2);
pub const PO_ALL_INTEGERS = @as(u32, 4);
pub const PO_ENUM_AS_INTEGERS = @as(u32, 8);
pub const PO_WIDENED = @as(u32, 16);
pub const PD_BEGINSUBPATH = @as(u32, 1);
pub const PD_ENDSUBPATH = @as(u32, 2);
pub const PD_RESETSTYLE = @as(u32, 4);
pub const PD_CLOSEFIGURE = @as(u32, 8);
pub const PD_BEZIERS = @as(u32, 16);
pub const SGI_EXTRASPACE = @as(u32, 0);
pub const STYPE_BITMAP = @as(i32, 0);
pub const STYPE_DEVBITMAP = @as(i32, 3);
pub const BMF_1BPP = @as(i32, 1);
pub const BMF_4BPP = @as(i32, 2);
pub const BMF_8BPP = @as(i32, 3);
pub const BMF_16BPP = @as(i32, 4);
pub const BMF_24BPP = @as(i32, 5);
pub const BMF_32BPP = @as(i32, 6);
pub const BMF_4RLE = @as(i32, 7);
pub const BMF_8RLE = @as(i32, 8);
pub const BMF_JPEG = @as(i32, 9);
pub const BMF_PNG = @as(i32, 10);
pub const BMF_TOPDOWN = @as(u32, 1);
pub const BMF_NOZEROINIT = @as(u32, 2);
pub const BMF_DONTCACHE = @as(u32, 4);
pub const BMF_USERMEM = @as(u32, 8);
pub const BMF_KMSECTION = @as(u32, 16);
pub const BMF_NOTSYSMEM = @as(u32, 32);
pub const BMF_WINDOW_BLT = @as(u32, 64);
pub const BMF_UMPDMEM = @as(u32, 128);
pub const BMF_TEMP_ALPHA = @as(u32, 256);
pub const BMF_ACC_NOTIFY = @as(u32, 32768);
pub const BMF_RMT_ENTER = @as(u32, 16384);
pub const BMF_RESERVED = @as(u32, 15872);
pub const GX_IDENTITY = @as(i32, 0);
pub const GX_OFFSET = @as(i32, 1);
pub const GX_SCALE = @as(i32, 2);
pub const GX_GENERAL = @as(i32, 3);
pub const XF_LTOL = @as(i32, 0);
pub const XF_INV_LTOL = @as(i32, 1);
pub const XF_LTOFX = @as(i32, 2);
pub const XF_INV_FXTOL = @as(i32, 3);
pub const XO_TRIVIAL = @as(u32, 1);
pub const XO_TABLE = @as(u32, 2);
pub const XO_TO_MONO = @as(u32, 4);
pub const XO_FROM_CMYK = @as(u32, 8);
pub const XO_DEVICE_ICM = @as(u32, 16);
pub const XO_HOST_ICM = @as(u32, 32);
pub const XO_SRCPALETTE = @as(u32, 1);
pub const XO_DESTPALETTE = @as(u32, 2);
pub const XO_DESTDCPALETTE = @as(u32, 3);
pub const XO_SRCBITFIELDS = @as(u32, 4);
pub const XO_DESTBITFIELDS = @as(u32, 5);
pub const HOOK_BITBLT = @as(u32, 1);
pub const HOOK_STRETCHBLT = @as(u32, 2);
pub const HOOK_PLGBLT = @as(u32, 4);
pub const HOOK_TEXTOUT = @as(u32, 8);
pub const HOOK_PAINT = @as(u32, 16);
pub const HOOK_STROKEPATH = @as(u32, 32);
pub const HOOK_FILLPATH = @as(u32, 64);
pub const HOOK_STROKEANDFILLPATH = @as(u32, 128);
pub const HOOK_LINETO = @as(u32, 256);
pub const HOOK_COPYBITS = @as(u32, 1024);
pub const HOOK_MOVEPANNING = @as(u32, 2048);
pub const HOOK_SYNCHRONIZE = @as(u32, 4096);
pub const HOOK_STRETCHBLTROP = @as(u32, 8192);
pub const HOOK_SYNCHRONIZEACCESS = @as(u32, 16384);
pub const HOOK_TRANSPARENTBLT = @as(u32, 32768);
pub const HOOK_ALPHABLEND = @as(u32, 65536);
pub const HOOK_GRADIENTFILL = @as(u32, 131072);
pub const HOOK_FLAGS = @as(u32, 243199);
pub const MS_NOTSYSTEMMEMORY = @as(u32, 1);
pub const MS_SHAREDACCESS = @as(u32, 2);
pub const MS_CDDDEVICEBITMAP = @as(u32, 4);
pub const MS_REUSEDDEVICEBITMAP = @as(u32, 8);
pub const DRVQUERY_USERMODE = @as(u32, 1);
pub const HS_DDI_MAX = @as(u32, 6);
pub const DRD_SUCCESS = @as(u32, 0);
pub const DRD_ERROR = @as(u32, 1);
pub const SS_SAVE = @as(u32, 0);
pub const SS_RESTORE = @as(u32, 1);
pub const SS_FREE = @as(u32, 2);
pub const CDBEX_REDIRECTION = @as(u32, 1);
pub const CDBEX_DXINTEROP = @as(u32, 2);
pub const CDBEX_NTSHAREDSURFACEHANDLE = @as(u32, 4);
pub const CDBEX_CROSSADAPTER = @as(u32, 8);
pub const CDBEX_REUSE = @as(u32, 16);
pub const WINDDI_MAXSETPALETTECOLORS = @as(u32, 256);
pub const WINDDI_MAXSETPALETTECOLORINDEX = @as(u32, 255);
pub const DM_DEFAULT = @as(u32, 1);
pub const DM_MONOCHROME = @as(u32, 2);
pub const DCR_SOLID = @as(u32, 0);
pub const DCR_DRIVER = @as(u32, 1);
pub const DCR_HALFTONE = @as(u32, 2);
pub const RB_DITHERCOLOR = @as(i32, -2147483648);
pub const QFT_LIGATURES = @as(i32, 1);
pub const QFT_KERNPAIRS = @as(i32, 2);
pub const QFT_GLYPHSET = @as(i32, 3);
pub const QFD_GLYPHANDBITMAP = @as(i32, 1);
pub const QFD_GLYPHANDOUTLINE = @as(i32, 2);
pub const QFD_MAXEXTENTS = @as(i32, 3);
pub const QFD_TT_GLYPHANDBITMAP = @as(i32, 4);
pub const QFD_TT_GRAY1_BITMAP = @as(i32, 5);
pub const QFD_TT_GRAY2_BITMAP = @as(i32, 6);
pub const QFD_TT_GRAY4_BITMAP = @as(i32, 8);
pub const QFD_TT_GRAY8_BITMAP = @as(i32, 9);
pub const QC_OUTLINES = @as(u32, 1);
pub const QC_1BIT = @as(u32, 2);
pub const QC_4BIT = @as(u32, 4);
pub const FF_SIGNATURE_VERIFIED = @as(u32, 1);
pub const FF_IGNORED_SIGNATURE = @as(u32, 2);
pub const QAW_GETWIDTHS = @as(u32, 0);
pub const QAW_GETEASYWIDTHS = @as(u32, 1);
pub const TTO_METRICS_ONLY = @as(u32, 1);
pub const TTO_QUBICS = @as(u32, 2);
pub const TTO_UNHINTED = @as(u32, 4);
pub const QFF_DESCRIPTION = @as(i32, 1);
pub const QFF_NUMFACES = @as(i32, 2);
pub const FP_ALTERNATEMODE = @as(i32, 1);
pub const FP_WINDINGMODE = @as(i32, 2);
pub const SPS_ERROR = @as(u32, 0);
pub const SPS_DECLINE = @as(u32, 1);
pub const SPS_ACCEPT_NOEXCLUDE = @as(u32, 2);
pub const SPS_ACCEPT_EXCLUDE = @as(u32, 3);
pub const SPS_ACCEPT_SYNCHRONOUS = @as(u32, 4);
pub const SPS_CHANGE = @as(i32, 1);
pub const SPS_ASYNCCHANGE = @as(i32, 2);
pub const SPS_ANIMATESTART = @as(i32, 4);
pub const SPS_ANIMATEUPDATE = @as(i32, 8);
pub const SPS_ALPHA = @as(i32, 16);
pub const SPS_RESERVED = @as(i32, 32);
pub const SPS_RESERVED1 = @as(i32, 64);
pub const SPS_FLAGSMASK = @as(i32, 255);
pub const SPS_LENGTHMASK = @as(i32, 3840);
pub const SPS_FREQMASK = @as(i32, 1044480);
pub const ED_ABORTDOC = @as(u32, 1);
pub const IGRF_RGB_256BYTES = @as(u32, 0);
pub const IGRF_RGB_256WORDS = @as(u32, 1);
pub const QDS_CHECKJPEGFORMAT = @as(u32, 0);
pub const QDS_CHECKPNGFORMAT = @as(u32, 1);
pub const DSS_TIMER_EVENT = @as(u32, 1);
pub const DSS_FLUSH_EVENT = @as(u32, 2);
pub const DSS_RESERVED = @as(u32, 4);
pub const DSS_RESERVED1 = @as(u32, 8);
pub const DSS_RESERVED2 = @as(u32, 16);
pub const DN_ACCELERATION_LEVEL = @as(u32, 1);
pub const DN_DEVICE_ORIGIN = @as(u32, 2);
pub const DN_SLEEP_MODE = @as(u32, 3);
pub const DN_DRAWING_BEGIN = @as(u32, 4);
pub const DN_ASSOCIATE_WINDOW = @as(u32, 5);
pub const DN_COMPOSITION_CHANGED = @as(u32, 6);
pub const DN_DRAWING_BEGIN_APIBITMAP = @as(u32, 7);
pub const DN_SURFOBJ_DESTRUCTION = @as(u32, 8);
pub const WOC_RGN_CLIENT_DELTA = @as(u32, 1);
pub const WOC_RGN_CLIENT = @as(u32, 2);
pub const WOC_RGN_SURFACE_DELTA = @as(u32, 4);
pub const WOC_RGN_SURFACE = @as(u32, 8);
pub const WOC_CHANGED = @as(u32, 16);
pub const WOC_DELETE = @as(u32, 32);
pub const WOC_DRAWN = @as(u32, 64);
pub const WOC_SPRITE_OVERLAP = @as(u32, 128);
pub const WOC_SPRITE_NO_OVERLAP = @as(u32, 256);
pub const WOC_RGN_SPRITE = @as(u32, 512);
pub const WO_RGN_CLIENT_DELTA = @as(u32, 1);
pub const WO_RGN_CLIENT = @as(u32, 2);
pub const WO_RGN_SURFACE_DELTA = @as(u32, 4);
pub const WO_RGN_SURFACE = @as(u32, 8);
pub const WO_RGN_UPDATE_ALL = @as(u32, 16);
pub const WO_RGN_WINDOW = @as(u32, 32);
pub const WO_DRAW_NOTIFY = @as(u32, 64);
pub const WO_SPRITE_NOTIFY = @as(u32, 128);
pub const WO_RGN_DESKTOP_COORD = @as(u32, 256);
pub const WO_RGN_SPRITE = @as(u32, 512);
pub const EHN_RESTORED = @as(u32, 0);
pub const EHN_ERROR = @as(u32, 1);
pub const ECS_TEARDOWN = @as(u32, 1);
pub const ECS_REDRAW = @as(u32, 2);
pub const DEVHTADJF_COLOR_DEVICE = @as(u32, 1);
pub const DEVHTADJF_ADDITIVE_DEVICE = @as(u32, 2);
pub const FL_ZERO_MEMORY = @as(u32, 1);
pub const FL_NONPAGED_MEMORY = @as(u32, 2);
pub const FL_NON_SESSION = @as(u32, 4);
pub const QSA_MMX = @as(u32, 256);
pub const QSA_SSE = @as(u32, 8192);
pub const QSA_3DNOW = @as(u32, 16384);
pub const QSA_SSE2 = @as(u32, 65536);
pub const QSA_SSE3 = @as(u32, 524288);
pub const ENG_FNT_CACHE_READ_FAULT = @as(u32, 1);
pub const ENG_FNT_CACHE_WRITE_FAULT = @as(u32, 2);
pub const DRH_APIBITMAP = @as(u32, 1);
pub const GUID_DEVINTERFACE_SCM_PHYSICAL_DEVICE = Guid.initString("4283609d-4dc2-43be-bbb4-4f15dfce2c61");
pub const GUID_SCM_PD_HEALTH_NOTIFICATION = Guid.initString("9da2d386-72f5-4ee3-8155-eca0678e3b06");
pub const GUID_SCM_PD_PASSTHROUGH_INVDIMM = Guid.initString("4309ac30-0d11-11e4-9191-0800200c9a66");
pub const GUID_DEVINTERFACE_COMPORT = Guid.initString("86e0d1e0-8089-11d0-9ce4-08003e301f73");
pub const GUID_DEVINTERFACE_SERENUM_BUS_ENUMERATOR = Guid.initString("4d36e978-e325-11ce-bfc1-08002be10318");
pub const FILE_DEVICE_BEEP = @as(u32, 1);
pub const FILE_DEVICE_CD_ROM_FILE_SYSTEM = @as(u32, 3);
pub const FILE_DEVICE_CONTROLLER = @as(u32, 4);
pub const FILE_DEVICE_DATALINK = @as(u32, 5);
pub const FILE_DEVICE_DFS = @as(u32, 6);
pub const FILE_DEVICE_DISK_FILE_SYSTEM = @as(u32, 8);
pub const FILE_DEVICE_FILE_SYSTEM = @as(u32, 9);
pub const FILE_DEVICE_INPORT_PORT = @as(u32, 10);
pub const FILE_DEVICE_KEYBOARD = @as(u32, 11);
pub const FILE_DEVICE_MAILSLOT = @as(u32, 12);
pub const FILE_DEVICE_MIDI_IN = @as(u32, 13);
pub const FILE_DEVICE_MIDI_OUT = @as(u32, 14);
pub const FILE_DEVICE_MOUSE = @as(u32, 15);
pub const FILE_DEVICE_MULTI_UNC_PROVIDER = @as(u32, 16);
pub const FILE_DEVICE_NAMED_PIPE = @as(u32, 17);
pub const FILE_DEVICE_NETWORK = @as(u32, 18);
pub const FILE_DEVICE_NETWORK_BROWSER = @as(u32, 19);
pub const FILE_DEVICE_NETWORK_FILE_SYSTEM = @as(u32, 20);
pub const FILE_DEVICE_NULL = @as(u32, 21);
pub const FILE_DEVICE_PARALLEL_PORT = @as(u32, 22);
pub const FILE_DEVICE_PHYSICAL_NETCARD = @as(u32, 23);
pub const FILE_DEVICE_PRINTER = @as(u32, 24);
pub const FILE_DEVICE_SCANNER = @as(u32, 25);
pub const FILE_DEVICE_SERIAL_MOUSE_PORT = @as(u32, 26);
pub const FILE_DEVICE_SERIAL_PORT = @as(u32, 27);
pub const FILE_DEVICE_SCREEN = @as(u32, 28);
pub const FILE_DEVICE_SOUND = @as(u32, 29);
pub const FILE_DEVICE_STREAMS = @as(u32, 30);
pub const FILE_DEVICE_TAPE_FILE_SYSTEM = @as(u32, 32);
pub const FILE_DEVICE_TRANSPORT = @as(u32, 33);
pub const FILE_DEVICE_UNKNOWN = @as(u32, 34);
pub const FILE_DEVICE_VIDEO = @as(u32, 35);
pub const FILE_DEVICE_VIRTUAL_DISK = @as(u32, 36);
pub const FILE_DEVICE_WAVE_IN = @as(u32, 37);
pub const FILE_DEVICE_WAVE_OUT = @as(u32, 38);
pub const FILE_DEVICE_8042_PORT = @as(u32, 39);
pub const FILE_DEVICE_NETWORK_REDIRECTOR = @as(u32, 40);
pub const FILE_DEVICE_BATTERY = @as(u32, 41);
pub const FILE_DEVICE_BUS_EXTENDER = @as(u32, 42);
pub const FILE_DEVICE_MODEM = @as(u32, 43);
pub const FILE_DEVICE_VDM = @as(u32, 44);
pub const FILE_DEVICE_MASS_STORAGE = @as(u32, 45);
pub const FILE_DEVICE_SMB = @as(u32, 46);
pub const FILE_DEVICE_KS = @as(u32, 47);
pub const FILE_DEVICE_CHANGER = @as(u32, 48);
pub const FILE_DEVICE_SMARTCARD = @as(u32, 49);
pub const FILE_DEVICE_ACPI = @as(u32, 50);
pub const FILE_DEVICE_FULLSCREEN_VIDEO = @as(u32, 52);
pub const FILE_DEVICE_DFS_FILE_SYSTEM = @as(u32, 53);
pub const FILE_DEVICE_DFS_VOLUME = @as(u32, 54);
pub const FILE_DEVICE_SERENUM = @as(u32, 55);
pub const FILE_DEVICE_TERMSRV = @as(u32, 56);
pub const FILE_DEVICE_KSEC = @as(u32, 57);
pub const FILE_DEVICE_FIPS = @as(u32, 58);
pub const FILE_DEVICE_INFINIBAND = @as(u32, 59);
pub const FILE_DEVICE_VMBUS = @as(u32, 62);
pub const FILE_DEVICE_CRYPT_PROVIDER = @as(u32, 63);
pub const FILE_DEVICE_WPD = @as(u32, 64);
pub const FILE_DEVICE_BLUETOOTH = @as(u32, 65);
pub const FILE_DEVICE_MT_COMPOSITE = @as(u32, 66);
pub const FILE_DEVICE_MT_TRANSPORT = @as(u32, 67);
pub const FILE_DEVICE_BIOMETRIC = @as(u32, 68);
pub const FILE_DEVICE_PMI = @as(u32, 69);
pub const FILE_DEVICE_EHSTOR = @as(u32, 70);
pub const FILE_DEVICE_DEVAPI = @as(u32, 71);
pub const FILE_DEVICE_GPIO = @as(u32, 72);
pub const FILE_DEVICE_USBEX = @as(u32, 73);
pub const FILE_DEVICE_CONSOLE = @as(u32, 80);
pub const FILE_DEVICE_NFP = @as(u32, 81);
pub const FILE_DEVICE_SYSENV = @as(u32, 82);
pub const FILE_DEVICE_VIRTUAL_BLOCK = @as(u32, 83);
pub const FILE_DEVICE_POINT_OF_SERVICE = @as(u32, 84);
pub const FILE_DEVICE_STORAGE_REPLICATION = @as(u32, 85);
pub const FILE_DEVICE_TRUST_ENV = @as(u32, 86);
pub const FILE_DEVICE_UCM = @as(u32, 87);
pub const FILE_DEVICE_UCMTCPCI = @as(u32, 88);
pub const FILE_DEVICE_PERSISTENT_MEMORY = @as(u32, 89);
pub const FILE_DEVICE_NVDIMM = @as(u32, 90);
pub const FILE_DEVICE_HOLOGRAPHIC = @as(u32, 91);
pub const FILE_DEVICE_SDFXHCI = @as(u32, 92);
pub const FILE_DEVICE_UCMUCSI = @as(u32, 93);
pub const METHOD_BUFFERED = @as(u32, 0);
pub const METHOD_IN_DIRECT = @as(u32, 1);
pub const METHOD_OUT_DIRECT = @as(u32, 2);
pub const METHOD_NEITHER = @as(u32, 3);
pub const FILE_ANY_ACCESS = @as(u32, 0);
pub const FILE_READ_ACCESS = @as(u32, 1);
pub const FILE_WRITE_ACCESS = @as(u32, 2);
pub const IOCTL_SCMBUS_DEVICE_FUNCTION_BASE = @as(u32, 0);
pub const IOCTL_SCM_LOGICAL_DEVICE_FUNCTION_BASE = @as(u32, 768);
pub const IOCTL_SCM_PHYSICAL_DEVICE_FUNCTION_BASE = @as(u32, 1536);
pub const IOCTL_SCM_BUS_GET_LOGICAL_DEVICES = @as(u32, 5832704);
pub const IOCTL_SCM_BUS_GET_PHYSICAL_DEVICES = @as(u32, 5832708);
pub const IOCTL_SCM_BUS_GET_REGIONS = @as(u32, 5832712);
pub const IOCTL_SCM_LD_GET_INTERLEAVE_SET = @as(u32, 5835776);
pub const IOCTL_SCM_PD_QUERY_PROPERTY = @as(u32, 5838848);
pub const IOCTL_SCM_PD_FIRMWARE_DOWNLOAD = @as(u32, 5871620);
pub const IOCTL_SCM_PD_FIRMWARE_ACTIVATE = @as(u32, 5871624);
pub const IOCTL_SCM_PD_PASSTHROUGH = @as(u32, 5888012);
pub const IOCTL_SCM_PD_UPDATE_MANAGEMENT_STATUS = @as(u32, 5838864);
pub const IOCTL_SCM_PD_REINITIALIZE_MEDIA = @as(u32, 5871636);
pub const SCM_MAX_SYMLINK_LEN_IN_CHARS = @as(u32, 256);
pub const MAX_INTERFACE_CODES = @as(u32, 8);
pub const SCM_PD_FIRMWARE_REVISION_LENGTH_BYTES = @as(u32, 32);
pub const SCM_PD_PROPERTY_NAME_LENGTH_IN_CHARS = @as(u32, 128);
pub const SCM_PD_MAX_OPERATIONAL_STATUS = @as(u32, 16);
pub const SCM_PD_FIRMWARE_LAST_DOWNLOAD = @as(u32, 1);
pub const IOCTL_DISK_GET_DRIVE_GEOMETRY = @as(u32, 458752);
pub const IOCTL_DISK_GET_PARTITION_INFO = @as(u32, 475140);
pub const IOCTL_DISK_SET_PARTITION_INFO = @as(u32, 507912);
pub const IOCTL_DISK_GET_DRIVE_LAYOUT = @as(u32, 475148);
pub const IOCTL_DISK_SET_DRIVE_LAYOUT = @as(u32, 507920);
pub const IOCTL_DISK_VERIFY = @as(u32, 458772);
pub const IOCTL_DISK_FORMAT_TRACKS = @as(u32, 507928);
pub const IOCTL_DISK_REASSIGN_BLOCKS = @as(u32, 507932);
pub const IOCTL_DISK_PERFORMANCE = @as(u32, 458784);
pub const IOCTL_DISK_IS_WRITABLE = @as(u32, 458788);
pub const IOCTL_DISK_LOGGING = @as(u32, 458792);
pub const IOCTL_DISK_FORMAT_TRACKS_EX = @as(u32, 507948);
pub const IOCTL_DISK_HISTOGRAM_STRUCTURE = @as(u32, 458800);
pub const IOCTL_DISK_HISTOGRAM_DATA = @as(u32, 458804);
pub const IOCTL_DISK_HISTOGRAM_RESET = @as(u32, 458808);
pub const IOCTL_DISK_REQUEST_STRUCTURE = @as(u32, 458812);
pub const IOCTL_DISK_REQUEST_DATA = @as(u32, 458816);
pub const IOCTL_DISK_PERFORMANCE_OFF = @as(u32, 458848);
pub const IOCTL_DISK_CONTROLLER_NUMBER = @as(u32, 458820);
pub const SMART_GET_VERSION = @as(u32, 475264);
pub const SMART_SEND_DRIVE_COMMAND = @as(u32, 508036);
pub const SMART_RCV_DRIVE_DATA = @as(u32, 508040);
pub const IOCTL_DISK_GET_PARTITION_INFO_EX = @as(u32, 458824);
pub const IOCTL_DISK_SET_PARTITION_INFO_EX = @as(u32, 507980);
pub const IOCTL_DISK_GET_DRIVE_LAYOUT_EX = @as(u32, 458832);
pub const IOCTL_DISK_SET_DRIVE_LAYOUT_EX = @as(u32, 507988);
pub const IOCTL_DISK_CREATE_DISK = @as(u32, 507992);
pub const IOCTL_DISK_GET_LENGTH_INFO = @as(u32, 475228);
pub const IOCTL_DISK_GET_DRIVE_GEOMETRY_EX = @as(u32, 458912);
pub const IOCTL_DISK_REASSIGN_BLOCKS_EX = @as(u32, 508068);
pub const IOCTL_DISK_UPDATE_DRIVE_SIZE = @as(u32, 508104);
pub const IOCTL_DISK_GROW_PARTITION = @as(u32, 508112);
pub const IOCTL_DISK_GET_CACHE_INFORMATION = @as(u32, 475348);
pub const IOCTL_DISK_SET_CACHE_INFORMATION = @as(u32, 508120);
pub const IOCTL_DISK_GET_WRITE_CACHE_STATE = @as(u32, 475356);
pub const OBSOLETE_DISK_GET_WRITE_CACHE_STATE = @as(u32, 475356);
pub const IOCTL_DISK_DELETE_DRIVE_LAYOUT = @as(u32, 508160);
pub const IOCTL_DISK_UPDATE_PROPERTIES = @as(u32, 459072);
pub const IOCTL_DISK_FORMAT_DRIVE = @as(u32, 508876);
pub const IOCTL_DISK_SENSE_DEVICE = @as(u32, 459744);
pub const IOCTL_DISK_CHECK_VERIFY = @as(u32, 477184);
pub const IOCTL_DISK_MEDIA_REMOVAL = @as(u32, 477188);
pub const IOCTL_DISK_EJECT_MEDIA = @as(u32, 477192);
pub const IOCTL_DISK_LOAD_MEDIA = @as(u32, 477196);
pub const IOCTL_DISK_RESERVE = @as(u32, 477200);
pub const IOCTL_DISK_RELEASE = @as(u32, 477204);
pub const IOCTL_DISK_FIND_NEW_DEVICES = @as(u32, 477208);
pub const IOCTL_DISK_GET_MEDIA_TYPES = @as(u32, 461824);
pub const PARTITION_ENTRY_UNUSED = @as(u32, 0);
pub const PARTITION_FAT_12 = @as(u32, 1);
pub const PARTITION_XENIX_1 = @as(u32, 2);
pub const PARTITION_XENIX_2 = @as(u32, 3);
pub const PARTITION_FAT_16 = @as(u32, 4);
pub const PARTITION_EXTENDED = @as(u32, 5);
pub const PARTITION_HUGE = @as(u32, 6);
pub const PARTITION_IFS = @as(u32, 7);
pub const PARTITION_OS2BOOTMGR = @as(u32, 10);
pub const PARTITION_FAT32 = @as(u32, 11);
pub const PARTITION_FAT32_XINT13 = @as(u32, 12);
pub const PARTITION_XINT13 = @as(u32, 14);
pub const PARTITION_XINT13_EXTENDED = @as(u32, 15);
pub const PARTITION_MSFT_RECOVERY = @as(u32, 39);
pub const PARTITION_MAIN_OS = @as(u32, 40);
pub const PARTIITON_OS_DATA = @as(u32, 41);
pub const PARTITION_PRE_INSTALLED = @as(u32, 42);
pub const PARTITION_BSP = @as(u32, 43);
pub const PARTITION_DPP = @as(u32, 44);
pub const PARTITION_WINDOWS_SYSTEM = @as(u32, 45);
pub const PARTITION_PREP = @as(u32, 65);
pub const PARTITION_LDM = @as(u32, 66);
pub const PARTITION_DM = @as(u32, 84);
pub const PARTITION_EZDRIVE = @as(u32, 85);
pub const PARTITION_UNIX = @as(u32, 99);
pub const PARTITION_SPACES_DATA = @as(u32, 215);
pub const PARTITION_SPACES = @as(u32, 231);
pub const PARTITION_GPT = @as(u32, 238);
pub const PARTITION_SYSTEM = @as(u32, 239);
pub const VALID_NTFT = @as(u32, 192);
pub const PARTITION_NTFT = @as(u32, 128);
pub const GPT_ATTRIBUTE_NO_BLOCK_IO_PROTOCOL = @as(u64, 2);
pub const GPT_ATTRIBUTE_LEGACY_BIOS_BOOTABLE = @as(u64, 4);
pub const GPT_BASIC_DATA_ATTRIBUTE_OFFLINE = @as(u64, 576460752303423488);
pub const GPT_BASIC_DATA_ATTRIBUTE_DAX = @as(u64, 288230376151711744);
pub const GPT_BASIC_DATA_ATTRIBUTE_SERVICE = @as(u64, 144115188075855872);
pub const GPT_SPACES_ATTRIBUTE_NO_METADATA = @as(u64, 9223372036854775808);
pub const HIST_NO_OF_BUCKETS = @as(u32, 24);
pub const DISK_LOGGING_START = @as(u32, 0);
pub const DISK_LOGGING_STOP = @as(u32, 1);
pub const DISK_LOGGING_DUMP = @as(u32, 2);
pub const DISK_BINNING = @as(u32, 3);
pub const CAP_ATA_ID_CMD = @as(u32, 1);
pub const CAP_ATAPI_ID_CMD = @as(u32, 2);
pub const CAP_SMART_CMD = @as(u32, 4);
pub const ATAPI_ID_CMD = @as(u32, 161);
pub const ID_CMD = @as(u32, 236);
pub const SMART_CMD = @as(u32, 176);
pub const SMART_CYL_LOW = @as(u32, 79);
pub const SMART_CYL_HI = @as(u32, 194);
pub const SMART_NO_ERROR = @as(u32, 0);
pub const SMART_IDE_ERROR = @as(u32, 1);
pub const SMART_INVALID_FLAG = @as(u32, 2);
pub const SMART_INVALID_COMMAND = @as(u32, 3);
pub const SMART_INVALID_BUFFER = @as(u32, 4);
pub const SMART_INVALID_DRIVE = @as(u32, 5);
pub const SMART_INVALID_IOCTL = @as(u32, 6);
pub const SMART_ERROR_NO_MEM = @as(u32, 7);
pub const SMART_INVALID_REGISTER = @as(u32, 8);
pub const SMART_NOT_SUPPORTED = @as(u32, 9);
pub const SMART_NO_IDE_DEVICE = @as(u32, 10);
pub const SMART_OFFLINE_ROUTINE_OFFLINE = @as(u32, 0);
pub const SMART_SHORT_SELFTEST_OFFLINE = @as(u32, 1);
pub const SMART_EXTENDED_SELFTEST_OFFLINE = @as(u32, 2);
pub const SMART_ABORT_OFFLINE_SELFTEST = @as(u32, 127);
pub const SMART_SHORT_SELFTEST_CAPTIVE = @as(u32, 129);
pub const SMART_EXTENDED_SELFTEST_CAPTIVE = @as(u32, 130);
pub const READ_ATTRIBUTE_BUFFER_SIZE = @as(u32, 512);
pub const IDENTIFY_BUFFER_SIZE = @as(u32, 512);
pub const READ_THRESHOLD_BUFFER_SIZE = @as(u32, 512);
pub const SMART_LOG_SECTOR_SIZE = @as(u32, 512);
pub const READ_ATTRIBUTES = @as(u32, 208);
pub const READ_THRESHOLDS = @as(u32, 209);
pub const ENABLE_DISABLE_AUTOSAVE = @as(u32, 210);
pub const SAVE_ATTRIBUTE_VALUES = @as(u32, 211);
pub const EXECUTE_OFFLINE_DIAGS = @as(u32, 212);
pub const SMART_READ_LOG = @as(u32, 213);
pub const SMART_WRITE_LOG = @as(u32, 214);
pub const ENABLE_SMART = @as(u32, 216);
pub const DISABLE_SMART = @as(u32, 217);
pub const RETURN_SMART_STATUS = @as(u32, 218);
pub const ENABLE_DISABLE_AUTO_OFFLINE = @as(u32, 219);
pub const IOCTL_DISK_GET_DISK_ATTRIBUTES = @as(u32, 458992);
pub const IOCTL_DISK_SET_DISK_ATTRIBUTES = @as(u32, 508148);
pub const DISK_ATTRIBUTE_OFFLINE = @as(u64, 1);
pub const DISK_ATTRIBUTE_READ_ONLY = @as(u64, 2);
pub const IOCTL_DISK_RESET_SNAPSHOT_INFO = @as(u32, 508432);
pub const IOCTL_CHANGER_GET_PARAMETERS = @as(u32, 3162112);
pub const IOCTL_CHANGER_GET_STATUS = @as(u32, 3162116);
pub const IOCTL_CHANGER_GET_PRODUCT_DATA = @as(u32, 3162120);
pub const IOCTL_CHANGER_SET_ACCESS = @as(u32, 3194896);
pub const IOCTL_CHANGER_GET_ELEMENT_STATUS = @as(u32, 3194900);
pub const IOCTL_CHANGER_INITIALIZE_ELEMENT_STATUS = @as(u32, 3162136);
pub const IOCTL_CHANGER_SET_POSITION = @as(u32, 3162140);
pub const IOCTL_CHANGER_EXCHANGE_MEDIUM = @as(u32, 3162144);
pub const IOCTL_CHANGER_MOVE_MEDIUM = @as(u32, 3162148);
pub const IOCTL_CHANGER_REINITIALIZE_TRANSPORT = @as(u32, 3162152);
pub const IOCTL_CHANGER_QUERY_VOLUME_TAGS = @as(u32, 3194924);
pub const MAX_VOLUME_ID_SIZE = @as(u32, 36);
pub const MAX_VOLUME_TEMPLATE_SIZE = @as(u32, 40);
pub const VENDOR_ID_LENGTH = @as(u32, 8);
pub const PRODUCT_ID_LENGTH = @as(u32, 16);
pub const REVISION_LENGTH = @as(u32, 4);
pub const SERIAL_NUMBER_LENGTH = @as(u32, 32);
pub const CHANGER_RESERVED_BIT = @as(u32, 2147483648);
pub const CHANGER_TO_TRANSPORT = @as(u32, 1);
pub const CHANGER_TO_SLOT = @as(u32, 2);
pub const CHANGER_TO_IEPORT = @as(u32, 4);
pub const CHANGER_TO_DRIVE = @as(u32, 8);
pub const LOCK_UNLOCK_IEPORT = @as(u32, 1);
pub const LOCK_UNLOCK_DOOR = @as(u32, 2);
pub const LOCK_UNLOCK_KEYPAD = @as(u32, 4);
pub const LOCK_ELEMENT = @as(u32, 0);
pub const UNLOCK_ELEMENT = @as(u32, 1);
pub const EXTEND_IEPORT = @as(u32, 2);
pub const RETRACT_IEPORT = @as(u32, 3);
pub const ERROR_LABEL_UNREADABLE = @as(u32, 1);
pub const ERROR_LABEL_QUESTIONABLE = @as(u32, 2);
pub const ERROR_SLOT_NOT_PRESENT = @as(u32, 4);
pub const ERROR_DRIVE_NOT_INSTALLED = @as(u32, 8);
pub const ERROR_TRAY_MALFUNCTION = @as(u32, 16);
pub const ERROR_INIT_STATUS_NEEDED = @as(u32, 17);
pub const ERROR_UNHANDLED_ERROR = @as(u32, 4294967295);
pub const SEARCH_ALL = @as(u32, 0);
pub const SEARCH_PRIMARY = @as(u32, 1);
pub const SEARCH_ALTERNATE = @as(u32, 2);
pub const SEARCH_ALL_NO_SEQ = @as(u32, 4);
pub const SEARCH_PRI_NO_SEQ = @as(u32, 5);
pub const SEARCH_ALT_NO_SEQ = @as(u32, 6);
pub const ASSERT_PRIMARY = @as(u32, 8);
pub const ASSERT_ALTERNATE = @as(u32, 9);
pub const REPLACE_PRIMARY = @as(u32, 10);
pub const REPLACE_ALTERNATE = @as(u32, 11);
pub const UNDEFINE_PRIMARY = @as(u32, 12);
pub const UNDEFINE_ALTERNATE = @as(u32, 13);
pub const IOCTL_SERIAL_LSRMST_INSERT = @as(u32, 1769596);
pub const IOCTL_SERENUM_EXPOSE_HARDWARE = @as(u32, 3604992);
pub const IOCTL_SERENUM_REMOVE_HARDWARE = @as(u32, 3604996);
pub const IOCTL_SERENUM_PORT_DESC = @as(u32, 3605000);
pub const IOCTL_SERENUM_GET_PORT_NAME = @as(u32, 3605004);
pub const FSCTL_REQUEST_OPLOCK_LEVEL_1 = @as(u32, 589824);
pub const FSCTL_REQUEST_OPLOCK_LEVEL_2 = @as(u32, 589828);
pub const FSCTL_REQUEST_BATCH_OPLOCK = @as(u32, 589832);
pub const FSCTL_OPLOCK_BREAK_ACKNOWLEDGE = @as(u32, 589836);
pub const FSCTL_OPBATCH_ACK_CLOSE_PENDING = @as(u32, 589840);
pub const FSCTL_OPLOCK_BREAK_NOTIFY = @as(u32, 589844);
pub const FSCTL_LOCK_VOLUME = @as(u32, 589848);
pub const FSCTL_UNLOCK_VOLUME = @as(u32, 589852);
pub const FSCTL_DISMOUNT_VOLUME = @as(u32, 589856);
pub const FSCTL_IS_VOLUME_MOUNTED = @as(u32, 589864);
pub const FSCTL_IS_PATHNAME_VALID = @as(u32, 589868);
pub const FSCTL_MARK_VOLUME_DIRTY = @as(u32, 589872);
pub const FSCTL_QUERY_RETRIEVAL_POINTERS = @as(u32, 589883);
pub const FSCTL_GET_COMPRESSION = @as(u32, 589884);
pub const FSCTL_SET_COMPRESSION = @as(u32, 639040);
pub const FSCTL_SET_BOOTLOADER_ACCESSED = @as(u32, 589903);
pub const FSCTL_OPLOCK_BREAK_ACK_NO_2 = @as(u32, 589904);
pub const FSCTL_INVALIDATE_VOLUMES = @as(u32, 589908);
pub const FSCTL_QUERY_FAT_BPB = @as(u32, 589912);
pub const FSCTL_REQUEST_FILTER_OPLOCK = @as(u32, 589916);
pub const FSCTL_FILESYSTEM_GET_STATISTICS = @as(u32, 589920);
pub const FSCTL_GET_NTFS_VOLUME_DATA = @as(u32, 589924);
pub const FSCTL_GET_NTFS_FILE_RECORD = @as(u32, 589928);
pub const FSCTL_GET_VOLUME_BITMAP = @as(u32, 589935);
pub const FSCTL_GET_RETRIEVAL_POINTERS = @as(u32, 589939);
pub const FSCTL_MOVE_FILE = @as(u32, 589940);
pub const FSCTL_IS_VOLUME_DIRTY = @as(u32, 589944);
pub const FSCTL_ALLOW_EXTENDED_DASD_IO = @as(u32, 589955);
pub const FSCTL_FIND_FILES_BY_SID = @as(u32, 589967);
pub const FSCTL_SET_OBJECT_ID = @as(u32, 589976);
pub const FSCTL_GET_OBJECT_ID = @as(u32, 589980);
pub const FSCTL_DELETE_OBJECT_ID = @as(u32, 589984);
pub const FSCTL_SET_REPARSE_POINT = @as(u32, 589988);
pub const FSCTL_GET_REPARSE_POINT = @as(u32, 589992);
pub const FSCTL_DELETE_REPARSE_POINT = @as(u32, 589996);
pub const FSCTL_ENUM_USN_DATA = @as(u32, 590003);
pub const FSCTL_SECURITY_ID_CHECK = @as(u32, 606391);
pub const FSCTL_READ_USN_JOURNAL = @as(u32, 590011);
pub const FSCTL_SET_OBJECT_ID_EXTENDED = @as(u32, 590012);
pub const FSCTL_CREATE_OR_GET_OBJECT_ID = @as(u32, 590016);
pub const FSCTL_SET_SPARSE = @as(u32, 590020);
pub const FSCTL_SET_ZERO_DATA = @as(u32, 622792);
pub const FSCTL_QUERY_ALLOCATED_RANGES = @as(u32, 606415);
pub const FSCTL_ENABLE_UPGRADE = @as(u32, 622800);
pub const FSCTL_SET_ENCRYPTION = @as(u32, 590039);
pub const FSCTL_ENCRYPTION_FSCTL_IO = @as(u32, 590043);
pub const FSCTL_WRITE_RAW_ENCRYPTED = @as(u32, 590047);
pub const FSCTL_READ_RAW_ENCRYPTED = @as(u32, 590051);
pub const FSCTL_CREATE_USN_JOURNAL = @as(u32, 590055);
pub const FSCTL_READ_FILE_USN_DATA = @as(u32, 590059);
pub const FSCTL_WRITE_USN_CLOSE_RECORD = @as(u32, 590063);
pub const FSCTL_EXTEND_VOLUME = @as(u32, 590064);
pub const FSCTL_QUERY_USN_JOURNAL = @as(u32, 590068);
pub const FSCTL_DELETE_USN_JOURNAL = @as(u32, 590072);
pub const FSCTL_MARK_HANDLE = @as(u32, 590076);
pub const FSCTL_SIS_COPYFILE = @as(u32, 590080);
pub const FSCTL_SIS_LINK_FILES = @as(u32, 639236);
pub const FSCTL_RECALL_FILE = @as(u32, 590103);
pub const FSCTL_READ_FROM_PLEX = @as(u32, 606494);
pub const FSCTL_FILE_PREFETCH = @as(u32, 590112);
pub const FSCTL_MAKE_MEDIA_COMPATIBLE = @as(u32, 622896);
pub const FSCTL_SET_DEFECT_MANAGEMENT = @as(u32, 622900);
pub const FSCTL_QUERY_SPARING_INFO = @as(u32, 590136);
pub const FSCTL_QUERY_ON_DISK_VOLUME_INFO = @as(u32, 590140);
pub const FSCTL_SET_VOLUME_COMPRESSION_STATE = @as(u32, 590144);
pub const FSCTL_TXFS_MODIFY_RM = @as(u32, 622916);
pub const FSCTL_TXFS_QUERY_RM_INFORMATION = @as(u32, 606536);
pub const FSCTL_TXFS_ROLLFORWARD_REDO = @as(u32, 622928);
pub const FSCTL_TXFS_ROLLFORWARD_UNDO = @as(u32, 622932);
pub const FSCTL_TXFS_START_RM = @as(u32, 622936);
pub const FSCTL_TXFS_SHUTDOWN_RM = @as(u32, 622940);
pub const FSCTL_TXFS_READ_BACKUP_INFORMATION = @as(u32, 606560);
pub const FSCTL_TXFS_WRITE_BACKUP_INFORMATION = @as(u32, 622948);
pub const FSCTL_TXFS_CREATE_SECONDARY_RM = @as(u32, 622952);
pub const FSCTL_TXFS_GET_METADATA_INFO = @as(u32, 606572);
pub const FSCTL_TXFS_GET_TRANSACTED_VERSION = @as(u32, 606576);
pub const FSCTL_TXFS_SAVEPOINT_INFORMATION = @as(u32, 622968);
pub const FSCTL_TXFS_CREATE_MINIVERSION = @as(u32, 622972);
pub const FSCTL_TXFS_TRANSACTION_ACTIVE = @as(u32, 606604);
pub const FSCTL_SET_ZERO_ON_DEALLOCATION = @as(u32, 590228);
pub const FSCTL_SET_REPAIR = @as(u32, 590232);
pub const FSCTL_GET_REPAIR = @as(u32, 590236);
pub const FSCTL_WAIT_FOR_REPAIR = @as(u32, 590240);
pub const FSCTL_INITIATE_REPAIR = @as(u32, 590248);
pub const FSCTL_CSC_INTERNAL = @as(u32, 590255);
pub const FSCTL_SHRINK_VOLUME = @as(u32, 590256);
pub const FSCTL_SET_SHORT_NAME_BEHAVIOR = @as(u32, 590260);
pub const FSCTL_DFSR_SET_GHOST_HANDLE_STATE = @as(u32, 590264);
pub const FSCTL_TXFS_LIST_TRANSACTION_LOCKED_FILES = @as(u32, 606688);
pub const FSCTL_TXFS_LIST_TRANSACTIONS = @as(u32, 606692);
pub const FSCTL_QUERY_PAGEFILE_ENCRYPTION = @as(u32, 590312);
pub const FSCTL_RESET_VOLUME_ALLOCATION_HINTS = @as(u32, 590316);
pub const FSCTL_QUERY_DEPENDENT_VOLUME = @as(u32, 590320);
pub const FSCTL_SD_GLOBAL_CHANGE = @as(u32, 590324);
pub const FSCTL_TXFS_READ_BACKUP_INFORMATION2 = @as(u32, 590328);
pub const FSCTL_LOOKUP_STREAM_FROM_CLUSTER = @as(u32, 590332);
pub const FSCTL_TXFS_WRITE_BACKUP_INFORMATION2 = @as(u32, 590336);
pub const FSCTL_FILE_TYPE_NOTIFICATION = @as(u32, 590340);
pub const FSCTL_FILE_LEVEL_TRIM = @as(u32, 623112);
pub const FSCTL_GET_BOOT_AREA_INFO = @as(u32, 590384);
pub const FSCTL_GET_RETRIEVAL_POINTER_BASE = @as(u32, 590388);
pub const FSCTL_SET_PERSISTENT_VOLUME_STATE = @as(u32, 590392);
pub const FSCTL_QUERY_PERSISTENT_VOLUME_STATE = @as(u32, 590396);
pub const FSCTL_REQUEST_OPLOCK = @as(u32, 590400);
pub const FSCTL_CSV_TUNNEL_REQUEST = @as(u32, 590404);
pub const FSCTL_IS_CSV_FILE = @as(u32, 590408);
pub const FSCTL_QUERY_FILE_SYSTEM_RECOGNITION = @as(u32, 590412);
pub const FSCTL_CSV_GET_VOLUME_PATH_NAME = @as(u32, 590416);
pub const FSCTL_CSV_GET_VOLUME_NAME_FOR_VOLUME_MOUNT_POINT = @as(u32, 590420);
pub const FSCTL_CSV_GET_VOLUME_PATH_NAMES_FOR_VOLUME_NAME = @as(u32, 590424);
pub const FSCTL_IS_FILE_ON_CSV_VOLUME = @as(u32, 590428);
pub const FSCTL_CORRUPTION_HANDLING = @as(u32, 590432);
pub const FSCTL_OFFLOAD_READ = @as(u32, 606820);
pub const FSCTL_OFFLOAD_WRITE = @as(u32, 623208);
pub const FSCTL_CSV_INTERNAL = @as(u32, 590444);
pub const FSCTL_SET_PURGE_FAILURE_MODE = @as(u32, 590448);
pub const FSCTL_QUERY_FILE_LAYOUT = @as(u32, 590455);
pub const FSCTL_IS_VOLUME_OWNED_BYCSVFS = @as(u32, 590456);
pub const FSCTL_GET_INTEGRITY_INFORMATION = @as(u32, 590460);
pub const FSCTL_SET_INTEGRITY_INFORMATION = @as(u32, 639616);
pub const FSCTL_QUERY_FILE_REGIONS = @as(u32, 590468);
pub const FSCTL_RKF_INTERNAL = @as(u32, 590511);
pub const FSCTL_SCRUB_DATA = @as(u32, 590512);
pub const FSCTL_REPAIR_COPIES = @as(u32, 639668);
pub const FSCTL_DISABLE_LOCAL_BUFFERING = @as(u32, 590520);
pub const FSCTL_CSV_MGMT_LOCK = @as(u32, 590524);
pub const FSCTL_CSV_QUERY_DOWN_LEVEL_FILE_SYSTEM_CHARACTERISTICS = @as(u32, 590528);
pub const FSCTL_ADVANCE_FILE_ID = @as(u32, 590532);
pub const FSCTL_CSV_SYNC_TUNNEL_REQUEST = @as(u32, 590536);
pub const FSCTL_CSV_QUERY_VETO_FILE_DIRECT_IO = @as(u32, 590540);
pub const FSCTL_WRITE_USN_REASON = @as(u32, 590544);
pub const FSCTL_CSV_CONTROL = @as(u32, 590548);
pub const FSCTL_GET_REFS_VOLUME_DATA = @as(u32, 590552);
pub const FSCTL_CSV_H_BREAKING_SYNC_TUNNEL_REQUEST = @as(u32, 590564);
pub const FSCTL_QUERY_STORAGE_CLASSES = @as(u32, 590572);
pub const FSCTL_QUERY_REGION_INFO = @as(u32, 590576);
pub const FSCTL_USN_TRACK_MODIFIED_RANGES = @as(u32, 590580);
pub const FSCTL_QUERY_SHARED_VIRTUAL_DISK_SUPPORT = @as(u32, 590592);
pub const FSCTL_SVHDX_SYNC_TUNNEL_REQUEST = @as(u32, 590596);
pub const FSCTL_SVHDX_SET_INITIATOR_INFORMATION = @as(u32, 590600);
pub const FSCTL_SET_EXTERNAL_BACKING = @as(u32, 590604);
pub const FSCTL_GET_EXTERNAL_BACKING = @as(u32, 590608);
pub const FSCTL_DELETE_EXTERNAL_BACKING = @as(u32, 590612);
pub const FSCTL_ENUM_EXTERNAL_BACKING = @as(u32, 590616);
pub const FSCTL_ENUM_OVERLAY = @as(u32, 590623);
pub const FSCTL_ADD_OVERLAY = @as(u32, 623408);
pub const FSCTL_REMOVE_OVERLAY = @as(u32, 623412);
pub const FSCTL_UPDATE_OVERLAY = @as(u32, 623416);
pub const FSCTL_SHUFFLE_FILE = @as(u32, 639808);
pub const FSCTL_DUPLICATE_EXTENTS_TO_FILE = @as(u32, 623428);
pub const FSCTL_SPARSE_OVERALLOCATE = @as(u32, 590668);
pub const FSCTL_STORAGE_QOS_CONTROL = @as(u32, 590672);
pub const FSCTL_INITIATE_FILE_METADATA_OPTIMIZATION = @as(u32, 590684);
pub const FSCTL_QUERY_FILE_METADATA_OPTIMIZATION = @as(u32, 590688);
pub const FSCTL_SVHDX_ASYNC_TUNNEL_REQUEST = @as(u32, 590692);
pub const FSCTL_GET_WOF_VERSION = @as(u32, 590696);
pub const FSCTL_HCS_SYNC_TUNNEL_REQUEST = @as(u32, 590700);
pub const FSCTL_HCS_ASYNC_TUNNEL_REQUEST = @as(u32, 590704);
pub const FSCTL_QUERY_EXTENT_READ_CACHE_INFO = @as(u32, 590711);
pub const FSCTL_QUERY_REFS_VOLUME_COUNTER_INFO = @as(u32, 590715);
pub const FSCTL_CLEAN_VOLUME_METADATA = @as(u32, 590716);
pub const FSCTL_SET_INTEGRITY_INFORMATION_EX = @as(u32, 590720);
pub const FSCTL_SUSPEND_OVERLAY = @as(u32, 590724);
pub const FSCTL_VIRTUAL_STORAGE_QUERY_PROPERTY = @as(u32, 590728);
pub const FSCTL_FILESYSTEM_GET_STATISTICS_EX = @as(u32, 590732);
pub const FSCTL_QUERY_VOLUME_CONTAINER_STATE = @as(u32, 590736);
pub const FSCTL_SET_LAYER_ROOT = @as(u32, 590740);
pub const FSCTL_QUERY_DIRECT_ACCESS_EXTENTS = @as(u32, 590747);
pub const FSCTL_NOTIFY_STORAGE_SPACE_ALLOCATION = @as(u32, 590748);
pub const FSCTL_SSDI_STORAGE_REQUEST = @as(u32, 590752);
pub const FSCTL_QUERY_DIRECT_IMAGE_ORIGINAL_BASE = @as(u32, 590756);
pub const FSCTL_READ_UNPRIVILEGED_USN_JOURNAL = @as(u32, 590763);
pub const FSCTL_GHOST_FILE_EXTENTS = @as(u32, 623532);
pub const FSCTL_QUERY_GHOSTED_FILE_EXTENTS = @as(u32, 590768);
pub const FSCTL_UNMAP_SPACE = @as(u32, 590772);
pub const FSCTL_HCS_SYNC_NO_WRITE_TUNNEL_REQUEST = @as(u32, 590776);
pub const FSCTL_STREAMS_QUERY_PARAMETERS = @as(u32, 590788);
pub const FSCTL_STREAMS_ASSOCIATE_ID = @as(u32, 590792);
pub const FSCTL_STREAMS_QUERY_ID = @as(u32, 590796);
pub const FSCTL_GET_RETRIEVAL_POINTERS_AND_REFCOUNT = @as(u32, 590803);
pub const FSCTL_QUERY_VOLUME_NUMA_INFO = @as(u32, 590804);
pub const FSCTL_REFS_DEALLOCATE_RANGES = @as(u32, 590808);
pub const FSCTL_QUERY_REFS_SMR_VOLUME_INFO = @as(u32, 590812);
pub const FSCTL_SET_REFS_SMR_VOLUME_GC_PARAMETERS = @as(u32, 590816);
pub const FSCTL_SET_REFS_FILE_STRICTLY_SEQUENTIAL = @as(u32, 590820);
pub const FSCTL_DUPLICATE_EXTENTS_TO_FILE_EX = @as(u32, 623592);
pub const FSCTL_QUERY_BAD_RANGES = @as(u32, 590828);
pub const FSCTL_SET_DAX_ALLOC_ALIGNMENT_HINT = @as(u32, 590832);
pub const FSCTL_DELETE_CORRUPTED_REFS_CONTAINER = @as(u32, 590836);
pub const FSCTL_SCRUB_UNDISCOVERABLE_ID = @as(u32, 590840);
pub const FSCTL_NOTIFY_DATA_CHANGE = @as(u32, 590844);
pub const FSCTL_START_VIRTUALIZATION_INSTANCE_EX = @as(u32, 590848);
pub const FSCTL_ENCRYPTION_KEY_CONTROL = @as(u32, 590852);
pub const FSCTL_VIRTUAL_STORAGE_SET_BEHAVIOR = @as(u32, 590856);
pub const FSCTL_SET_REPARSE_POINT_EX = @as(u32, 590860);
pub const FSCTL_REARRANGE_FILE = @as(u32, 640032);
pub const FSCTL_VIRTUAL_STORAGE_PASSTHROUGH = @as(u32, 590884);
pub const FSCTL_GET_RETRIEVAL_POINTER_COUNT = @as(u32, 590891);
pub const FSCTL_ENABLE_PER_IO_FLAGS = @as(u32, 590892);
pub const GET_VOLUME_BITMAP_FLAG_MASK_METADATA = @as(u32, 1);
pub const FLAG_USN_TRACK_MODIFIED_RANGES_ENABLE = @as(u32, 1);
pub const USN_PAGE_SIZE = @as(u32, 4096);
pub const USN_REASON_DATA_OVERWRITE = @as(u32, 1);
pub const USN_REASON_DATA_EXTEND = @as(u32, 2);
pub const USN_REASON_DATA_TRUNCATION = @as(u32, 4);
pub const USN_REASON_NAMED_DATA_OVERWRITE = @as(u32, 16);
pub const USN_REASON_NAMED_DATA_EXTEND = @as(u32, 32);
pub const USN_REASON_NAMED_DATA_TRUNCATION = @as(u32, 64);
pub const USN_REASON_FILE_CREATE = @as(u32, 256);
pub const USN_REASON_FILE_DELETE = @as(u32, 512);
pub const USN_REASON_EA_CHANGE = @as(u32, 1024);
pub const USN_REASON_SECURITY_CHANGE = @as(u32, 2048);
pub const USN_REASON_RENAME_OLD_NAME = @as(u32, 4096);
pub const USN_REASON_RENAME_NEW_NAME = @as(u32, 8192);
pub const USN_REASON_INDEXABLE_CHANGE = @as(u32, 16384);
pub const USN_REASON_BASIC_INFO_CHANGE = @as(u32, 32768);
pub const USN_REASON_HARD_LINK_CHANGE = @as(u32, 65536);
pub const USN_REASON_COMPRESSION_CHANGE = @as(u32, 131072);
pub const USN_REASON_ENCRYPTION_CHANGE = @as(u32, 262144);
pub const USN_REASON_OBJECT_ID_CHANGE = @as(u32, 524288);
pub const USN_REASON_REPARSE_POINT_CHANGE = @as(u32, 1048576);
pub const USN_REASON_STREAM_CHANGE = @as(u32, 2097152);
pub const USN_REASON_TRANSACTED_CHANGE = @as(u32, 4194304);
pub const USN_REASON_INTEGRITY_CHANGE = @as(u32, 8388608);
pub const USN_REASON_DESIRED_STORAGE_CLASS_CHANGE = @as(u32, 16777216);
pub const USN_REASON_CLOSE = @as(u32, 2147483648);
pub const USN_DELETE_VALID_FLAGS = @as(u32, 3);
pub const MARK_HANDLE_PROTECT_CLUSTERS = @as(u32, 1);
pub const MARK_HANDLE_TXF_SYSTEM_LOG = @as(u32, 4);
pub const MARK_HANDLE_NOT_TXF_SYSTEM_LOG = @as(u32, 8);
pub const MARK_HANDLE_REALTIME = @as(u32, 32);
pub const MARK_HANDLE_NOT_REALTIME = @as(u32, 64);
pub const MARK_HANDLE_FILTER_METADATA = @as(u32, 512);
pub const MARK_HANDLE_CLOUD_SYNC = @as(u32, 2048);
pub const MARK_HANDLE_READ_COPY = @as(u32, 128);
pub const MARK_HANDLE_NOT_READ_COPY = @as(u32, 256);
pub const MARK_HANDLE_RETURN_PURGE_FAILURE = @as(u32, 1024);
pub const MARK_HANDLE_DISABLE_FILE_METADATA_OPTIMIZATION = @as(u32, 4096);
pub const MARK_HANDLE_ENABLE_USN_SOURCE_ON_PAGING_IO = @as(u32, 8192);
pub const MARK_HANDLE_SKIP_COHERENCY_SYNC_DISALLOW_WRITES = @as(u32, 16384);
pub const MARK_HANDLE_ENABLE_CPU_CACHE = @as(u32, 268435456);
pub const VOLUME_IS_DIRTY = @as(u32, 1);
pub const VOLUME_UPGRADE_SCHEDULED = @as(u32, 2);
pub const VOLUME_SESSION_OPEN = @as(u32, 4);
pub const FILE_PREFETCH_TYPE_FOR_CREATE = @as(u32, 1);
pub const FILE_PREFETCH_TYPE_FOR_DIRENUM = @as(u32, 2);
pub const FILE_PREFETCH_TYPE_FOR_CREATE_EX = @as(u32, 3);
pub const FILE_PREFETCH_TYPE_FOR_DIRENUM_EX = @as(u32, 4);
pub const FILE_PREFETCH_TYPE_MAX = @as(u32, 4);
pub const FILESYSTEM_STATISTICS_TYPE_REFS = @as(u32, 4);
pub const FILE_ZERO_DATA_INFORMATION_FLAG_PRESERVE_CACHED_DATA = @as(u32, 1);
pub const FILE_SET_ENCRYPTION = @as(u32, 1);
pub const FILE_CLEAR_ENCRYPTION = @as(u32, 2);
pub const STREAM_SET_ENCRYPTION = @as(u32, 3);
pub const STREAM_CLEAR_ENCRYPTION = @as(u32, 4);
pub const MAXIMUM_ENCRYPTION_VALUE = @as(u32, 4);
pub const ENCRYPTION_FORMAT_DEFAULT = @as(u32, 1);
pub const ENCRYPTED_DATA_INFO_SPARSE_FILE = @as(u32, 1);
pub const COPYFILE_SIS_LINK = @as(u32, 1);
pub const COPYFILE_SIS_REPLACE = @as(u32, 2);
pub const COPYFILE_SIS_FLAGS = @as(u32, 3);
pub const SET_REPAIR_ENABLED = @as(u32, 1);
pub const SET_REPAIR_WARN_ABOUT_DATA_LOSS = @as(u32, 8);
pub const SET_REPAIR_DISABLED_AND_BUGCHECK_ON_CORRUPT = @as(u32, 16);
pub const SET_REPAIR_VALID_MASK = @as(u32, 25);
pub const FILE_INITIATE_REPAIR_HINT1_FILE_RECORD_NOT_IN_USE = @as(u64, 1);
pub const FILE_INITIATE_REPAIR_HINT1_FILE_RECORD_REUSED = @as(u64, 2);
pub const FILE_INITIATE_REPAIR_HINT1_FILE_RECORD_NOT_EXIST = @as(u64, 4);
pub const FILE_INITIATE_REPAIR_HINT1_FILE_RECORD_NOT_BASE_RECORD = @as(u64, 8);
pub const FILE_INITIATE_REPAIR_HINT1_SYSTEM_FILE = @as(u64, 16);
pub const FILE_INITIATE_REPAIR_HINT1_NOT_IMPLEMENTED = @as(u64, 32);
pub const FILE_INITIATE_REPAIR_HINT1_UNABLE_TO_REPAIR = @as(u64, 64);
pub const FILE_INITIATE_REPAIR_HINT1_REPAIR_DISABLED = @as(u64, 128);
pub const FILE_INITIATE_REPAIR_HINT1_RECURSIVELY_CORRUPTED = @as(u64, 256);
pub const FILE_INITIATE_REPAIR_HINT1_ORPHAN_GENERATED = @as(u64, 512);
pub const FILE_INITIATE_REPAIR_HINT1_REPAIRED = @as(u64, 1024);
pub const FILE_INITIATE_REPAIR_HINT1_NOTHING_WRONG = @as(u64, 2048);
pub const FILE_INITIATE_REPAIR_HINT1_ATTRIBUTE_NOT_FOUND = @as(u64, 4096);
pub const FILE_INITIATE_REPAIR_HINT1_POTENTIAL_CROSSLINK = @as(u64, 8192);
pub const FILE_INITIATE_REPAIR_HINT1_STALE_INFORMATION = @as(u64, 16384);
pub const FILE_INITIATE_REPAIR_HINT1_CLUSTERS_ALREADY_IN_USE = @as(u64, 32768);
pub const FILE_INITIATE_REPAIR_HINT1_LCN_NOT_EXIST = @as(u64, 65536);
pub const FILE_INITIATE_REPAIR_HINT1_INVALID_RUN_LENGTH = @as(u64, 131072);
pub const FILE_INITIATE_REPAIR_HINT1_FILE_RECORD_NOT_ORPHAN = @as(u64, 262144);
pub const FILE_INITIATE_REPAIR_HINT1_FILE_RECORD_IS_BASE_RECORD = @as(u64, 524288);
pub const FILE_INITIATE_REPAIR_HINT1_INVALID_ARRAY_LENGTH_COUNT = @as(u64, 1048576);
pub const FILE_INITIATE_REPAIR_HINT1_SID_VALID = @as(u64, 2097152);
pub const FILE_INITIATE_REPAIR_HINT1_SID_MISMATCH = @as(u64, 4194304);
pub const FILE_INITIATE_REPAIR_HINT1_INVALID_PARENT = @as(u64, 8388608);
pub const FILE_INITIATE_REPAIR_HINT1_PARENT_FILE_RECORD_NOT_IN_USE = @as(u64, 16777216);
pub const FILE_INITIATE_REPAIR_HINT1_PARENT_FILE_RECORD_REUSED = @as(u64, 33554432);
pub const FILE_INITIATE_REPAIR_HINT1_PARENT_FILE_RECORD_NOT_EXIST = @as(u64, 67108864);
pub const FILE_INITIATE_REPAIR_HINT1_PARENT_FILE_RECORD_NOT_BASE_RECORD = @as(u64, 134217728);
pub const FILE_INITIATE_REPAIR_HINT1_PARENT_FILE_RECORD_NOT_INDEX = @as(u64, 268435456);
pub const FILE_INITIATE_REPAIR_HINT1_VALID_INDEX_ENTRY = @as(u64, 536870912);
pub const FILE_INITIATE_REPAIR_HINT1_OUT_OF_GENERIC_NAMES = @as(u64, 1073741824);
pub const FILE_INITIATE_REPAIR_HINT1_OUT_OF_RESOURCE = @as(u64, 2147483648);
pub const FILE_INITIATE_REPAIR_HINT1_INVALID_LCN = @as(u64, 4294967296);
pub const FILE_INITIATE_REPAIR_HINT1_INVALID_VCN = @as(u64, 8589934592);
pub const FILE_INITIATE_REPAIR_HINT1_NAME_CONFLICT = @as(u64, 17179869184);
pub const FILE_INITIATE_REPAIR_HINT1_ORPHAN = @as(u64, 34359738368);
pub const FILE_INITIATE_REPAIR_HINT1_ATTRIBUTE_TOO_SMALL = @as(u64, 68719476736);
pub const FILE_INITIATE_REPAIR_HINT1_ATTRIBUTE_NON_RESIDENT = @as(u64, 137438953472);
pub const FILE_INITIATE_REPAIR_HINT1_DENY_DEFRAG = @as(u64, 274877906944);
pub const FILE_INITIATE_REPAIR_HINT1_PREVIOUS_PARENT_STILL_VALID = @as(u64, 549755813888);
pub const FILE_INITIATE_REPAIR_HINT1_INDEX_ENTRY_MISMATCH = @as(u64, 1099511627776);
pub const FILE_INITIATE_REPAIR_HINT1_INVALID_ORPHAN_RECOVERY_NAME = @as(u64, 2199023255552);
pub const FILE_INITIATE_REPAIR_HINT1_MULTIPLE_FILE_NAME_ATTRIBUTES = @as(u64, 4398046511104);
pub const TXFS_LOGGING_MODE_SIMPLE = @as(u32, 1);
pub const TXFS_LOGGING_MODE_FULL = @as(u32, 2);
pub const TXFS_TRANSACTION_STATE_NONE = @as(u32, 0);
pub const TXFS_TRANSACTION_STATE_ACTIVE = @as(u32, 1);
pub const TXFS_TRANSACTION_STATE_PREPARED = @as(u32, 2);
pub const TXFS_TRANSACTION_STATE_NOTACTIVE = @as(u32, 3);
pub const TXFS_RM_STATE_NOT_STARTED = @as(u32, 0);
pub const TXFS_RM_STATE_STARTING = @as(u32, 1);
pub const TXFS_RM_STATE_ACTIVE = @as(u32, 2);
pub const TXFS_RM_STATE_SHUTTING_DOWN = @as(u32, 3);
pub const TXFS_ROLLFORWARD_REDO_FLAG_USE_LAST_REDO_LSN = @as(u32, 1);
pub const TXFS_ROLLFORWARD_REDO_FLAG_USE_LAST_VIRTUAL_CLOCK = @as(u32, 2);
pub const TXFS_START_RM_FLAG_LOG_CONTAINER_COUNT_MAX = @as(u32, 1);
pub const TXFS_START_RM_FLAG_LOG_CONTAINER_COUNT_MIN = @as(u32, 2);
pub const TXFS_START_RM_FLAG_LOG_CONTAINER_SIZE = @as(u32, 4);
pub const TXFS_START_RM_FLAG_LOG_GROWTH_INCREMENT_NUM_CONTAINERS = @as(u32, 8);
pub const TXFS_START_RM_FLAG_LOG_GROWTH_INCREMENT_PERCENT = @as(u32, 16);
pub const TXFS_START_RM_FLAG_LOG_AUTO_SHRINK_PERCENTAGE = @as(u32, 32);
pub const TXFS_START_RM_FLAG_LOG_NO_CONTAINER_COUNT_MAX = @as(u32, 64);
pub const TXFS_START_RM_FLAG_LOG_NO_CONTAINER_COUNT_MIN = @as(u32, 128);
pub const TXFS_START_RM_FLAG_RECOVER_BEST_EFFORT = @as(u32, 512);
pub const TXFS_START_RM_FLAG_LOGGING_MODE = @as(u32, 1024);
pub const TXFS_START_RM_FLAG_PRESERVE_CHANGES = @as(u32, 2048);
pub const TXFS_START_RM_FLAG_PREFER_CONSISTENCY = @as(u32, 4096);
pub const TXFS_START_RM_FLAG_PREFER_AVAILABILITY = @as(u32, 8192);
pub const TXFS_LIST_TRANSACTION_LOCKED_FILES_ENTRY_FLAG_CREATED = @as(u32, 1);
pub const TXFS_LIST_TRANSACTION_LOCKED_FILES_ENTRY_FLAG_DELETED = @as(u32, 2);
pub const TXFS_TRANSACTED_VERSION_NONTRANSACTED = @as(u32, 4294967294);
pub const TXFS_TRANSACTED_VERSION_UNCOMMITTED = @as(u32, 4294967295);
pub const TXFS_SAVEPOINT_SET = @as(u32, 1);
pub const TXFS_SAVEPOINT_ROLLBACK = @as(u32, 2);
pub const TXFS_SAVEPOINT_CLEAR = @as(u32, 4);
pub const TXFS_SAVEPOINT_CLEAR_ALL = @as(u32, 16);
pub const PERSISTENT_VOLUME_STATE_SHORT_NAME_CREATION_DISABLED = @as(u32, 1);
pub const PERSISTENT_VOLUME_STATE_VOLUME_SCRUB_DISABLED = @as(u32, 2);
pub const PERSISTENT_VOLUME_STATE_GLOBAL_METADATA_NO_SEEK_PENALTY = @as(u32, 4);
pub const PERSISTENT_VOLUME_STATE_LOCAL_METADATA_NO_SEEK_PENALTY = @as(u32, 8);
pub const PERSISTENT_VOLUME_STATE_NO_HEAT_GATHERING = @as(u32, 16);
pub const PERSISTENT_VOLUME_STATE_CONTAINS_BACKING_WIM = @as(u32, 32);
pub const PERSISTENT_VOLUME_STATE_BACKED_BY_WIM = @as(u32, 64);
pub const PERSISTENT_VOLUME_STATE_NO_WRITE_AUTO_TIERING = @as(u32, 128);
pub const PERSISTENT_VOLUME_STATE_TXF_DISABLED = @as(u32, 256);
pub const PERSISTENT_VOLUME_STATE_REALLOCATE_ALL_DATA_WRITES = @as(u32, 512);
pub const OPLOCK_LEVEL_CACHE_READ = @as(u32, 1);
pub const OPLOCK_LEVEL_CACHE_HANDLE = @as(u32, 2);
pub const OPLOCK_LEVEL_CACHE_WRITE = @as(u32, 4);
pub const REQUEST_OPLOCK_INPUT_FLAG_REQUEST = @as(u32, 1);
pub const REQUEST_OPLOCK_INPUT_FLAG_ACK = @as(u32, 2);
pub const REQUEST_OPLOCK_INPUT_FLAG_COMPLETE_ACK_ON_CLOSE = @as(u32, 4);
pub const REQUEST_OPLOCK_CURRENT_VERSION = @as(u32, 1);
pub const REQUEST_OPLOCK_OUTPUT_FLAG_ACK_REQUIRED = @as(u32, 1);
pub const REQUEST_OPLOCK_OUTPUT_FLAG_MODES_PROVIDED = @as(u32, 2);
pub const QUERY_DEPENDENT_VOLUME_REQUEST_FLAG_HOST_VOLUMES = @as(u32, 1);
pub const QUERY_DEPENDENT_VOLUME_REQUEST_FLAG_GUEST_VOLUMES = @as(u32, 2);
pub const SD_GLOBAL_CHANGE_TYPE_MACHINE_SID = @as(u32, 1);
pub const SD_GLOBAL_CHANGE_TYPE_QUERY_STATS = @as(u32, 65536);
pub const SD_GLOBAL_CHANGE_TYPE_ENUM_SDS = @as(u32, 131072);
pub const LOOKUP_STREAM_FROM_CLUSTER_ENTRY_FLAG_PAGE_FILE = @as(u32, 1);
pub const LOOKUP_STREAM_FROM_CLUSTER_ENTRY_FLAG_DENY_DEFRAG_SET = @as(u32, 2);
pub const LOOKUP_STREAM_FROM_CLUSTER_ENTRY_FLAG_FS_SYSTEM_FILE = @as(u32, 4);
pub const LOOKUP_STREAM_FROM_CLUSTER_ENTRY_FLAG_TXF_SYSTEM_FILE = @as(u32, 8);
pub const LOOKUP_STREAM_FROM_CLUSTER_ENTRY_ATTRIBUTE_MASK = @as(u32, 4278190080);
pub const LOOKUP_STREAM_FROM_CLUSTER_ENTRY_ATTRIBUTE_DATA = @as(u32, 16777216);
pub const LOOKUP_STREAM_FROM_CLUSTER_ENTRY_ATTRIBUTE_INDEX = @as(u32, 33554432);
pub const LOOKUP_STREAM_FROM_CLUSTER_ENTRY_ATTRIBUTE_SYSTEM = @as(u32, 50331648);
pub const FILE_TYPE_NOTIFICATION_FLAG_USAGE_BEGIN = @as(u32, 1);
pub const FILE_TYPE_NOTIFICATION_FLAG_USAGE_END = @as(u32, 2);
pub const FILE_TYPE_NOTIFICATION_GUID_PAGE_FILE = Guid.initString("0d0a64a1-38fc-4db8-9fe7-3f4352cd7c5c");
pub const FILE_TYPE_NOTIFICATION_GUID_HIBERNATION_FILE = Guid.initString("b7624d64-b9a3-4cf8-8011-5b86c940e7b7");
pub const FILE_TYPE_NOTIFICATION_GUID_CRASHDUMP_FILE = Guid.initString("9d453eb7-d2a6-4dbd-a2e3-fbd0ed9109a9");
pub const CSV_MGMTLOCK_CHECK_VOLUME_REDIRECTED = @as(u32, 1);
pub const CSV_INVALID_DEVICE_NUMBER = @as(u32, 4294967295);
pub const CSV_QUERY_MDS_PATH_V2_VERSION_1 = @as(u32, 1);
pub const CSV_QUERY_MDS_PATH_FLAG_STORAGE_ON_THIS_NODE_IS_CONNECTED = @as(u32, 1);
pub const CSV_QUERY_MDS_PATH_FLAG_CSV_DIRECT_IO_ENABLED = @as(u32, 2);
pub const CSV_QUERY_MDS_PATH_FLAG_SMB_BYPASS_CSV_ENABLED = @as(u32, 4);
pub const QUERY_FILE_LAYOUT_RESTART = @as(u32, 1);
pub const QUERY_FILE_LAYOUT_INCLUDE_NAMES = @as(u32, 2);
pub const QUERY_FILE_LAYOUT_INCLUDE_STREAMS = @as(u32, 4);
pub const QUERY_FILE_LAYOUT_INCLUDE_EXTENTS = @as(u32, 8);
pub const QUERY_FILE_LAYOUT_INCLUDE_EXTRA_INFO = @as(u32, 16);
pub const QUERY_FILE_LAYOUT_INCLUDE_STREAMS_WITH_NO_CLUSTERS_ALLOCATED = @as(u32, 32);
pub const QUERY_FILE_LAYOUT_INCLUDE_FULL_PATH_IN_NAMES = @as(u32, 64);
pub const QUERY_FILE_LAYOUT_INCLUDE_STREAM_INFORMATION = @as(u32, 128);
pub const QUERY_FILE_LAYOUT_INCLUDE_STREAM_INFORMATION_FOR_DSC_ATTRIBUTE = @as(u32, 256);
pub const QUERY_FILE_LAYOUT_INCLUDE_STREAM_INFORMATION_FOR_TXF_ATTRIBUTE = @as(u32, 512);
pub const QUERY_FILE_LAYOUT_INCLUDE_STREAM_INFORMATION_FOR_EFS_ATTRIBUTE = @as(u32, 1024);
pub const QUERY_FILE_LAYOUT_INCLUDE_ONLY_FILES_WITH_SPECIFIC_ATTRIBUTES = @as(u32, 2048);
pub const QUERY_FILE_LAYOUT_INCLUDE_FILES_WITH_DSC_ATTRIBUTE = @as(u32, 4096);
pub const QUERY_FILE_LAYOUT_INCLUDE_STREAM_INFORMATION_FOR_DATA_ATTRIBUTE = @as(u32, 8192);
pub const QUERY_FILE_LAYOUT_INCLUDE_STREAM_INFORMATION_FOR_REPARSE_ATTRIBUTE = @as(u32, 16384);
pub const QUERY_FILE_LAYOUT_INCLUDE_STREAM_INFORMATION_FOR_EA_ATTRIBUTE = @as(u32, 32768);
pub const QUERY_FILE_LAYOUT_SINGLE_INSTANCED = @as(u32, 1);
pub const FILE_LAYOUT_NAME_ENTRY_PRIMARY = @as(u32, 1);
pub const FILE_LAYOUT_NAME_ENTRY_DOS = @as(u32, 2);
pub const STREAM_LAYOUT_ENTRY_IMMOVABLE = @as(u32, 1);
pub const STREAM_LAYOUT_ENTRY_PINNED = @as(u32, 2);
pub const STREAM_LAYOUT_ENTRY_RESIDENT = @as(u32, 4);
pub const STREAM_LAYOUT_ENTRY_NO_CLUSTERS_ALLOCATED = @as(u32, 8);
pub const STREAM_LAYOUT_ENTRY_HAS_INFORMATION = @as(u32, 16);
pub const STREAM_EXTENT_ENTRY_AS_RETRIEVAL_POINTERS = @as(u32, 1);
pub const STREAM_EXTENT_ENTRY_ALL_EXTENTS = @as(u32, 2);
pub const CHECKSUM_TYPE_UNCHANGED = @as(i32, -1);
pub const CHECKSUM_TYPE_NONE = @as(u32, 0);
pub const CHECKSUM_TYPE_CRC32 = @as(u32, 1);
pub const CHECKSUM_TYPE_CRC64 = @as(u32, 2);
pub const CHECKSUM_TYPE_ECC = @as(u32, 3);
pub const CHECKSUM_TYPE_FIRST_UNUSED_TYPE = @as(u32, 4);
pub const FSCTL_INTEGRITY_FLAG_CHECKSUM_ENFORCEMENT_OFF = @as(u32, 1);
pub const OFFLOAD_READ_FLAG_ALL_ZERO_BEYOND_CURRENT_RANGE = @as(u32, 1);
pub const SET_PURGE_FAILURE_MODE_ENABLED = @as(u32, 1);
pub const SET_PURGE_FAILURE_MODE_DISABLED = @as(u32, 2);
pub const FILE_REGION_USAGE_VALID_CACHED_DATA = @as(u32, 1);
pub const FILE_REGION_USAGE_VALID_NONCACHED_DATA = @as(u32, 2);
pub const FILE_REGION_USAGE_OTHER_PAGE_ALIGNMENT = @as(u32, 4);
pub const FILE_REGION_USAGE_LARGE_PAGE_ALIGNMENT = @as(u32, 8);
pub const FILE_REGION_USAGE_HUGE_PAGE_ALIGNMENT = @as(u32, 16);
pub const FILE_STORAGE_TIER_NAME_LENGTH = @as(u32, 256);
pub const FILE_STORAGE_TIER_DESCRIPTION_LENGTH = @as(u32, 512);
pub const FILE_STORAGE_TIER_FLAG_WRITE_BACK_CACHE = @as(u32, 2097152);
pub const FILE_STORAGE_TIER_FLAG_READ_CACHE = @as(u32, 4194304);
pub const FILE_STORAGE_TIER_FLAG_PARITY = @as(u32, 8388608);
pub const FILE_STORAGE_TIER_FLAG_SMR = @as(u32, 16777216);
pub const QUERY_STORAGE_CLASSES_FLAGS_MEASURE_WRITE = @as(u32, 2147483648);
pub const QUERY_STORAGE_CLASSES_FLAGS_MEASURE_READ = @as(u32, 1073741824);
pub const QUERY_STORAGE_CLASSES_FLAGS_NO_DEFRAG_VOLUME = @as(u32, 536870912);
pub const QUERY_FILE_LAYOUT_REPARSE_DATA_INVALID = @as(u32, 1);
pub const QUERY_FILE_LAYOUT_REPARSE_TAG_INVALID = @as(u32, 2);
pub const DUPLICATE_EXTENTS_DATA_EX_SOURCE_ATOMIC = @as(u32, 1);
pub const DUPLICATE_EXTENTS_DATA_EX_ASYNC = @as(u32, 2);
pub const REFS_SMR_VOLUME_INFO_OUTPUT_VERSION_V1 = @as(u32, 1);
pub const REFS_SMR_VOLUME_GC_PARAMETERS_VERSION_V1 = @as(u32, 1);
pub const STREAMS_INVALID_ID = @as(u32, 0);
pub const STREAMS_ASSOCIATE_ID_CLEAR = @as(u32, 1);
pub const STREAMS_ASSOCIATE_ID_SET = @as(u32, 2);
pub const DAX_ALLOC_ALIGNMENT_FLAG_MANDATORY = @as(u32, 1);
pub const DAX_ALLOC_ALIGNMENT_FLAG_FALLBACK_SPECIFIED = @as(u32, 2);
pub const WOF_CURRENT_VERSION = @as(u32, 1);
pub const WOF_PROVIDER_WIM = @as(u32, 1);
pub const WOF_PROVIDER_FILE = @as(u32, 2);
pub const WOF_PROVIDER_CLOUD = @as(u32, 3);
pub const WIM_PROVIDER_HASH_SIZE = @as(u32, 20);
pub const WIM_PROVIDER_CURRENT_VERSION = @as(u32, 1);
pub const WIM_PROVIDER_EXTERNAL_FLAG_NOT_ACTIVE = @as(u32, 1);
pub const WIM_PROVIDER_EXTERNAL_FLAG_SUSPENDED = @as(u32, 2);
pub const WIM_BOOT_OS_WIM = @as(u32, 1);
pub const WIM_BOOT_NOT_OS_WIM = @as(u32, 0);
pub const FILE_PROVIDER_CURRENT_VERSION = @as(u32, 1);
pub const FILE_PROVIDER_SINGLE_FILE = @as(u32, 1);
pub const FILE_PROVIDER_COMPRESSION_XPRESS4K = @as(u32, 0);
pub const FILE_PROVIDER_COMPRESSION_LZX = @as(u32, 1);
pub const FILE_PROVIDER_COMPRESSION_XPRESS8K = @as(u32, 2);
pub const FILE_PROVIDER_COMPRESSION_XPRESS16K = @as(u32, 3);
pub const FILE_PROVIDER_COMPRESSION_MAXIMUM = @as(u32, 4);
pub const FILE_PROVIDER_FLAG_COMPRESS_ON_WRITE = @as(u32, 1);
pub const CONTAINER_VOLUME_STATE_HOSTING_CONTAINER = @as(u32, 1);
pub const CONTAINER_ROOT_INFO_FLAG_SCRATCH_ROOT = @as(u32, 1);
pub const CONTAINER_ROOT_INFO_FLAG_LAYER_ROOT = @as(u32, 2);
pub const CONTAINER_ROOT_INFO_FLAG_VIRTUALIZATION_ROOT = @as(u32, 4);
pub const CONTAINER_ROOT_INFO_FLAG_VIRTUALIZATION_TARGET_ROOT = @as(u32, 8);
pub const CONTAINER_ROOT_INFO_FLAG_VIRTUALIZATION_EXCEPTION_ROOT = @as(u32, 16);
pub const CONTAINER_ROOT_INFO_FLAG_BIND_ROOT = @as(u32, 32);
pub const CONTAINER_ROOT_INFO_FLAG_BIND_TARGET_ROOT = @as(u32, 64);
pub const CONTAINER_ROOT_INFO_FLAG_BIND_EXCEPTION_ROOT = @as(u32, 128);
pub const CONTAINER_ROOT_INFO_FLAG_BIND_DO_NOT_MAP_NAME = @as(u32, 256);
pub const CONTAINER_ROOT_INFO_VALID_FLAGS = @as(u32, 511);
pub const PROJFS_PROTOCOL_VERSION = @as(u32, 3);
pub const IOCTL_VOLUME_BASE = @as(u32, 86);
pub const IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS = @as(u32, 5636096);
pub const IOCTL_VOLUME_ONLINE = @as(u32, 5685256);
pub const IOCTL_VOLUME_OFFLINE = @as(u32, 5685260);
pub const IOCTL_VOLUME_IS_CLUSTERED = @as(u32, 5636144);
pub const IOCTL_VOLUME_GET_GPT_ATTRIBUTES = @as(u32, 5636152);
pub const EFS_TRACKED_OFFSET_HEADER_FLAG = @as(u32, 1);
pub const SPACES_TRACKED_OFFSET_HEADER_FLAG = @as(u32, 2);
pub const ROTFLAGS_REGISTRATIONKEEPSALIVE = @as(u32, 1);
pub const ROTFLAGS_ALLOWANYCLIENT = @as(u32, 2);
pub const ROT_COMPARE_MAX = @as(u32, 2048);
pub const WDT_INPROC_CALL = @as(u32, 1215587415);
pub const WDT_REMOTE_CALL = @as(u32, 1383359575);
pub const WDT_INPROC64_CALL = @as(u32, 1349805143);
pub const TIME_ONESHOT = @as(u32, 0);
pub const TIME_PERIODIC = @as(u32, 1);
pub const TIME_CALLBACK_FUNCTION = @as(u32, 0);
pub const TIME_CALLBACK_EVENT_SET = @as(u32, 16);
pub const TIME_CALLBACK_EVENT_PULSE = @as(u32, 32);
pub const TIME_KILL_SYNCHRONOUS = @as(u32, 256);
pub const PROCESS_HEAP_REGION = @as(u32, 1);
pub const PROCESS_HEAP_UNCOMMITTED_RANGE = @as(u32, 2);
pub const PROCESS_HEAP_ENTRY_BUSY = @as(u32, 4);
pub const PROCESS_HEAP_SEG_ALLOC = @as(u32, 8);
pub const PROCESS_HEAP_ENTRY_MOVEABLE = @as(u32, 16);
pub const PROCESS_HEAP_ENTRY_DDESHARE = @as(u32, 32);
pub const LMEM_NOCOMPACT = @as(u32, 16);
pub const LMEM_NODISCARD = @as(u32, 32);
pub const LMEM_MODIFY = @as(u32, 128);
pub const LMEM_DISCARDABLE = @as(u32, 3840);
pub const LMEM_VALID_FLAGS = @as(u32, 3954);
pub const LMEM_INVALID_HANDLE = @as(u32, 32768);
pub const LMEM_DISCARDED = @as(u32, 16384);
pub const LMEM_LOCKCOUNT = @as(u32, 255);
pub const NUMA_NO_PREFERRED_NODE = @as(u32, 4294967295);
pub const REDBOOK_DIGITAL_AUDIO_EXTRACTION_INFO_VERSION = @as(u32, 1);
//--------------------------------------------------------------------------------
// Section: Types (968)
//--------------------------------------------------------------------------------
pub const ALERT_SYSTEM_SEV = enum(u32) {
INFORMATIONAL = 1,
WARNING = 2,
ERROR = 3,
QUERY = 4,
CRITICAL = 5,
};
pub const ALERT_SYSTEM_INFORMATIONAL = ALERT_SYSTEM_SEV.INFORMATIONAL;
pub const ALERT_SYSTEM_WARNING = ALERT_SYSTEM_SEV.WARNING;
pub const ALERT_SYSTEM_ERROR = ALERT_SYSTEM_SEV.ERROR;
pub const ALERT_SYSTEM_QUERY = ALERT_SYSTEM_SEV.QUERY;
pub const ALERT_SYSTEM_CRITICAL = ALERT_SYSTEM_SEV.CRITICAL;
pub const APPCOMMAND_ID = enum(u32) {
BROWSER_BACKWARD = 1,
BROWSER_FORWARD = 2,
BROWSER_REFRESH = 3,
BROWSER_STOP = 4,
BROWSER_SEARCH = 5,
BROWSER_FAVORITES = 6,
BROWSER_HOME = 7,
VOLUME_MUTE = 8,
VOLUME_DOWN = 9,
VOLUME_UP = 10,
MEDIA_NEXTTRACK = 11,
MEDIA_PREVIOUSTRACK = 12,
MEDIA_STOP = 13,
MEDIA_PLAY_PAUSE = 14,
LAUNCH_MAIL = 15,
LAUNCH_MEDIA_SELECT = 16,
LAUNCH_APP1 = 17,
LAUNCH_APP2 = 18,
BASS_DOWN = 19,
BASS_BOOST = 20,
BASS_UP = 21,
TREBLE_DOWN = 22,
TREBLE_UP = 23,
MICROPHONE_VOLUME_MUTE = 24,
MICROPHONE_VOLUME_DOWN = 25,
MICROPHONE_VOLUME_UP = 26,
HELP = 27,
FIND = 28,
NEW = 29,
OPEN = 30,
CLOSE = 31,
SAVE = 32,
PRINT = 33,
UNDO = 34,
REDO = 35,
COPY = 36,
CUT = 37,
PASTE = 38,
REPLY_TO_MAIL = 39,
FORWARD_MAIL = 40,
SEND_MAIL = 41,
SPELL_CHECK = 42,
DICTATE_OR_COMMAND_CONTROL_TOGGLE = 43,
MIC_ON_OFF_TOGGLE = 44,
CORRECTION_LIST = 45,
MEDIA_PLAY = 46,
MEDIA_PAUSE = 47,
MEDIA_RECORD = 48,
MEDIA_FAST_FORWARD = 49,
MEDIA_REWIND = 50,
MEDIA_CHANNEL_UP = 51,
MEDIA_CHANNEL_DOWN = 52,
DELETE = 53,
DWM_FLIP3D = 54,
};
pub const APPCOMMAND_BROWSER_BACKWARD = APPCOMMAND_ID.BROWSER_BACKWARD;
pub const APPCOMMAND_BROWSER_FORWARD = APPCOMMAND_ID.BROWSER_FORWARD;
pub const APPCOMMAND_BROWSER_REFRESH = APPCOMMAND_ID.BROWSER_REFRESH;
pub const APPCOMMAND_BROWSER_STOP = APPCOMMAND_ID.BROWSER_STOP;
pub const APPCOMMAND_BROWSER_SEARCH = APPCOMMAND_ID.BROWSER_SEARCH;
pub const APPCOMMAND_BROWSER_FAVORITES = APPCOMMAND_ID.BROWSER_FAVORITES;
pub const APPCOMMAND_BROWSER_HOME = APPCOMMAND_ID.BROWSER_HOME;
pub const APPCOMMAND_VOLUME_MUTE = APPCOMMAND_ID.VOLUME_MUTE;
pub const APPCOMMAND_VOLUME_DOWN = APPCOMMAND_ID.VOLUME_DOWN;
pub const APPCOMMAND_VOLUME_UP = APPCOMMAND_ID.VOLUME_UP;
pub const APPCOMMAND_MEDIA_NEXTTRACK = APPCOMMAND_ID.MEDIA_NEXTTRACK;
pub const APPCOMMAND_MEDIA_PREVIOUSTRACK = APPCOMMAND_ID.MEDIA_PREVIOUSTRACK;
pub const APPCOMMAND_MEDIA_STOP = APPCOMMAND_ID.MEDIA_STOP;
pub const APPCOMMAND_MEDIA_PLAY_PAUSE = APPCOMMAND_ID.MEDIA_PLAY_PAUSE;
pub const APPCOMMAND_LAUNCH_MAIL = APPCOMMAND_ID.LAUNCH_MAIL;
pub const APPCOMMAND_LAUNCH_MEDIA_SELECT = APPCOMMAND_ID.LAUNCH_MEDIA_SELECT;
pub const APPCOMMAND_LAUNCH_APP1 = APPCOMMAND_ID.LAUNCH_APP1;
pub const APPCOMMAND_LAUNCH_APP2 = APPCOMMAND_ID.LAUNCH_APP2;
pub const APPCOMMAND_BASS_DOWN = APPCOMMAND_ID.BASS_DOWN;
pub const APPCOMMAND_BASS_BOOST = APPCOMMAND_ID.BASS_BOOST;
pub const APPCOMMAND_BASS_UP = APPCOMMAND_ID.BASS_UP;
pub const APPCOMMAND_TREBLE_DOWN = APPCOMMAND_ID.TREBLE_DOWN;
pub const APPCOMMAND_TREBLE_UP = APPCOMMAND_ID.TREBLE_UP;
pub const APPCOMMAND_MICROPHONE_VOLUME_MUTE = APPCOMMAND_ID.MICROPHONE_VOLUME_MUTE;
pub const APPCOMMAND_MICROPHONE_VOLUME_DOWN = APPCOMMAND_ID.MICROPHONE_VOLUME_DOWN;
pub const APPCOMMAND_MICROPHONE_VOLUME_UP = APPCOMMAND_ID.MICROPHONE_VOLUME_UP;
pub const APPCOMMAND_HELP = APPCOMMAND_ID.HELP;
pub const APPCOMMAND_FIND = APPCOMMAND_ID.FIND;
pub const APPCOMMAND_NEW = APPCOMMAND_ID.NEW;
pub const APPCOMMAND_OPEN = APPCOMMAND_ID.OPEN;
pub const APPCOMMAND_CLOSE = APPCOMMAND_ID.CLOSE;
pub const APPCOMMAND_SAVE = APPCOMMAND_ID.SAVE;
pub const APPCOMMAND_PRINT = APPCOMMAND_ID.PRINT;
pub const APPCOMMAND_UNDO = APPCOMMAND_ID.UNDO;
pub const APPCOMMAND_REDO = APPCOMMAND_ID.REDO;
pub const APPCOMMAND_COPY = APPCOMMAND_ID.COPY;
pub const APPCOMMAND_CUT = APPCOMMAND_ID.CUT;
pub const APPCOMMAND_PASTE = APPCOMMAND_ID.PASTE;
pub const APPCOMMAND_REPLY_TO_MAIL = APPCOMMAND_ID.REPLY_TO_MAIL;
pub const APPCOMMAND_FORWARD_MAIL = APPCOMMAND_ID.FORWARD_MAIL;
pub const APPCOMMAND_SEND_MAIL = APPCOMMAND_ID.SEND_MAIL;
pub const APPCOMMAND_SPELL_CHECK = APPCOMMAND_ID.SPELL_CHECK;
pub const APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE = APPCOMMAND_ID.DICTATE_OR_COMMAND_CONTROL_TOGGLE;
pub const APPCOMMAND_MIC_ON_OFF_TOGGLE = APPCOMMAND_ID.MIC_ON_OFF_TOGGLE;
pub const APPCOMMAND_CORRECTION_LIST = APPCOMMAND_ID.CORRECTION_LIST;
pub const APPCOMMAND_MEDIA_PLAY = APPCOMMAND_ID.MEDIA_PLAY;
pub const APPCOMMAND_MEDIA_PAUSE = APPCOMMAND_ID.MEDIA_PAUSE;
pub const APPCOMMAND_MEDIA_RECORD = APPCOMMAND_ID.MEDIA_RECORD;
pub const APPCOMMAND_MEDIA_FAST_FORWARD = APPCOMMAND_ID.MEDIA_FAST_FORWARD;
pub const APPCOMMAND_MEDIA_REWIND = APPCOMMAND_ID.MEDIA_REWIND;
pub const APPCOMMAND_MEDIA_CHANNEL_UP = APPCOMMAND_ID.MEDIA_CHANNEL_UP;
pub const APPCOMMAND_MEDIA_CHANNEL_DOWN = APPCOMMAND_ID.MEDIA_CHANNEL_DOWN;
pub const APPCOMMAND_DELETE = APPCOMMAND_ID.DELETE;
pub const APPCOMMAND_DWM_FLIP3D = APPCOMMAND_ID.DWM_FLIP3D;
pub const ATF_FLAGS = enum(u32) {
TIMEOUTON = 1,
ONOFFFEEDBACK = 2,
_,
pub fn initFlags(o: struct {
TIMEOUTON: u1 = 0,
ONOFFFEEDBACK: u1 = 0,
}) ATF_FLAGS {
return @intToEnum(ATF_FLAGS,
(if (o.TIMEOUTON == 1) @enumToInt(ATF_FLAGS.TIMEOUTON) else 0)
| (if (o.ONOFFFEEDBACK == 1) @enumToInt(ATF_FLAGS.ONOFFFEEDBACK) else 0)
);
}
};
pub const ATF_TIMEOUTON = ATF_FLAGS.TIMEOUTON;
pub const ATF_ONOFFFEEDBACK = ATF_FLAGS.ONOFFFEEDBACK;
pub const CHOOSECOLOR_FLAGS = enum(u32) {
RGBINIT = 1,
FULLOPEN = 2,
PREVENTFULLOPEN = 4,
SHOWHELP = 8,
ENABLEHOOK = 16,
ENABLETEMPLATE = 32,
ENABLETEMPLATEHANDLE = 64,
SOLIDCOLOR = 128,
ANYCOLOR = 256,
_,
pub fn initFlags(o: struct {
RGBINIT: u1 = 0,
FULLOPEN: u1 = 0,
PREVENTFULLOPEN: u1 = 0,
SHOWHELP: u1 = 0,
ENABLEHOOK: u1 = 0,
ENABLETEMPLATE: u1 = 0,
ENABLETEMPLATEHANDLE: u1 = 0,
SOLIDCOLOR: u1 = 0,
ANYCOLOR: u1 = 0,
}) CHOOSECOLOR_FLAGS {
return @intToEnum(CHOOSECOLOR_FLAGS,
(if (o.RGBINIT == 1) @enumToInt(CHOOSECOLOR_FLAGS.RGBINIT) else 0)
| (if (o.FULLOPEN == 1) @enumToInt(CHOOSECOLOR_FLAGS.FULLOPEN) else 0)
| (if (o.PREVENTFULLOPEN == 1) @enumToInt(CHOOSECOLOR_FLAGS.PREVENTFULLOPEN) else 0)
| (if (o.SHOWHELP == 1) @enumToInt(CHOOSECOLOR_FLAGS.SHOWHELP) else 0)
| (if (o.ENABLEHOOK == 1) @enumToInt(CHOOSECOLOR_FLAGS.ENABLEHOOK) else 0)
| (if (o.ENABLETEMPLATE == 1) @enumToInt(CHOOSECOLOR_FLAGS.ENABLETEMPLATE) else 0)
| (if (o.ENABLETEMPLATEHANDLE == 1) @enumToInt(CHOOSECOLOR_FLAGS.ENABLETEMPLATEHANDLE) else 0)
| (if (o.SOLIDCOLOR == 1) @enumToInt(CHOOSECOLOR_FLAGS.SOLIDCOLOR) else 0)
| (if (o.ANYCOLOR == 1) @enumToInt(CHOOSECOLOR_FLAGS.ANYCOLOR) else 0)
);
}
};
pub const CC_RGBINIT = CHOOSECOLOR_FLAGS.RGBINIT;
pub const CC_FULLOPEN = CHOOSECOLOR_FLAGS.FULLOPEN;
pub const CC_PREVENTFULLOPEN = CHOOSECOLOR_FLAGS.PREVENTFULLOPEN;
pub const CC_SHOWHELP = CHOOSECOLOR_FLAGS.SHOWHELP;
pub const CC_ENABLEHOOK = CHOOSECOLOR_FLAGS.ENABLEHOOK;
pub const CC_ENABLETEMPLATE = CHOOSECOLOR_FLAGS.ENABLETEMPLATE;
pub const CC_ENABLETEMPLATEHANDLE = CHOOSECOLOR_FLAGS.ENABLETEMPLATEHANDLE;
pub const CC_SOLIDCOLOR = CHOOSECOLOR_FLAGS.SOLIDCOLOR;
pub const CC_ANYCOLOR = CHOOSECOLOR_FLAGS.ANYCOLOR;
pub const CLIPBOARD_FORMATS = enum(u32) {
TEXT = 1,
BITMAP = 2,
METAFILEPICT = 3,
SYLK = 4,
DIF = 5,
TIFF = 6,
OEMTEXT = 7,
DIB = 8,
PALETTE = 9,
PENDATA = 10,
RIFF = 11,
WAVE = 12,
UNICODETEXT = 13,
ENHMETAFILE = 14,
HDROP = 15,
LOCALE = 16,
DIBV5 = 17,
MAX = 18,
OWNERDISPLAY = 128,
DSPTEXT = 129,
DSPBITMAP = 130,
DSPMETAFILEPICT = 131,
DSPENHMETAFILE = 142,
PRIVATEFIRST = 512,
PRIVATELAST = 767,
GDIOBJFIRST = 768,
GDIOBJLAST = 1023,
};
pub const CF_TEXT = CLIPBOARD_FORMATS.TEXT;
pub const CF_BITMAP = CLIPBOARD_FORMATS.BITMAP;
pub const CF_METAFILEPICT = CLIPBOARD_FORMATS.METAFILEPICT;
pub const CF_SYLK = CLIPBOARD_FORMATS.SYLK;
pub const CF_DIF = CLIPBOARD_FORMATS.DIF;
pub const CF_TIFF = CLIPBOARD_FORMATS.TIFF;
pub const CF_OEMTEXT = CLIPBOARD_FORMATS.OEMTEXT;
pub const CF_DIB = CLIPBOARD_FORMATS.DIB;
pub const CF_PALETTE = CLIPBOARD_FORMATS.PALETTE;
pub const CF_PENDATA = CLIPBOARD_FORMATS.PENDATA;
pub const CF_RIFF = CLIPBOARD_FORMATS.RIFF;
pub const CF_WAVE = CLIPBOARD_FORMATS.WAVE;
pub const CF_UNICODETEXT = CLIPBOARD_FORMATS.UNICODETEXT;
pub const CF_ENHMETAFILE = CLIPBOARD_FORMATS.ENHMETAFILE;
pub const CF_HDROP = CLIPBOARD_FORMATS.HDROP;
pub const CF_LOCALE = CLIPBOARD_FORMATS.LOCALE;
pub const CF_DIBV5 = CLIPBOARD_FORMATS.DIBV5;
pub const CF_MAX = CLIPBOARD_FORMATS.MAX;
pub const CF_OWNERDISPLAY = CLIPBOARD_FORMATS.OWNERDISPLAY;
pub const CF_DSPTEXT = CLIPBOARD_FORMATS.DSPTEXT;
pub const CF_DSPBITMAP = CLIPBOARD_FORMATS.DSPBITMAP;
pub const CF_DSPMETAFILEPICT = CLIPBOARD_FORMATS.DSPMETAFILEPICT;
pub const CF_DSPENHMETAFILE = CLIPBOARD_FORMATS.DSPENHMETAFILE;
pub const CF_PRIVATEFIRST = CLIPBOARD_FORMATS.PRIVATEFIRST;
pub const CF_PRIVATELAST = CLIPBOARD_FORMATS.PRIVATELAST;
pub const CF_GDIOBJFIRST = CLIPBOARD_FORMATS.GDIOBJFIRST;
pub const CF_GDIOBJLAST = CLIPBOARD_FORMATS.GDIOBJLAST;
pub const GESTURECONFIG_FLAGS = enum(u32) {
ALLGESTURES = 1,
// ZOOM = 1, this enum value conflicts with ALLGESTURES
// PAN = 1, this enum value conflicts with ALLGESTURES
PAN_WITH_SINGLE_FINGER_VERTICALLY = 2,
PAN_WITH_SINGLE_FINGER_HORIZONTALLY = 4,
PAN_WITH_GUTTER = 8,
PAN_WITH_INERTIA = 16,
// ROTATE = 1, this enum value conflicts with ALLGESTURES
// TWOFINGERTAP = 1, this enum value conflicts with ALLGESTURES
// PRESSANDTAP = 1, this enum value conflicts with ALLGESTURES
// ROLLOVER = 1, this enum value conflicts with ALLGESTURES
_,
pub fn initFlags(o: struct {
ALLGESTURES: u1 = 0,
PAN_WITH_SINGLE_FINGER_VERTICALLY: u1 = 0,
PAN_WITH_SINGLE_FINGER_HORIZONTALLY: u1 = 0,
PAN_WITH_GUTTER: u1 = 0,
PAN_WITH_INERTIA: u1 = 0,
}) GESTURECONFIG_FLAGS {
return @intToEnum(GESTURECONFIG_FLAGS,
(if (o.ALLGESTURES == 1) @enumToInt(GESTURECONFIG_FLAGS.ALLGESTURES) else 0)
| (if (o.PAN_WITH_SINGLE_FINGER_VERTICALLY == 1) @enumToInt(GESTURECONFIG_FLAGS.PAN_WITH_SINGLE_FINGER_VERTICALLY) else 0)
| (if (o.PAN_WITH_SINGLE_FINGER_HORIZONTALLY == 1) @enumToInt(GESTURECONFIG_FLAGS.PAN_WITH_SINGLE_FINGER_HORIZONTALLY) else 0)
| (if (o.PAN_WITH_GUTTER == 1) @enumToInt(GESTURECONFIG_FLAGS.PAN_WITH_GUTTER) else 0)
| (if (o.PAN_WITH_INERTIA == 1) @enumToInt(GESTURECONFIG_FLAGS.PAN_WITH_INERTIA) else 0)
);
}
};
pub const GC_ALLGESTURES = GESTURECONFIG_FLAGS.ALLGESTURES;
pub const GC_ZOOM = GESTURECONFIG_FLAGS.ALLGESTURES;
pub const GC_PAN = GESTURECONFIG_FLAGS.ALLGESTURES;
pub const GC_PAN_WITH_SINGLE_FINGER_VERTICALLY = GESTURECONFIG_FLAGS.PAN_WITH_SINGLE_FINGER_VERTICALLY;
pub const GC_PAN_WITH_SINGLE_FINGER_HORIZONTALLY = GESTURECONFIG_FLAGS.PAN_WITH_SINGLE_FINGER_HORIZONTALLY;
pub const GC_PAN_WITH_GUTTER = GESTURECONFIG_FLAGS.PAN_WITH_GUTTER;
pub const GC_PAN_WITH_INERTIA = GESTURECONFIG_FLAGS.PAN_WITH_INERTIA;
pub const GC_ROTATE = GESTURECONFIG_FLAGS.ALLGESTURES;
pub const GC_TWOFINGERTAP = GESTURECONFIG_FLAGS.ALLGESTURES;
pub const GC_PRESSANDTAP = GESTURECONFIG_FLAGS.ALLGESTURES;
pub const GC_ROLLOVER = GESTURECONFIG_FLAGS.ALLGESTURES;
pub const CFE_UNDERLINE = enum(u32) {
CF1UNDERLINE = 255,
INVERT = 254,
UNDERLINETHICKLONGDASH = 18,
UNDERLINETHICKDOTTED = 17,
UNDERLINETHICKDASHDOTDOT = 16,
UNDERLINETHICKDASHDOT = 15,
UNDERLINETHICKDASH = 14,
UNDERLINELONGDASH = 13,
UNDERLINEHEAVYWAVE = 12,
UNDERLINEDOUBLEWAVE = 11,
UNDERLINEHAIRLINE = 10,
UNDERLINETHICK = 9,
UNDERLINEWAVE = 8,
UNDERLINEDASHDOTDOT = 7,
UNDERLINEDASHDOT = 6,
UNDERLINEDASH = 5,
UNDERLINEDOTTED = 4,
UNDERLINEDOUBLE = 3,
UNDERLINEWORD = 2,
UNDERLINE = 1,
UNDERLINENONE = 0,
_,
pub fn initFlags(o: struct {
CF1UNDERLINE: u1 = 0,
INVERT: u1 = 0,
UNDERLINETHICKLONGDASH: u1 = 0,
UNDERLINETHICKDOTTED: u1 = 0,
UNDERLINETHICKDASHDOTDOT: u1 = 0,
UNDERLINETHICKDASHDOT: u1 = 0,
UNDERLINETHICKDASH: u1 = 0,
UNDERLINELONGDASH: u1 = 0,
UNDERLINEHEAVYWAVE: u1 = 0,
UNDERLINEDOUBLEWAVE: u1 = 0,
UNDERLINEHAIRLINE: u1 = 0,
UNDERLINETHICK: u1 = 0,
UNDERLINEWAVE: u1 = 0,
UNDERLINEDASHDOTDOT: u1 = 0,
UNDERLINEDASHDOT: u1 = 0,
UNDERLINEDASH: u1 = 0,
UNDERLINEDOTTED: u1 = 0,
UNDERLINEDOUBLE: u1 = 0,
UNDERLINEWORD: u1 = 0,
UNDERLINE: u1 = 0,
UNDERLINENONE: u1 = 0,
}) CFE_UNDERLINE {
return @intToEnum(CFE_UNDERLINE,
(if (o.CF1UNDERLINE == 1) @enumToInt(CFE_UNDERLINE.CF1UNDERLINE) else 0)
| (if (o.INVERT == 1) @enumToInt(CFE_UNDERLINE.INVERT) else 0)
| (if (o.UNDERLINETHICKLONGDASH == 1) @enumToInt(CFE_UNDERLINE.UNDERLINETHICKLONGDASH) else 0)
| (if (o.UNDERLINETHICKDOTTED == 1) @enumToInt(CFE_UNDERLINE.UNDERLINETHICKDOTTED) else 0)
| (if (o.UNDERLINETHICKDASHDOTDOT == 1) @enumToInt(CFE_UNDERLINE.UNDERLINETHICKDASHDOTDOT) else 0)
| (if (o.UNDERLINETHICKDASHDOT == 1) @enumToInt(CFE_UNDERLINE.UNDERLINETHICKDASHDOT) else 0)
| (if (o.UNDERLINETHICKDASH == 1) @enumToInt(CFE_UNDERLINE.UNDERLINETHICKDASH) else 0)
| (if (o.UNDERLINELONGDASH == 1) @enumToInt(CFE_UNDERLINE.UNDERLINELONGDASH) else 0)
| (if (o.UNDERLINEHEAVYWAVE == 1) @enumToInt(CFE_UNDERLINE.UNDERLINEHEAVYWAVE) else 0)
| (if (o.UNDERLINEDOUBLEWAVE == 1) @enumToInt(CFE_UNDERLINE.UNDERLINEDOUBLEWAVE) else 0)
| (if (o.UNDERLINEHAIRLINE == 1) @enumToInt(CFE_UNDERLINE.UNDERLINEHAIRLINE) else 0)
| (if (o.UNDERLINETHICK == 1) @enumToInt(CFE_UNDERLINE.UNDERLINETHICK) else 0)
| (if (o.UNDERLINEWAVE == 1) @enumToInt(CFE_UNDERLINE.UNDERLINEWAVE) else 0)
| (if (o.UNDERLINEDASHDOTDOT == 1) @enumToInt(CFE_UNDERLINE.UNDERLINEDASHDOTDOT) else 0)
| (if (o.UNDERLINEDASHDOT == 1) @enumToInt(CFE_UNDERLINE.UNDERLINEDASHDOT) else 0)
| (if (o.UNDERLINEDASH == 1) @enumToInt(CFE_UNDERLINE.UNDERLINEDASH) else 0)
| (if (o.UNDERLINEDOTTED == 1) @enumToInt(CFE_UNDERLINE.UNDERLINEDOTTED) else 0)
| (if (o.UNDERLINEDOUBLE == 1) @enumToInt(CFE_UNDERLINE.UNDERLINEDOUBLE) else 0)
| (if (o.UNDERLINEWORD == 1) @enumToInt(CFE_UNDERLINE.UNDERLINEWORD) else 0)
| (if (o.UNDERLINE == 1) @enumToInt(CFE_UNDERLINE.UNDERLINE) else 0)
| (if (o.UNDERLINENONE == 1) @enumToInt(CFE_UNDERLINE.UNDERLINENONE) else 0)
);
}
};
pub const CFU_CF1UNDERLINE = CFE_UNDERLINE.CF1UNDERLINE;
pub const CFU_INVERT = CFE_UNDERLINE.INVERT;
pub const CFU_UNDERLINETHICKLONGDASH = CFE_UNDERLINE.UNDERLINETHICKLONGDASH;
pub const CFU_UNDERLINETHICKDOTTED = CFE_UNDERLINE.UNDERLINETHICKDOTTED;
pub const CFU_UNDERLINETHICKDASHDOTDOT = CFE_UNDERLINE.UNDERLINETHICKDASHDOTDOT;
pub const CFU_UNDERLINETHICKDASHDOT = CFE_UNDERLINE.UNDERLINETHICKDASHDOT;
pub const CFU_UNDERLINETHICKDASH = CFE_UNDERLINE.UNDERLINETHICKDASH;
pub const CFU_UNDERLINELONGDASH = CFE_UNDERLINE.UNDERLINELONGDASH;
pub const CFU_UNDERLINEHEAVYWAVE = CFE_UNDERLINE.UNDERLINEHEAVYWAVE;
pub const CFU_UNDERLINEDOUBLEWAVE = CFE_UNDERLINE.UNDERLINEDOUBLEWAVE;
pub const CFU_UNDERLINEHAIRLINE = CFE_UNDERLINE.UNDERLINEHAIRLINE;
pub const CFU_UNDERLINETHICK = CFE_UNDERLINE.UNDERLINETHICK;
pub const CFU_UNDERLINEWAVE = CFE_UNDERLINE.UNDERLINEWAVE;
pub const CFU_UNDERLINEDASHDOTDOT = CFE_UNDERLINE.UNDERLINEDASHDOTDOT;
pub const CFU_UNDERLINEDASHDOT = CFE_UNDERLINE.UNDERLINEDASHDOT;
pub const CFU_UNDERLINEDASH = CFE_UNDERLINE.UNDERLINEDASH;
pub const CFU_UNDERLINEDOTTED = CFE_UNDERLINE.UNDERLINEDOTTED;
pub const CFU_UNDERLINEDOUBLE = CFE_UNDERLINE.UNDERLINEDOUBLE;
pub const CFU_UNDERLINEWORD = CFE_UNDERLINE.UNDERLINEWORD;
pub const CFU_UNDERLINE = CFE_UNDERLINE.UNDERLINE;
pub const CFU_UNDERLINENONE = CFE_UNDERLINE.UNDERLINENONE;
pub const IGP_ID = enum(u32) {
GETIMEVERSION = 4294967292,
PROPERTY = 4,
CONVERSION = 8,
SENTENCE = 12,
UI = 16,
SETCOMPSTR = 20,
SELECT = 24,
};
pub const IGP_GETIMEVERSION = IGP_ID.GETIMEVERSION;
pub const IGP_PROPERTY = IGP_ID.PROPERTY;
pub const IGP_CONVERSION = IGP_ID.CONVERSION;
pub const IGP_SENTENCE = IGP_ID.SENTENCE;
pub const IGP_UI = IGP_ID.UI;
pub const IGP_SETCOMPSTR = IGP_ID.SETCOMPSTR;
pub const IGP_SELECT = IGP_ID.SELECT;
pub const SECTION_FLAGS = enum(u32) {
ALL_ACCESS = 983071,
QUERY = 1,
MAP_WRITE = 2,
MAP_READ = 4,
MAP_EXECUTE = 8,
EXTEND_SIZE = 16,
MAP_EXECUTE_EXPLICIT = 32,
_,
pub fn initFlags(o: struct {
ALL_ACCESS: u1 = 0,
QUERY: u1 = 0,
MAP_WRITE: u1 = 0,
MAP_READ: u1 = 0,
MAP_EXECUTE: u1 = 0,
EXTEND_SIZE: u1 = 0,
MAP_EXECUTE_EXPLICIT: u1 = 0,
}) SECTION_FLAGS {
return @intToEnum(SECTION_FLAGS,
(if (o.ALL_ACCESS == 1) @enumToInt(SECTION_FLAGS.ALL_ACCESS) else 0)
| (if (o.QUERY == 1) @enumToInt(SECTION_FLAGS.QUERY) else 0)
| (if (o.MAP_WRITE == 1) @enumToInt(SECTION_FLAGS.MAP_WRITE) else 0)
| (if (o.MAP_READ == 1) @enumToInt(SECTION_FLAGS.MAP_READ) else 0)
| (if (o.MAP_EXECUTE == 1) @enumToInt(SECTION_FLAGS.MAP_EXECUTE) else 0)
| (if (o.EXTEND_SIZE == 1) @enumToInt(SECTION_FLAGS.EXTEND_SIZE) else 0)
| (if (o.MAP_EXECUTE_EXPLICIT == 1) @enumToInt(SECTION_FLAGS.MAP_EXECUTE_EXPLICIT) else 0)
);
}
};
pub const SECTION_ALL_ACCESS = SECTION_FLAGS.ALL_ACCESS;
pub const SECTION_QUERY = SECTION_FLAGS.QUERY;
pub const SECTION_MAP_WRITE = SECTION_FLAGS.MAP_WRITE;
pub const SECTION_MAP_READ = SECTION_FLAGS.MAP_READ;
pub const SECTION_MAP_EXECUTE = SECTION_FLAGS.MAP_EXECUTE;
pub const SECTION_EXTEND_SIZE = SECTION_FLAGS.EXTEND_SIZE;
pub const SECTION_MAP_EXECUTE_EXPLICIT = SECTION_FLAGS.MAP_EXECUTE_EXPLICIT;
pub const JOB_OBJECT_CPU_RATE_CONTROL = enum(u32) {
CPU_RATE_CONTROL_ENABLE = 1,
CPU_RATE_CONTROL_WEIGHT_BASED = 2,
CPU_RATE_CONTROL_HARD_CAP = 4,
CPU_RATE_CONTROL_NOTIFY = 8,
_CPU_RATE_CONTROL_MIN_MAX_RATE = 16,
};
pub const JOB_OBJECT_CPU_RATE_CONTROL_ENABLE = JOB_OBJECT_CPU_RATE_CONTROL.CPU_RATE_CONTROL_ENABLE;
pub const JOB_OBJECT_CPU_RATE_CONTROL_WEIGHT_BASED = JOB_OBJECT_CPU_RATE_CONTROL.CPU_RATE_CONTROL_WEIGHT_BASED;
pub const JOB_OBJECT_CPU_RATE_CONTROL_HARD_CAP = JOB_OBJECT_CPU_RATE_CONTROL.CPU_RATE_CONTROL_HARD_CAP;
pub const JOB_OBJECT_CPU_RATE_CONTROL_NOTIFY = JOB_OBJECT_CPU_RATE_CONTROL.CPU_RATE_CONTROL_NOTIFY;
pub const JOB_OBJECT__CPU_RATE_CONTROL_MIN_MAX_RATE = JOB_OBJECT_CPU_RATE_CONTROL._CPU_RATE_CONTROL_MIN_MAX_RATE;
pub const CHANGER_FEATURES = enum(u32) {
BAR_CODE_SCANNER_INSTALLED = 1,
CARTRIDGE_MAGAZINE = 256,
CLEANER_ACCESS_NOT_VALID = 262144,
CLEANER_SLOT = 64,
CLOSE_IEPORT = 4,
DEVICE_REINITIALIZE_CAPABLE = 134217728,
DRIVE_CLEANING_REQUIRED = 65536,
DRIVE_EMPTY_ON_DOOR_ACCESS = 536870912,
EXCHANGE_MEDIA = 32,
INIT_ELEM_STAT_WITH_RANGE = 2,
KEYPAD_ENABLE_DISABLE = 268435456,
LOCK_UNLOCK = 128,
MEDIUM_FLIP = 512,
OPEN_IEPORT = 8,
POSITION_TO_ELEMENT = 1024,
PREDISMOUNT_EJECT_REQUIRED = 131072,
PREMOUNT_EJECT_REQUIRED = 524288,
REPORT_IEPORT_STATE = 2048,
SERIAL_NUMBER_VALID = 67108864,
STATUS_NON_VOLATILE = 16,
STORAGE_DRIVE = 4096,
STORAGE_IEPORT = 8192,
STORAGE_SLOT = 16384,
STORAGE_TRANSPORT = 32768,
VOLUME_ASSERT = 4194304,
VOLUME_IDENTIFICATION = 1048576,
VOLUME_REPLACE = 8388608,
VOLUME_SEARCH = 2097152,
VOLUME_UNDEFINE = 16777216,
_,
pub fn initFlags(o: struct {
BAR_CODE_SCANNER_INSTALLED: u1 = 0,
CARTRIDGE_MAGAZINE: u1 = 0,
CLEANER_ACCESS_NOT_VALID: u1 = 0,
CLEANER_SLOT: u1 = 0,
CLOSE_IEPORT: u1 = 0,
DEVICE_REINITIALIZE_CAPABLE: u1 = 0,
DRIVE_CLEANING_REQUIRED: u1 = 0,
DRIVE_EMPTY_ON_DOOR_ACCESS: u1 = 0,
EXCHANGE_MEDIA: u1 = 0,
INIT_ELEM_STAT_WITH_RANGE: u1 = 0,
KEYPAD_ENABLE_DISABLE: u1 = 0,
LOCK_UNLOCK: u1 = 0,
MEDIUM_FLIP: u1 = 0,
OPEN_IEPORT: u1 = 0,
POSITION_TO_ELEMENT: u1 = 0,
PREDISMOUNT_EJECT_REQUIRED: u1 = 0,
PREMOUNT_EJECT_REQUIRED: u1 = 0,
REPORT_IEPORT_STATE: u1 = 0,
SERIAL_NUMBER_VALID: u1 = 0,
STATUS_NON_VOLATILE: u1 = 0,
STORAGE_DRIVE: u1 = 0,
STORAGE_IEPORT: u1 = 0,
STORAGE_SLOT: u1 = 0,
STORAGE_TRANSPORT: u1 = 0,
VOLUME_ASSERT: u1 = 0,
VOLUME_IDENTIFICATION: u1 = 0,
VOLUME_REPLACE: u1 = 0,
VOLUME_SEARCH: u1 = 0,
VOLUME_UNDEFINE: u1 = 0,
}) CHANGER_FEATURES {
return @intToEnum(CHANGER_FEATURES,
(if (o.BAR_CODE_SCANNER_INSTALLED == 1) @enumToInt(CHANGER_FEATURES.BAR_CODE_SCANNER_INSTALLED) else 0)
| (if (o.CARTRIDGE_MAGAZINE == 1) @enumToInt(CHANGER_FEATURES.CARTRIDGE_MAGAZINE) else 0)
| (if (o.CLEANER_ACCESS_NOT_VALID == 1) @enumToInt(CHANGER_FEATURES.CLEANER_ACCESS_NOT_VALID) else 0)
| (if (o.CLEANER_SLOT == 1) @enumToInt(CHANGER_FEATURES.CLEANER_SLOT) else 0)
| (if (o.CLOSE_IEPORT == 1) @enumToInt(CHANGER_FEATURES.CLOSE_IEPORT) else 0)
| (if (o.DEVICE_REINITIALIZE_CAPABLE == 1) @enumToInt(CHANGER_FEATURES.DEVICE_REINITIALIZE_CAPABLE) else 0)
| (if (o.DRIVE_CLEANING_REQUIRED == 1) @enumToInt(CHANGER_FEATURES.DRIVE_CLEANING_REQUIRED) else 0)
| (if (o.DRIVE_EMPTY_ON_DOOR_ACCESS == 1) @enumToInt(CHANGER_FEATURES.DRIVE_EMPTY_ON_DOOR_ACCESS) else 0)
| (if (o.EXCHANGE_MEDIA == 1) @enumToInt(CHANGER_FEATURES.EXCHANGE_MEDIA) else 0)
| (if (o.INIT_ELEM_STAT_WITH_RANGE == 1) @enumToInt(CHANGER_FEATURES.INIT_ELEM_STAT_WITH_RANGE) else 0)
| (if (o.KEYPAD_ENABLE_DISABLE == 1) @enumToInt(CHANGER_FEATURES.KEYPAD_ENABLE_DISABLE) else 0)
| (if (o.LOCK_UNLOCK == 1) @enumToInt(CHANGER_FEATURES.LOCK_UNLOCK) else 0)
| (if (o.MEDIUM_FLIP == 1) @enumToInt(CHANGER_FEATURES.MEDIUM_FLIP) else 0)
| (if (o.OPEN_IEPORT == 1) @enumToInt(CHANGER_FEATURES.OPEN_IEPORT) else 0)
| (if (o.POSITION_TO_ELEMENT == 1) @enumToInt(CHANGER_FEATURES.POSITION_TO_ELEMENT) else 0)
| (if (o.PREDISMOUNT_EJECT_REQUIRED == 1) @enumToInt(CHANGER_FEATURES.PREDISMOUNT_EJECT_REQUIRED) else 0)
| (if (o.PREMOUNT_EJECT_REQUIRED == 1) @enumToInt(CHANGER_FEATURES.PREMOUNT_EJECT_REQUIRED) else 0)
| (if (o.REPORT_IEPORT_STATE == 1) @enumToInt(CHANGER_FEATURES.REPORT_IEPORT_STATE) else 0)
| (if (o.SERIAL_NUMBER_VALID == 1) @enumToInt(CHANGER_FEATURES.SERIAL_NUMBER_VALID) else 0)
| (if (o.STATUS_NON_VOLATILE == 1) @enumToInt(CHANGER_FEATURES.STATUS_NON_VOLATILE) else 0)
| (if (o.STORAGE_DRIVE == 1) @enumToInt(CHANGER_FEATURES.STORAGE_DRIVE) else 0)
| (if (o.STORAGE_IEPORT == 1) @enumToInt(CHANGER_FEATURES.STORAGE_IEPORT) else 0)
| (if (o.STORAGE_SLOT == 1) @enumToInt(CHANGER_FEATURES.STORAGE_SLOT) else 0)
| (if (o.STORAGE_TRANSPORT == 1) @enumToInt(CHANGER_FEATURES.STORAGE_TRANSPORT) else 0)
| (if (o.VOLUME_ASSERT == 1) @enumToInt(CHANGER_FEATURES.VOLUME_ASSERT) else 0)
| (if (o.VOLUME_IDENTIFICATION == 1) @enumToInt(CHANGER_FEATURES.VOLUME_IDENTIFICATION) else 0)
| (if (o.VOLUME_REPLACE == 1) @enumToInt(CHANGER_FEATURES.VOLUME_REPLACE) else 0)
| (if (o.VOLUME_SEARCH == 1) @enumToInt(CHANGER_FEATURES.VOLUME_SEARCH) else 0)
| (if (o.VOLUME_UNDEFINE == 1) @enumToInt(CHANGER_FEATURES.VOLUME_UNDEFINE) else 0)
);
}
};
pub const CHANGER_BAR_CODE_SCANNER_INSTALLED = CHANGER_FEATURES.BAR_CODE_SCANNER_INSTALLED;
pub const CHANGER_CARTRIDGE_MAGAZINE = CHANGER_FEATURES.CARTRIDGE_MAGAZINE;
pub const CHANGER_CLEANER_ACCESS_NOT_VALID = CHANGER_FEATURES.CLEANER_ACCESS_NOT_VALID;
pub const CHANGER_CLEANER_SLOT = CHANGER_FEATURES.CLEANER_SLOT;
pub const CHANGER_CLOSE_IEPORT = CHANGER_FEATURES.CLOSE_IEPORT;
pub const CHANGER_DEVICE_REINITIALIZE_CAPABLE = CHANGER_FEATURES.DEVICE_REINITIALIZE_CAPABLE;
pub const CHANGER_DRIVE_CLEANING_REQUIRED = CHANGER_FEATURES.DRIVE_CLEANING_REQUIRED;
pub const CHANGER_DRIVE_EMPTY_ON_DOOR_ACCESS = CHANGER_FEATURES.DRIVE_EMPTY_ON_DOOR_ACCESS;
pub const CHANGER_EXCHANGE_MEDIA = CHANGER_FEATURES.EXCHANGE_MEDIA;
pub const CHANGER_INIT_ELEM_STAT_WITH_RANGE = CHANGER_FEATURES.INIT_ELEM_STAT_WITH_RANGE;
pub const CHANGER_KEYPAD_ENABLE_DISABLE = CHANGER_FEATURES.KEYPAD_ENABLE_DISABLE;
pub const CHANGER_LOCK_UNLOCK = CHANGER_FEATURES.LOCK_UNLOCK;
pub const CHANGER_MEDIUM_FLIP = CHANGER_FEATURES.MEDIUM_FLIP;
pub const CHANGER_OPEN_IEPORT = CHANGER_FEATURES.OPEN_IEPORT;
pub const CHANGER_POSITION_TO_ELEMENT = CHANGER_FEATURES.POSITION_TO_ELEMENT;
pub const CHANGER_PREDISMOUNT_EJECT_REQUIRED = CHANGER_FEATURES.PREDISMOUNT_EJECT_REQUIRED;
pub const CHANGER_PREMOUNT_EJECT_REQUIRED = CHANGER_FEATURES.PREMOUNT_EJECT_REQUIRED;
pub const CHANGER_REPORT_IEPORT_STATE = CHANGER_FEATURES.REPORT_IEPORT_STATE;
pub const CHANGER_SERIAL_NUMBER_VALID = CHANGER_FEATURES.SERIAL_NUMBER_VALID;
pub const CHANGER_STATUS_NON_VOLATILE = CHANGER_FEATURES.STATUS_NON_VOLATILE;
pub const CHANGER_STORAGE_DRIVE = CHANGER_FEATURES.STORAGE_DRIVE;
pub const CHANGER_STORAGE_IEPORT = CHANGER_FEATURES.STORAGE_IEPORT;
pub const CHANGER_STORAGE_SLOT = CHANGER_FEATURES.STORAGE_SLOT;
pub const CHANGER_STORAGE_TRANSPORT = CHANGER_FEATURES.STORAGE_TRANSPORT;
pub const CHANGER_VOLUME_ASSERT = CHANGER_FEATURES.VOLUME_ASSERT;
pub const CHANGER_VOLUME_IDENTIFICATION = CHANGER_FEATURES.VOLUME_IDENTIFICATION;
pub const CHANGER_VOLUME_REPLACE = CHANGER_FEATURES.VOLUME_REPLACE;
pub const CHANGER_VOLUME_SEARCH = CHANGER_FEATURES.VOLUME_SEARCH;
pub const CHANGER_VOLUME_UNDEFINE = CHANGER_FEATURES.VOLUME_UNDEFINE;
pub const TTTOOLINFO_FLAGS = enum(u32) {
ABSOLUTE = 128,
CENTERTIP = 2,
IDISHWND = 1,
PARSELINKS = 4096,
RTLREADING = 4,
SUBCLASS = 16,
TRACK = 32,
TRANSPARENT = 256,
_,
pub fn initFlags(o: struct {
ABSOLUTE: u1 = 0,
CENTERTIP: u1 = 0,
IDISHWND: u1 = 0,
PARSELINKS: u1 = 0,
RTLREADING: u1 = 0,
SUBCLASS: u1 = 0,
TRACK: u1 = 0,
TRANSPARENT: u1 = 0,
}) TTTOOLINFO_FLAGS {
return @intToEnum(TTTOOLINFO_FLAGS,
(if (o.ABSOLUTE == 1) @enumToInt(TTTOOLINFO_FLAGS.ABSOLUTE) else 0)
| (if (o.CENTERTIP == 1) @enumToInt(TTTOOLINFO_FLAGS.CENTERTIP) else 0)
| (if (o.IDISHWND == 1) @enumToInt(TTTOOLINFO_FLAGS.IDISHWND) else 0)
| (if (o.PARSELINKS == 1) @enumToInt(TTTOOLINFO_FLAGS.PARSELINKS) else 0)
| (if (o.RTLREADING == 1) @enumToInt(TTTOOLINFO_FLAGS.RTLREADING) else 0)
| (if (o.SUBCLASS == 1) @enumToInt(TTTOOLINFO_FLAGS.SUBCLASS) else 0)
| (if (o.TRACK == 1) @enumToInt(TTTOOLINFO_FLAGS.TRACK) else 0)
| (if (o.TRANSPARENT == 1) @enumToInt(TTTOOLINFO_FLAGS.TRANSPARENT) else 0)
);
}
};
pub const TTF_ABSOLUTE = TTTOOLINFO_FLAGS.ABSOLUTE;
pub const TTF_CENTERTIP = TTTOOLINFO_FLAGS.CENTERTIP;
pub const TTF_IDISHWND = TTTOOLINFO_FLAGS.IDISHWND;
pub const TTF_PARSELINKS = TTTOOLINFO_FLAGS.PARSELINKS;
pub const TTF_RTLREADING = TTTOOLINFO_FLAGS.RTLREADING;
pub const TTF_SUBCLASS = TTTOOLINFO_FLAGS.SUBCLASS;
pub const TTF_TRACK = TTTOOLINFO_FLAGS.TRACK;
pub const TTF_TRANSPARENT = TTTOOLINFO_FLAGS.TRANSPARENT;
pub const JOB_OBJECT_TERMINATE_AT_END_ACTION = enum(u32) {
TERMINATE_AT_END_OF_JOB = 0,
POST_AT_END_OF_JOB = 1,
};
pub const JOB_OBJECT_TERMINATE_AT_END_OF_JOB = JOB_OBJECT_TERMINATE_AT_END_ACTION.TERMINATE_AT_END_OF_JOB;
pub const JOB_OBJECT_POST_AT_END_OF_JOB = JOB_OBJECT_TERMINATE_AT_END_ACTION.POST_AT_END_OF_JOB;
pub const CHANGER_ELEMENT_STATUS_FLAGS = enum(u32) {
ACCESS = 8,
AVOLTAG = 536870912,
EXCEPT = 4,
EXENAB = 16,
FULL = 1,
ID_VALID = 8192,
IMPEXP = 2,
INENAB = 32,
INVERT = 4194304,
LUN_VALID = 4096,
NOT_BUS = 32768,
PVOLTAG = 268435456,
SVALID = 8388608,
PRODUCT_DATA = 64,
_,
pub fn initFlags(o: struct {
ACCESS: u1 = 0,
AVOLTAG: u1 = 0,
EXCEPT: u1 = 0,
EXENAB: u1 = 0,
FULL: u1 = 0,
ID_VALID: u1 = 0,
IMPEXP: u1 = 0,
INENAB: u1 = 0,
INVERT: u1 = 0,
LUN_VALID: u1 = 0,
NOT_BUS: u1 = 0,
PVOLTAG: u1 = 0,
SVALID: u1 = 0,
PRODUCT_DATA: u1 = 0,
}) CHANGER_ELEMENT_STATUS_FLAGS {
return @intToEnum(CHANGER_ELEMENT_STATUS_FLAGS,
(if (o.ACCESS == 1) @enumToInt(CHANGER_ELEMENT_STATUS_FLAGS.ACCESS) else 0)
| (if (o.AVOLTAG == 1) @enumToInt(CHANGER_ELEMENT_STATUS_FLAGS.AVOLTAG) else 0)
| (if (o.EXCEPT == 1) @enumToInt(CHANGER_ELEMENT_STATUS_FLAGS.EXCEPT) else 0)
| (if (o.EXENAB == 1) @enumToInt(CHANGER_ELEMENT_STATUS_FLAGS.EXENAB) else 0)
| (if (o.FULL == 1) @enumToInt(CHANGER_ELEMENT_STATUS_FLAGS.FULL) else 0)
| (if (o.ID_VALID == 1) @enumToInt(CHANGER_ELEMENT_STATUS_FLAGS.ID_VALID) else 0)
| (if (o.IMPEXP == 1) @enumToInt(CHANGER_ELEMENT_STATUS_FLAGS.IMPEXP) else 0)
| (if (o.INENAB == 1) @enumToInt(CHANGER_ELEMENT_STATUS_FLAGS.INENAB) else 0)
| (if (o.INVERT == 1) @enumToInt(CHANGER_ELEMENT_STATUS_FLAGS.INVERT) else 0)
| (if (o.LUN_VALID == 1) @enumToInt(CHANGER_ELEMENT_STATUS_FLAGS.LUN_VALID) else 0)
| (if (o.NOT_BUS == 1) @enumToInt(CHANGER_ELEMENT_STATUS_FLAGS.NOT_BUS) else 0)
| (if (o.PVOLTAG == 1) @enumToInt(CHANGER_ELEMENT_STATUS_FLAGS.PVOLTAG) else 0)
| (if (o.SVALID == 1) @enumToInt(CHANGER_ELEMENT_STATUS_FLAGS.SVALID) else 0)
| (if (o.PRODUCT_DATA == 1) @enumToInt(CHANGER_ELEMENT_STATUS_FLAGS.PRODUCT_DATA) else 0)
);
}
};
pub const ELEMENT_STATUS_ACCESS = CHANGER_ELEMENT_STATUS_FLAGS.ACCESS;
pub const ELEMENT_STATUS_AVOLTAG = CHANGER_ELEMENT_STATUS_FLAGS.AVOLTAG;
pub const ELEMENT_STATUS_EXCEPT = CHANGER_ELEMENT_STATUS_FLAGS.EXCEPT;
pub const ELEMENT_STATUS_EXENAB = CHANGER_ELEMENT_STATUS_FLAGS.EXENAB;
pub const ELEMENT_STATUS_FULL = CHANGER_ELEMENT_STATUS_FLAGS.FULL;
pub const ELEMENT_STATUS_ID_VALID = CHANGER_ELEMENT_STATUS_FLAGS.ID_VALID;
pub const ELEMENT_STATUS_IMPEXP = CHANGER_ELEMENT_STATUS_FLAGS.IMPEXP;
pub const ELEMENT_STATUS_INENAB = CHANGER_ELEMENT_STATUS_FLAGS.INENAB;
pub const ELEMENT_STATUS_INVERT = CHANGER_ELEMENT_STATUS_FLAGS.INVERT;
pub const ELEMENT_STATUS_LUN_VALID = CHANGER_ELEMENT_STATUS_FLAGS.LUN_VALID;
pub const ELEMENT_STATUS_NOT_BUS = CHANGER_ELEMENT_STATUS_FLAGS.NOT_BUS;
pub const ELEMENT_STATUS_PVOLTAG = CHANGER_ELEMENT_STATUS_FLAGS.PVOLTAG;
pub const ELEMENT_STATUS_SVALID = CHANGER_ELEMENT_STATUS_FLAGS.SVALID;
pub const ELEMENT_STATUS_PRODUCT_DATA = CHANGER_ELEMENT_STATUS_FLAGS.PRODUCT_DATA;
pub const TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH = enum(u32) {
ABS_BLK_IMMED = 2147491840,
ABSOLUTE_BLK = 2147487744,
END_OF_DATA = 2147549184,
FILEMARKS = 2147745792,
LOAD_UNLOAD = 2147483649,
LOAD_UNLD_IMMED = 2147483680,
LOCK_UNLOCK = 2147483652,
LOCK_UNLK_IMMED = 2147483776,
LOG_BLK_IMMED = 2147516416,
LOGICAL_BLK = 2147500032,
RELATIVE_BLKS = 2147614720,
REVERSE_POSITION = 2151677952,
REWIND_IMMEDIATE = 2147483656,
SEQUENTIAL_FMKS = 2148007936,
SEQUENTIAL_SMKS = 2149580800,
SET_BLOCK_SIZE = 2147483664,
SET_COMPRESSION = 2147484160,
SET_ECC = 2147483904,
SET_PADDING = 2147484672,
SET_REPORT_SMKS = 2147485696,
SETMARKS = 2148532224,
SPACE_IMMEDIATE = 2155872256,
TENSION = 2147483650,
TENSION_IMMED = 2147483712,
WRITE_FILEMARKS = 2181038080,
WRITE_LONG_FMKS = 2281701376,
WRITE_MARK_IMMED = 2415919104,
WRITE_SETMARKS = 2164260864,
WRITE_SHORT_FMKS = 2214592512,
_,
pub fn initFlags(o: struct {
ABS_BLK_IMMED: u1 = 0,
ABSOLUTE_BLK: u1 = 0,
END_OF_DATA: u1 = 0,
FILEMARKS: u1 = 0,
LOAD_UNLOAD: u1 = 0,
LOAD_UNLD_IMMED: u1 = 0,
LOCK_UNLOCK: u1 = 0,
LOCK_UNLK_IMMED: u1 = 0,
LOG_BLK_IMMED: u1 = 0,
LOGICAL_BLK: u1 = 0,
RELATIVE_BLKS: u1 = 0,
REVERSE_POSITION: u1 = 0,
REWIND_IMMEDIATE: u1 = 0,
SEQUENTIAL_FMKS: u1 = 0,
SEQUENTIAL_SMKS: u1 = 0,
SET_BLOCK_SIZE: u1 = 0,
SET_COMPRESSION: u1 = 0,
SET_ECC: u1 = 0,
SET_PADDING: u1 = 0,
SET_REPORT_SMKS: u1 = 0,
SETMARKS: u1 = 0,
SPACE_IMMEDIATE: u1 = 0,
TENSION: u1 = 0,
TENSION_IMMED: u1 = 0,
WRITE_FILEMARKS: u1 = 0,
WRITE_LONG_FMKS: u1 = 0,
WRITE_MARK_IMMED: u1 = 0,
WRITE_SETMARKS: u1 = 0,
WRITE_SHORT_FMKS: u1 = 0,
}) TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH {
return @intToEnum(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH,
(if (o.ABS_BLK_IMMED == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.ABS_BLK_IMMED) else 0)
| (if (o.ABSOLUTE_BLK == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.ABSOLUTE_BLK) else 0)
| (if (o.END_OF_DATA == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.END_OF_DATA) else 0)
| (if (o.FILEMARKS == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.FILEMARKS) else 0)
| (if (o.LOAD_UNLOAD == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.LOAD_UNLOAD) else 0)
| (if (o.LOAD_UNLD_IMMED == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.LOAD_UNLD_IMMED) else 0)
| (if (o.LOCK_UNLOCK == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.LOCK_UNLOCK) else 0)
| (if (o.LOCK_UNLK_IMMED == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.LOCK_UNLK_IMMED) else 0)
| (if (o.LOG_BLK_IMMED == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.LOG_BLK_IMMED) else 0)
| (if (o.LOGICAL_BLK == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.LOGICAL_BLK) else 0)
| (if (o.RELATIVE_BLKS == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.RELATIVE_BLKS) else 0)
| (if (o.REVERSE_POSITION == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.REVERSE_POSITION) else 0)
| (if (o.REWIND_IMMEDIATE == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.REWIND_IMMEDIATE) else 0)
| (if (o.SEQUENTIAL_FMKS == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.SEQUENTIAL_FMKS) else 0)
| (if (o.SEQUENTIAL_SMKS == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.SEQUENTIAL_SMKS) else 0)
| (if (o.SET_BLOCK_SIZE == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.SET_BLOCK_SIZE) else 0)
| (if (o.SET_COMPRESSION == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.SET_COMPRESSION) else 0)
| (if (o.SET_ECC == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.SET_ECC) else 0)
| (if (o.SET_PADDING == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.SET_PADDING) else 0)
| (if (o.SET_REPORT_SMKS == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.SET_REPORT_SMKS) else 0)
| (if (o.SETMARKS == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.SETMARKS) else 0)
| (if (o.SPACE_IMMEDIATE == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.SPACE_IMMEDIATE) else 0)
| (if (o.TENSION == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.TENSION) else 0)
| (if (o.TENSION_IMMED == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.TENSION_IMMED) else 0)
| (if (o.WRITE_FILEMARKS == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.WRITE_FILEMARKS) else 0)
| (if (o.WRITE_LONG_FMKS == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.WRITE_LONG_FMKS) else 0)
| (if (o.WRITE_MARK_IMMED == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.WRITE_MARK_IMMED) else 0)
| (if (o.WRITE_SETMARKS == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.WRITE_SETMARKS) else 0)
| (if (o.WRITE_SHORT_FMKS == 1) @enumToInt(TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.WRITE_SHORT_FMKS) else 0)
);
}
};
pub const TAPE_DRIVE_ABS_BLK_IMMED = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.ABS_BLK_IMMED;
pub const TAPE_DRIVE_ABSOLUTE_BLK = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.ABSOLUTE_BLK;
pub const TAPE_DRIVE_END_OF_DATA = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.END_OF_DATA;
pub const TAPE_DRIVE_FILEMARKS = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.FILEMARKS;
pub const TAPE_DRIVE_LOAD_UNLOAD = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.LOAD_UNLOAD;
pub const TAPE_DRIVE_LOAD_UNLD_IMMED = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.LOAD_UNLD_IMMED;
pub const TAPE_DRIVE_LOCK_UNLOCK = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.LOCK_UNLOCK;
pub const TAPE_DRIVE_LOCK_UNLK_IMMED = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.LOCK_UNLK_IMMED;
pub const TAPE_DRIVE_LOG_BLK_IMMED = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.LOG_BLK_IMMED;
pub const TAPE_DRIVE_LOGICAL_BLK = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.LOGICAL_BLK;
pub const TAPE_DRIVE_RELATIVE_BLKS = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.RELATIVE_BLKS;
pub const TAPE_DRIVE_REVERSE_POSITION = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.REVERSE_POSITION;
pub const TAPE_DRIVE_REWIND_IMMEDIATE = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.REWIND_IMMEDIATE;
pub const TAPE_DRIVE_SEQUENTIAL_FMKS = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.SEQUENTIAL_FMKS;
pub const TAPE_DRIVE_SEQUENTIAL_SMKS = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.SEQUENTIAL_SMKS;
pub const TAPE_DRIVE_SET_BLOCK_SIZE = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.SET_BLOCK_SIZE;
pub const TAPE_DRIVE_SET_COMPRESSION = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.SET_COMPRESSION;
pub const TAPE_DRIVE_SET_ECC = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.SET_ECC;
pub const TAPE_DRIVE_SET_PADDING = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.SET_PADDING;
pub const TAPE_DRIVE_SET_REPORT_SMKS = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.SET_REPORT_SMKS;
pub const TAPE_DRIVE_SETMARKS = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.SETMARKS;
pub const TAPE_DRIVE_SPACE_IMMEDIATE = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.SPACE_IMMEDIATE;
pub const TAPE_DRIVE_TENSION = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.TENSION;
pub const TAPE_DRIVE_TENSION_IMMED = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.TENSION_IMMED;
pub const TAPE_DRIVE_WRITE_FILEMARKS = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.WRITE_FILEMARKS;
pub const TAPE_DRIVE_WRITE_LONG_FMKS = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.WRITE_LONG_FMKS;
pub const TAPE_DRIVE_WRITE_MARK_IMMED = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.WRITE_MARK_IMMED;
pub const TAPE_DRIVE_WRITE_SETMARKS = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.WRITE_SETMARKS;
pub const TAPE_DRIVE_WRITE_SHORT_FMKS = TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH.WRITE_SHORT_FMKS;
pub const DEV_BROADCAST_HDR_DEVICE_TYPE = enum(u32) {
DEVICEINTERFACE = 5,
HANDLE = 6,
OEM = 0,
PORT = 3,
VOLUME = 2,
};
pub const DBT_DEVTYP_DEVICEINTERFACE = DEV_BROADCAST_HDR_DEVICE_TYPE.DEVICEINTERFACE;
pub const DBT_DEVTYP_HANDLE = DEV_BROADCAST_HDR_DEVICE_TYPE.HANDLE;
pub const DBT_DEVTYP_OEM = DEV_BROADCAST_HDR_DEVICE_TYPE.OEM;
pub const DBT_DEVTYP_PORT = DEV_BROADCAST_HDR_DEVICE_TYPE.PORT;
pub const DBT_DEVTYP_VOLUME = DEV_BROADCAST_HDR_DEVICE_TYPE.VOLUME;
pub const GET_CHANGER_PARAMETERS_FEATURES1 = enum(u32) {
CLEANER_AUTODISMOUNT = 2147483652,
CLEANER_OPS_NOT_SUPPORTED = 2147483712,
IEPORT_USER_CONTROL_CLOSE = 2147483904,
IEPORT_USER_CONTROL_OPEN = 2147483776,
MOVE_EXTENDS_IEPORT = 2147484160,
MOVE_RETRACTS_IEPORT = 2147484672,
PREDISMOUNT_ALIGN_TO_DRIVE = 2147483650,
PREDISMOUNT_ALIGN_TO_SLOT = 2147483649,
RTN_MEDIA_TO_ORIGINAL_ADDR = 2147483680,
SLOTS_USE_TRAYS = 2147483664,
TRUE_EXCHANGE_CAPABLE = 2147483656,
_,
pub fn initFlags(o: struct {
CLEANER_AUTODISMOUNT: u1 = 0,
CLEANER_OPS_NOT_SUPPORTED: u1 = 0,
IEPORT_USER_CONTROL_CLOSE: u1 = 0,
IEPORT_USER_CONTROL_OPEN: u1 = 0,
MOVE_EXTENDS_IEPORT: u1 = 0,
MOVE_RETRACTS_IEPORT: u1 = 0,
PREDISMOUNT_ALIGN_TO_DRIVE: u1 = 0,
PREDISMOUNT_ALIGN_TO_SLOT: u1 = 0,
RTN_MEDIA_TO_ORIGINAL_ADDR: u1 = 0,
SLOTS_USE_TRAYS: u1 = 0,
TRUE_EXCHANGE_CAPABLE: u1 = 0,
}) GET_CHANGER_PARAMETERS_FEATURES1 {
return @intToEnum(GET_CHANGER_PARAMETERS_FEATURES1,
(if (o.CLEANER_AUTODISMOUNT == 1) @enumToInt(GET_CHANGER_PARAMETERS_FEATURES1.CLEANER_AUTODISMOUNT) else 0)
| (if (o.CLEANER_OPS_NOT_SUPPORTED == 1) @enumToInt(GET_CHANGER_PARAMETERS_FEATURES1.CLEANER_OPS_NOT_SUPPORTED) else 0)
| (if (o.IEPORT_USER_CONTROL_CLOSE == 1) @enumToInt(GET_CHANGER_PARAMETERS_FEATURES1.IEPORT_USER_CONTROL_CLOSE) else 0)
| (if (o.IEPORT_USER_CONTROL_OPEN == 1) @enumToInt(GET_CHANGER_PARAMETERS_FEATURES1.IEPORT_USER_CONTROL_OPEN) else 0)
| (if (o.MOVE_EXTENDS_IEPORT == 1) @enumToInt(GET_CHANGER_PARAMETERS_FEATURES1.MOVE_EXTENDS_IEPORT) else 0)
| (if (o.MOVE_RETRACTS_IEPORT == 1) @enumToInt(GET_CHANGER_PARAMETERS_FEATURES1.MOVE_RETRACTS_IEPORT) else 0)
| (if (o.PREDISMOUNT_ALIGN_TO_DRIVE == 1) @enumToInt(GET_CHANGER_PARAMETERS_FEATURES1.PREDISMOUNT_ALIGN_TO_DRIVE) else 0)
| (if (o.PREDISMOUNT_ALIGN_TO_SLOT == 1) @enumToInt(GET_CHANGER_PARAMETERS_FEATURES1.PREDISMOUNT_ALIGN_TO_SLOT) else 0)
| (if (o.RTN_MEDIA_TO_ORIGINAL_ADDR == 1) @enumToInt(GET_CHANGER_PARAMETERS_FEATURES1.RTN_MEDIA_TO_ORIGINAL_ADDR) else 0)
| (if (o.SLOTS_USE_TRAYS == 1) @enumToInt(GET_CHANGER_PARAMETERS_FEATURES1.SLOTS_USE_TRAYS) else 0)
| (if (o.TRUE_EXCHANGE_CAPABLE == 1) @enumToInt(GET_CHANGER_PARAMETERS_FEATURES1.TRUE_EXCHANGE_CAPABLE) else 0)
);
}
};
pub const CHANGER_CLEANER_AUTODISMOUNT = GET_CHANGER_PARAMETERS_FEATURES1.CLEANER_AUTODISMOUNT;
pub const CHANGER_CLEANER_OPS_NOT_SUPPORTED = GET_CHANGER_PARAMETERS_FEATURES1.CLEANER_OPS_NOT_SUPPORTED;
pub const CHANGER_IEPORT_USER_CONTROL_CLOSE = GET_CHANGER_PARAMETERS_FEATURES1.IEPORT_USER_CONTROL_CLOSE;
pub const CHANGER_IEPORT_USER_CONTROL_OPEN = GET_CHANGER_PARAMETERS_FEATURES1.IEPORT_USER_CONTROL_OPEN;
pub const CHANGER_MOVE_EXTENDS_IEPORT = GET_CHANGER_PARAMETERS_FEATURES1.MOVE_EXTENDS_IEPORT;
pub const CHANGER_MOVE_RETRACTS_IEPORT = GET_CHANGER_PARAMETERS_FEATURES1.MOVE_RETRACTS_IEPORT;
pub const CHANGER_PREDISMOUNT_ALIGN_TO_DRIVE = GET_CHANGER_PARAMETERS_FEATURES1.PREDISMOUNT_ALIGN_TO_DRIVE;
pub const CHANGER_PREDISMOUNT_ALIGN_TO_SLOT = GET_CHANGER_PARAMETERS_FEATURES1.PREDISMOUNT_ALIGN_TO_SLOT;
pub const CHANGER_RTN_MEDIA_TO_ORIGINAL_ADDR = GET_CHANGER_PARAMETERS_FEATURES1.RTN_MEDIA_TO_ORIGINAL_ADDR;
pub const CHANGER_SLOTS_USE_TRAYS = GET_CHANGER_PARAMETERS_FEATURES1.SLOTS_USE_TRAYS;
pub const CHANGER_TRUE_EXCHANGE_CAPABLE = GET_CHANGER_PARAMETERS_FEATURES1.TRUE_EXCHANGE_CAPABLE;
pub const DEV_BROADCAST_VOLUME_FLAGS = enum(u16) {
MEDIA = 1,
NET = 2,
};
pub const DBTF_MEDIA = DEV_BROADCAST_VOLUME_FLAGS.MEDIA;
pub const DBTF_NET = DEV_BROADCAST_VOLUME_FLAGS.NET;
pub const CERT_VIEWPROPERTIES_STRUCT_FLAGS = enum(u32) {
ENABLEHOOK = 1,
SHOW_HELP = 2,
SHOW_HELPICON = 4,
ENABLETEMPLATE = 8,
HIDE_ADVANCEPAGE = 16,
HIDE_TRUSTPAGE = 32,
NO_NAMECHANGE = 64,
NO_EDITTRUST = 128,
HIDE_DETAILPAGE = 256,
ADD_CERT_STORES = 512,
_,
pub fn initFlags(o: struct {
ENABLEHOOK: u1 = 0,
SHOW_HELP: u1 = 0,
SHOW_HELPICON: u1 = 0,
ENABLETEMPLATE: u1 = 0,
HIDE_ADVANCEPAGE: u1 = 0,
HIDE_TRUSTPAGE: u1 = 0,
NO_NAMECHANGE: u1 = 0,
NO_EDITTRUST: u1 = 0,
HIDE_DETAILPAGE: u1 = 0,
ADD_CERT_STORES: u1 = 0,
}) CERT_VIEWPROPERTIES_STRUCT_FLAGS {
return @intToEnum(CERT_VIEWPROPERTIES_STRUCT_FLAGS,
(if (o.ENABLEHOOK == 1) @enumToInt(CERT_VIEWPROPERTIES_STRUCT_FLAGS.ENABLEHOOK) else 0)
| (if (o.SHOW_HELP == 1) @enumToInt(CERT_VIEWPROPERTIES_STRUCT_FLAGS.SHOW_HELP) else 0)
| (if (o.SHOW_HELPICON == 1) @enumToInt(CERT_VIEWPROPERTIES_STRUCT_FLAGS.SHOW_HELPICON) else 0)
| (if (o.ENABLETEMPLATE == 1) @enumToInt(CERT_VIEWPROPERTIES_STRUCT_FLAGS.ENABLETEMPLATE) else 0)
| (if (o.HIDE_ADVANCEPAGE == 1) @enumToInt(CERT_VIEWPROPERTIES_STRUCT_FLAGS.HIDE_ADVANCEPAGE) else 0)
| (if (o.HIDE_TRUSTPAGE == 1) @enumToInt(CERT_VIEWPROPERTIES_STRUCT_FLAGS.HIDE_TRUSTPAGE) else 0)
| (if (o.NO_NAMECHANGE == 1) @enumToInt(CERT_VIEWPROPERTIES_STRUCT_FLAGS.NO_NAMECHANGE) else 0)
| (if (o.NO_EDITTRUST == 1) @enumToInt(CERT_VIEWPROPERTIES_STRUCT_FLAGS.NO_EDITTRUST) else 0)
| (if (o.HIDE_DETAILPAGE == 1) @enumToInt(CERT_VIEWPROPERTIES_STRUCT_FLAGS.HIDE_DETAILPAGE) else 0)
| (if (o.ADD_CERT_STORES == 1) @enumToInt(CERT_VIEWPROPERTIES_STRUCT_FLAGS.ADD_CERT_STORES) else 0)
);
}
};
pub const CM_ENABLEHOOK = CERT_VIEWPROPERTIES_STRUCT_FLAGS.ENABLEHOOK;
pub const CM_SHOW_HELP = CERT_VIEWPROPERTIES_STRUCT_FLAGS.SHOW_HELP;
pub const CM_SHOW_HELPICON = CERT_VIEWPROPERTIES_STRUCT_FLAGS.SHOW_HELPICON;
pub const CM_ENABLETEMPLATE = CERT_VIEWPROPERTIES_STRUCT_FLAGS.ENABLETEMPLATE;
pub const CM_HIDE_ADVANCEPAGE = CERT_VIEWPROPERTIES_STRUCT_FLAGS.HIDE_ADVANCEPAGE;
pub const CM_HIDE_TRUSTPAGE = CERT_VIEWPROPERTIES_STRUCT_FLAGS.HIDE_TRUSTPAGE;
pub const CM_NO_NAMECHANGE = CERT_VIEWPROPERTIES_STRUCT_FLAGS.NO_NAMECHANGE;
pub const CM_NO_EDITTRUST = CERT_VIEWPROPERTIES_STRUCT_FLAGS.NO_EDITTRUST;
pub const CM_HIDE_DETAILPAGE = CERT_VIEWPROPERTIES_STRUCT_FLAGS.HIDE_DETAILPAGE;
pub const CM_ADD_CERT_STORES = CERT_VIEWPROPERTIES_STRUCT_FLAGS.ADD_CERT_STORES;
pub const POWER_REQUEST_CONTEXT_FLAGS = enum(u32) {
DETAILED_STRING = 2,
SIMPLE_STRING = 1,
};
pub const POWER_REQUEST_CONTEXT_DETAILED_STRING = POWER_REQUEST_CONTEXT_FLAGS.DETAILED_STRING;
pub const POWER_REQUEST_CONTEXT_SIMPLE_STRING = POWER_REQUEST_CONTEXT_FLAGS.SIMPLE_STRING;
pub const PUMS_SCHEDULER_ENTRY_POINT = fn(
Reason: RTL_UMS_SCHEDULER_REASON,
ActivationPayload: usize,
SchedulerParam: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
pub const TP_CALLBACK_INSTANCE = extern struct {
placeholder: usize, // TODO: why is this type empty?
};
pub const TP_POOL = extern struct {
placeholder: usize, // TODO: why is this type empty?
};
pub const TP_CLEANUP_GROUP = extern struct {
placeholder: usize, // TODO: why is this type empty?
};
pub const TP_WORK = extern struct {
placeholder: usize, // TODO: why is this type empty?
};
pub const TP_TIMER = extern struct {
placeholder: usize, // TODO: why is this type empty?
};
pub const TP_WAIT = extern struct {
placeholder: usize, // TODO: why is this type empty?
};
pub const TP_IO = extern struct {
placeholder: usize, // TODO: why is this type empty?
};
pub const TEB = extern struct {
placeholder: usize, // TODO: why is this type empty?
};
pub const AtlThunkData_t = extern struct {
placeholder: usize, // TODO: why is this type empty?
};
pub const HSURF = *opaque{};
pub const DPI_AWARENESS_CONTEXT = isize;
pub const HUMPD = *opaque{};
pub const HSTR = *opaque{};
pub const HSPRITE = *opaque{};
pub const HLSURF = *opaque{};
pub const HFASTMUTEX = *opaque{};
pub const HDRVOBJ = *opaque{};
pub const HDEV = *opaque{};
pub const HBM = *opaque{};
pub const DHSURF = isize;
pub const DHPDEV = isize;
pub const CHAR = u8;
pub const SHANDLE_PTR = isize;
pub const HANDLE_PTR = usize;
pub const FLOAT128 = extern struct {
LowPart: i64,
HighPart: i64,
};
pub const LARGE_INTEGER = extern union {
Anonymous: extern struct {
LowPart: u32,
HighPart: i32,
},
u: extern struct {
LowPart: u32,
HighPart: i32,
},
QuadPart: i64,
};
pub const ULARGE_INTEGER = extern union {
Anonymous: extern struct {
LowPart: u32,
HighPart: u32,
},
u: extern struct {
LowPart: u32,
HighPart: u32,
},
QuadPart: u64,
};
pub const LUID = extern struct {
LowPart: u32,
HighPart: i32,
};
pub const M128A = extern struct {
Low: u64,
High: i64,
};
pub const XSAVE_CET_U_FORMAT = extern struct {
Ia32CetUMsr: u64,
Ia32Pl3SspMsr: u64,
};
pub const XSAVE_AREA_HEADER = extern struct {
Mask: u64,
CompactionMask: u64,
Reserved2: [6]u64,
};
pub const XSAVE_AREA = extern struct {
LegacyState: XSAVE_FORMAT,
Header: XSAVE_AREA_HEADER,
};
pub const SCOPE_TABLE_AMD64 = extern struct {
Count: u32,
ScopeRecord: [1]extern struct {
BeginAddress: u32,
EndAddress: u32,
HandlerAddress: u32,
JumpTarget: u32,
},
};
pub const SCOPE_TABLE_ARM = extern struct {
Count: u32,
ScopeRecord: [1]extern struct {
BeginAddress: u32,
EndAddress: u32,
HandlerAddress: u32,
JumpTarget: u32,
},
};
pub const SCOPE_TABLE_ARM64 = extern struct {
Count: u32,
ScopeRecord: [1]extern struct {
BeginAddress: u32,
EndAddress: u32,
HandlerAddress: u32,
JumpTarget: u32,
},
};
pub const EXCEPTION_RECORD32 = extern struct {
ExceptionCode: NTSTATUS,
ExceptionFlags: u32,
ExceptionRecord: u32,
ExceptionAddress: u32,
NumberParameters: u32,
ExceptionInformation: [15]u32,
};
pub const SE_SID = extern union {
Sid: SID,
Buffer: [68]u8,
};
pub const SYSTEM_PROCESS_TRUST_LABEL_ACE = extern struct {
Header: ACE_HEADER,
Mask: u32,
SidStart: u32,
};
pub const SYSTEM_ACCESS_FILTER_ACE = extern struct {
Header: ACE_HEADER,
Mask: u32,
SidStart: u32,
};
pub const SECURITY_DESCRIPTOR_RELATIVE = extern struct {
Revision: u8,
Sbz1: u8,
Control: u16,
Owner: u32,
Group: u32,
Sacl: u32,
Dacl: u32,
};
pub const SECURITY_OBJECT_AI_PARAMS = extern struct {
Size: u32,
ConstraintMask: u32,
};
pub const ACCESS_REASON_TYPE = enum(i32) {
None = 0,
AllowedAce = 65536,
DeniedAce = 131072,
AllowedParentAce = 196608,
DeniedParentAce = 262144,
NotGrantedByCape = 327680,
NotGrantedByParentCape = 393216,
NotGrantedToAppContainer = 458752,
MissingPrivilege = 1048576,
FromPrivilege = 2097152,
IntegrityLevel = 3145728,
Ownership = 4194304,
NullDacl = 5242880,
EmptyDacl = 6291456,
NoSD = 7340032,
NoGrant = 8388608,
TrustLabel = 9437184,
FilterAce = 10485760,
};
pub const AccessReasonNone = ACCESS_REASON_TYPE.None;
pub const AccessReasonAllowedAce = ACCESS_REASON_TYPE.AllowedAce;
pub const AccessReasonDeniedAce = ACCESS_REASON_TYPE.DeniedAce;
pub const AccessReasonAllowedParentAce = ACCESS_REASON_TYPE.AllowedParentAce;
pub const AccessReasonDeniedParentAce = ACCESS_REASON_TYPE.DeniedParentAce;
pub const AccessReasonNotGrantedByCape = ACCESS_REASON_TYPE.NotGrantedByCape;
pub const AccessReasonNotGrantedByParentCape = ACCESS_REASON_TYPE.NotGrantedByParentCape;
pub const AccessReasonNotGrantedToAppContainer = ACCESS_REASON_TYPE.NotGrantedToAppContainer;
pub const AccessReasonMissingPrivilege = ACCESS_REASON_TYPE.MissingPrivilege;
pub const AccessReasonFromPrivilege = ACCESS_REASON_TYPE.FromPrivilege;
pub const AccessReasonIntegrityLevel = ACCESS_REASON_TYPE.IntegrityLevel;
pub const AccessReasonOwnership = ACCESS_REASON_TYPE.Ownership;
pub const AccessReasonNullDacl = ACCESS_REASON_TYPE.NullDacl;
pub const AccessReasonEmptyDacl = ACCESS_REASON_TYPE.EmptyDacl;
pub const AccessReasonNoSD = ACCESS_REASON_TYPE.NoSD;
pub const AccessReasonNoGrant = ACCESS_REASON_TYPE.NoGrant;
pub const AccessReasonTrustLabel = ACCESS_REASON_TYPE.TrustLabel;
pub const AccessReasonFilterAce = ACCESS_REASON_TYPE.FilterAce;
pub const ACCESS_REASONS = extern struct {
Data: [32]u32,
};
pub const SE_SECURITY_DESCRIPTOR = extern struct {
Size: u32,
Flags: u32,
SecurityDescriptor: ?*SECURITY_DESCRIPTOR,
};
pub const SE_ACCESS_REQUEST = extern struct {
Size: u32,
SeSecurityDescriptor: ?*SE_SECURITY_DESCRIPTOR,
DesiredAccess: u32,
PreviouslyGrantedAccess: u32,
PrincipalSelfSid: ?PSID,
GenericMapping: ?*GENERIC_MAPPING,
ObjectTypeListCount: u32,
ObjectTypeList: ?*OBJECT_TYPE_LIST,
};
pub const SE_ACCESS_REPLY = extern struct {
Size: u32,
ResultListCount: u32,
GrantedAccess: ?*u32,
AccessStatus: ?*u32,
AccessReason: ?*ACCESS_REASONS,
Privileges: ?*?*PRIVILEGE_SET,
};
pub const SE_TOKEN_USER = extern struct {
Anonymous1: extern union {
TokenUser: TOKEN_USER,
User: SID_AND_ATTRIBUTES,
},
Anonymous2: extern union {
Sid: SID,
Buffer: [68]u8,
},
};
pub const TOKEN_SID_INFORMATION = extern struct {
Sid: ?PSID,
};
pub const TOKEN_BNO_ISOLATION_INFORMATION = extern struct {
IsolationPrefix: ?PWSTR,
IsolationEnabled: BOOLEAN,
};
pub const SE_IMPERSONATION_STATE = extern struct {
Token: ?*c_void,
CopyOnOpen: BOOLEAN,
EffectiveOnly: BOOLEAN,
Level: SECURITY_IMPERSONATION_LEVEL,
};
pub const SE_IMAGE_SIGNATURE_TYPE = enum(i32) {
None = 0,
Embedded = 1,
Cache = 2,
CatalogCached = 3,
CatalogNotCached = 4,
CatalogHint = 5,
PackageCatalog = 6,
};
pub const SeImageSignatureNone = SE_IMAGE_SIGNATURE_TYPE.None;
pub const SeImageSignatureEmbedded = SE_IMAGE_SIGNATURE_TYPE.Embedded;
pub const SeImageSignatureCache = SE_IMAGE_SIGNATURE_TYPE.Cache;
pub const SeImageSignatureCatalogCached = SE_IMAGE_SIGNATURE_TYPE.CatalogCached;
pub const SeImageSignatureCatalogNotCached = SE_IMAGE_SIGNATURE_TYPE.CatalogNotCached;
pub const SeImageSignatureCatalogHint = SE_IMAGE_SIGNATURE_TYPE.CatalogHint;
pub const SeImageSignaturePackageCatalog = SE_IMAGE_SIGNATURE_TYPE.PackageCatalog;
pub const SE_LEARNING_MODE_DATA_TYPE = enum(i32) {
InvalidType = 0,
Settings = 1,
Max = 2,
};
pub const SeLearningModeInvalidType = SE_LEARNING_MODE_DATA_TYPE.InvalidType;
pub const SeLearningModeSettings = SE_LEARNING_MODE_DATA_TYPE.Settings;
pub const SeLearningModeMax = SE_LEARNING_MODE_DATA_TYPE.Max;
pub const JOB_SET_ARRAY = extern struct {
JobHandle: ?HANDLE,
MemberLevel: u32,
Flags: u32,
};
pub const EXCEPTION_REGISTRATION_RECORD = extern struct {
Next: ?*EXCEPTION_REGISTRATION_RECORD,
Handler: ?EXCEPTION_ROUTINE,
};
pub const NT_TIB = extern struct {
ExceptionList: ?*EXCEPTION_REGISTRATION_RECORD,
StackBase: ?*c_void,
StackLimit: ?*c_void,
SubSystemTib: ?*c_void,
Anonymous: extern union {
FiberData: ?*c_void,
Version: u32,
},
ArbitraryUserPointer: ?*c_void,
Self: ?*NT_TIB,
};
pub const NT_TIB32 = extern struct {
ExceptionList: u32,
StackBase: u32,
StackLimit: u32,
SubSystemTib: u32,
Anonymous: extern union {
FiberData: u32,
Version: u32,
},
ArbitraryUserPointer: u32,
Self: u32,
};
pub const NT_TIB64 = extern struct {
ExceptionList: u64,
StackBase: u64,
StackLimit: u64,
SubSystemTib: u64,
Anonymous: extern union {
FiberData: u64,
Version: u32,
},
ArbitraryUserPointer: u64,
Self: u64,
};
pub const UMS_CREATE_THREAD_ATTRIBUTES = extern struct {
UmsVersion: u32,
UmsContext: ?*c_void,
UmsCompletionList: ?*c_void,
};
pub const PROCESS_DYNAMIC_EH_CONTINUATION_TARGET = extern struct {
TargetAddress: usize,
Flags: usize,
};
pub const PROCESS_DYNAMIC_EH_CONTINUATION_TARGETS_INFORMATION = extern struct {
NumberOfTargets: u16,
Reserved: u16,
Reserved2: u32,
Targets: ?*PROCESS_DYNAMIC_EH_CONTINUATION_TARGET,
};
pub const RATE_QUOTA_LIMIT = extern union {
RateData: u32,
Anonymous: extern struct {
_bitfield: u32,
},
};
pub const QUOTA_LIMITS_EX = extern struct {
PagedPoolLimit: usize,
NonPagedPoolLimit: usize,
MinimumWorkingSetSize: usize,
MaximumWorkingSetSize: usize,
PagefileLimit: usize,
TimeLimit: LARGE_INTEGER,
WorkingSetLimit: usize,
Reserved2: usize,
Reserved3: usize,
Reserved4: usize,
Flags: u32,
CpuRateLimit: RATE_QUOTA_LIMIT,
};
pub const IO_COUNTERS = extern struct {
ReadOperationCount: u64,
WriteOperationCount: u64,
OtherOperationCount: u64,
ReadTransferCount: u64,
WriteTransferCount: u64,
OtherTransferCount: u64,
};
pub const PROCESS_MITIGATION_POLICY = enum(i32) {
ProcessDEPPolicy = 0,
ProcessASLRPolicy = 1,
ProcessDynamicCodePolicy = 2,
ProcessStrictHandleCheckPolicy = 3,
ProcessSystemCallDisablePolicy = 4,
ProcessMitigationOptionsMask = 5,
ProcessExtensionPointDisablePolicy = 6,
ProcessControlFlowGuardPolicy = 7,
ProcessSignaturePolicy = 8,
ProcessFontDisablePolicy = 9,
ProcessImageLoadPolicy = 10,
ProcessSystemCallFilterPolicy = 11,
ProcessPayloadRestrictionPolicy = 12,
ProcessChildProcessPolicy = 13,
ProcessSideChannelIsolationPolicy = 14,
ProcessUserShadowStackPolicy = 15,
MaxProcessMitigationPolicy = 16,
};
pub const ProcessDEPPolicy = PROCESS_MITIGATION_POLICY.ProcessDEPPolicy;
pub const ProcessASLRPolicy = PROCESS_MITIGATION_POLICY.ProcessASLRPolicy;
pub const ProcessDynamicCodePolicy = PROCESS_MITIGATION_POLICY.ProcessDynamicCodePolicy;
pub const ProcessStrictHandleCheckPolicy = PROCESS_MITIGATION_POLICY.ProcessStrictHandleCheckPolicy;
pub const ProcessSystemCallDisablePolicy = PROCESS_MITIGATION_POLICY.ProcessSystemCallDisablePolicy;
pub const ProcessMitigationOptionsMask = PROCESS_MITIGATION_POLICY.ProcessMitigationOptionsMask;
pub const ProcessExtensionPointDisablePolicy = PROCESS_MITIGATION_POLICY.ProcessExtensionPointDisablePolicy;
pub const ProcessControlFlowGuardPolicy = PROCESS_MITIGATION_POLICY.ProcessControlFlowGuardPolicy;
pub const ProcessSignaturePolicy = PROCESS_MITIGATION_POLICY.ProcessSignaturePolicy;
pub const ProcessFontDisablePolicy = PROCESS_MITIGATION_POLICY.ProcessFontDisablePolicy;
pub const ProcessImageLoadPolicy = PROCESS_MITIGATION_POLICY.ProcessImageLoadPolicy;
pub const ProcessSystemCallFilterPolicy = PROCESS_MITIGATION_POLICY.ProcessSystemCallFilterPolicy;
pub const ProcessPayloadRestrictionPolicy = PROCESS_MITIGATION_POLICY.ProcessPayloadRestrictionPolicy;
pub const ProcessChildProcessPolicy = PROCESS_MITIGATION_POLICY.ProcessChildProcessPolicy;
pub const ProcessSideChannelIsolationPolicy = PROCESS_MITIGATION_POLICY.ProcessSideChannelIsolationPolicy;
pub const ProcessUserShadowStackPolicy = PROCESS_MITIGATION_POLICY.ProcessUserShadowStackPolicy;
pub const MaxProcessMitigationPolicy = PROCESS_MITIGATION_POLICY.MaxProcessMitigationPolicy;
pub const PROCESS_MITIGATION_ASLR_POLICY = extern struct {
Anonymous: extern union {
Flags: u32,
Anonymous: extern struct {
_bitfield: u32,
},
},
};
pub const PROCESS_MITIGATION_DEP_POLICY = extern struct {
Anonymous: extern union {
Flags: u32,
Anonymous: extern struct {
_bitfield: u32,
},
},
Permanent: BOOLEAN,
};
pub const PROCESS_MITIGATION_STRICT_HANDLE_CHECK_POLICY = extern struct {
Anonymous: extern union {
Flags: u32,
Anonymous: extern struct {
_bitfield: u32,
},
},
};
pub const PROCESS_MITIGATION_SYSTEM_CALL_DISABLE_POLICY = extern struct {
Anonymous: extern union {
Flags: u32,
Anonymous: extern struct {
_bitfield: u32,
},
},
};
pub const PROCESS_MITIGATION_EXTENSION_POINT_DISABLE_POLICY = extern struct {
Anonymous: extern union {
Flags: u32,
Anonymous: extern struct {
_bitfield: u32,
},
},
};
pub const PROCESS_MITIGATION_DYNAMIC_CODE_POLICY = extern struct {
Anonymous: extern union {
Flags: u32,
Anonymous: extern struct {
_bitfield: u32,
},
},
};
pub const PROCESS_MITIGATION_CONTROL_FLOW_GUARD_POLICY = extern struct {
Anonymous: extern union {
Flags: u32,
Anonymous: extern struct {
_bitfield: u32,
},
},
};
pub const PROCESS_MITIGATION_BINARY_SIGNATURE_POLICY = extern struct {
Anonymous: extern union {
Flags: u32,
Anonymous: extern struct {
_bitfield: u32,
},
},
};
pub const PROCESS_MITIGATION_FONT_DISABLE_POLICY = extern struct {
Anonymous: extern union {
Flags: u32,
Anonymous: extern struct {
_bitfield: u32,
},
},
};
pub const PROCESS_MITIGATION_IMAGE_LOAD_POLICY = extern struct {
Anonymous: extern union {
Flags: u32,
Anonymous: extern struct {
_bitfield: u32,
},
},
};
pub const PROCESS_MITIGATION_SYSTEM_CALL_FILTER_POLICY = extern struct {
Anonymous: extern union {
Flags: u32,
Anonymous: extern struct {
_bitfield: u32,
},
},
};
pub const PROCESS_MITIGATION_PAYLOAD_RESTRICTION_POLICY = extern struct {
Anonymous: extern union {
Flags: u32,
Anonymous: extern struct {
_bitfield: u32,
},
},
};
pub const PROCESS_MITIGATION_CHILD_PROCESS_POLICY = extern struct {
Anonymous: extern union {
Flags: u32,
Anonymous: extern struct {
_bitfield: u32,
},
},
};
pub const PROCESS_MITIGATION_SIDE_CHANNEL_ISOLATION_POLICY = extern struct {
Anonymous: extern union {
Flags: u32,
Anonymous: extern struct {
_bitfield: u32,
},
},
};
pub const PROCESS_MITIGATION_USER_SHADOW_STACK_POLICY = extern struct {
Anonymous: extern union {
Flags: u32,
Anonymous: extern struct {
_bitfield: u32,
},
},
};
pub const JOBOBJECT_BASIC_ACCOUNTING_INFORMATION = extern struct {
TotalUserTime: LARGE_INTEGER,
TotalKernelTime: LARGE_INTEGER,
ThisPeriodTotalUserTime: LARGE_INTEGER,
ThisPeriodTotalKernelTime: LARGE_INTEGER,
TotalPageFaultCount: u32,
TotalProcesses: u32,
ActiveProcesses: u32,
TotalTerminatedProcesses: u32,
};
pub const JOBOBJECT_BASIC_LIMIT_INFORMATION = extern struct {
PerProcessUserTimeLimit: LARGE_INTEGER,
PerJobUserTimeLimit: LARGE_INTEGER,
LimitFlags: JOB_OBJECT_LIMIT,
MinimumWorkingSetSize: usize,
MaximumWorkingSetSize: usize,
ActiveProcessLimit: u32,
Affinity: usize,
PriorityClass: u32,
SchedulingClass: u32,
};
pub const JOBOBJECT_EXTENDED_LIMIT_INFORMATION = extern struct {
BasicLimitInformation: JOBOBJECT_BASIC_LIMIT_INFORMATION,
IoInfo: IO_COUNTERS,
ProcessMemoryLimit: usize,
JobMemoryLimit: usize,
PeakProcessMemoryUsed: usize,
PeakJobMemoryUsed: usize,
};
pub const JOBOBJECT_BASIC_PROCESS_ID_LIST = extern struct {
NumberOfAssignedProcesses: u32,
NumberOfProcessIdsInList: u32,
ProcessIdList: [1]usize,
};
pub const JOBOBJECT_BASIC_UI_RESTRICTIONS = extern struct {
UIRestrictionsClass: JOB_OBJECT_UILIMIT,
};
pub const JOBOBJECT_SECURITY_LIMIT_INFORMATION = extern struct {
SecurityLimitFlags: JOB_OBJECT_SECURITY,
JobToken: ?HANDLE,
SidsToDisable: ?*TOKEN_GROUPS,
PrivilegesToDelete: ?*TOKEN_PRIVILEGES,
RestrictedSids: ?*TOKEN_GROUPS,
};
pub const JOBOBJECT_END_OF_JOB_TIME_INFORMATION = extern struct {
EndOfJobTimeAction: JOB_OBJECT_TERMINATE_AT_END_ACTION,
};
pub const JOBOBJECT_ASSOCIATE_COMPLETION_PORT = extern struct {
CompletionKey: ?*c_void,
CompletionPort: ?HANDLE,
};
pub const JOBOBJECT_BASIC_AND_IO_ACCOUNTING_INFORMATION = extern struct {
BasicInfo: JOBOBJECT_BASIC_ACCOUNTING_INFORMATION,
IoInfo: IO_COUNTERS,
};
pub const JOBOBJECT_JOBSET_INFORMATION = extern struct {
MemberLevel: u32,
};
pub const JOBOBJECT_RATE_CONTROL_TOLERANCE = enum(i32) {
Low = 1,
Medium = 2,
High = 3,
};
pub const ToleranceLow = JOBOBJECT_RATE_CONTROL_TOLERANCE.Low;
pub const ToleranceMedium = JOBOBJECT_RATE_CONTROL_TOLERANCE.Medium;
pub const ToleranceHigh = JOBOBJECT_RATE_CONTROL_TOLERANCE.High;
pub const JOBOBJECT_RATE_CONTROL_TOLERANCE_INTERVAL = enum(i32) {
Short = 1,
Medium = 2,
Long = 3,
};
// TODO: enum 'JOBOBJECT_RATE_CONTROL_TOLERANCE_INTERVAL' has known issues with its value aliases
pub const JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION = extern struct {
IoReadBytesLimit: u64,
IoWriteBytesLimit: u64,
PerJobUserTimeLimit: LARGE_INTEGER,
JobMemoryLimit: u64,
RateControlTolerance: JOBOBJECT_RATE_CONTROL_TOLERANCE,
RateControlToleranceInterval: JOBOBJECT_RATE_CONTROL_TOLERANCE_INTERVAL,
LimitFlags: JOB_OBJECT_LIMIT,
};
pub const JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION_2 = extern struct {
IoReadBytesLimit: u64,
IoWriteBytesLimit: u64,
PerJobUserTimeLimit: LARGE_INTEGER,
Anonymous1: extern union {
JobHighMemoryLimit: u64,
JobMemoryLimit: u64,
},
Anonymous2: extern union {
RateControlTolerance: JOBOBJECT_RATE_CONTROL_TOLERANCE,
CpuRateControlTolerance: JOBOBJECT_RATE_CONTROL_TOLERANCE,
},
Anonymous3: extern union {
RateControlToleranceInterval: JOBOBJECT_RATE_CONTROL_TOLERANCE_INTERVAL,
CpuRateControlToleranceInterval: JOBOBJECT_RATE_CONTROL_TOLERANCE_INTERVAL,
},
LimitFlags: JOB_OBJECT_LIMIT,
IoRateControlTolerance: JOBOBJECT_RATE_CONTROL_TOLERANCE,
JobLowMemoryLimit: u64,
IoRateControlToleranceInterval: JOBOBJECT_RATE_CONTROL_TOLERANCE_INTERVAL,
NetRateControlTolerance: JOBOBJECT_RATE_CONTROL_TOLERANCE,
NetRateControlToleranceInterval: JOBOBJECT_RATE_CONTROL_TOLERANCE_INTERVAL,
};
pub const JOBOBJECT_LIMIT_VIOLATION_INFORMATION = extern struct {
LimitFlags: JOB_OBJECT_LIMIT,
ViolationLimitFlags: JOB_OBJECT_LIMIT,
IoReadBytes: u64,
IoReadBytesLimit: u64,
IoWriteBytes: u64,
IoWriteBytesLimit: u64,
PerJobUserTime: LARGE_INTEGER,
PerJobUserTimeLimit: LARGE_INTEGER,
JobMemory: u64,
JobMemoryLimit: u64,
RateControlTolerance: JOBOBJECT_RATE_CONTROL_TOLERANCE,
RateControlToleranceLimit: JOBOBJECT_RATE_CONTROL_TOLERANCE,
};
pub const JOBOBJECT_LIMIT_VIOLATION_INFORMATION_2 = extern struct {
LimitFlags: JOB_OBJECT_LIMIT,
ViolationLimitFlags: JOB_OBJECT_LIMIT,
IoReadBytes: u64,
IoReadBytesLimit: u64,
IoWriteBytes: u64,
IoWriteBytesLimit: u64,
PerJobUserTime: LARGE_INTEGER,
PerJobUserTimeLimit: LARGE_INTEGER,
JobMemory: u64,
Anonymous1: extern union {
JobHighMemoryLimit: u64,
JobMemoryLimit: u64,
},
Anonymous2: extern union {
RateControlTolerance: JOBOBJECT_RATE_CONTROL_TOLERANCE,
CpuRateControlTolerance: JOBOBJECT_RATE_CONTROL_TOLERANCE,
},
Anonymous3: extern union {
RateControlToleranceLimit: JOBOBJECT_RATE_CONTROL_TOLERANCE,
CpuRateControlToleranceLimit: JOBOBJECT_RATE_CONTROL_TOLERANCE,
},
JobLowMemoryLimit: u64,
IoRateControlTolerance: JOBOBJECT_RATE_CONTROL_TOLERANCE,
IoRateControlToleranceLimit: JOBOBJECT_RATE_CONTROL_TOLERANCE,
NetRateControlTolerance: JOBOBJECT_RATE_CONTROL_TOLERANCE,
NetRateControlToleranceLimit: JOBOBJECT_RATE_CONTROL_TOLERANCE,
};
pub const JOBOBJECT_CPU_RATE_CONTROL_INFORMATION = extern struct {
ControlFlags: JOB_OBJECT_CPU_RATE_CONTROL,
Anonymous: extern union {
CpuRate: u32,
Weight: u32,
Anonymous: extern struct {
MinRate: u16,
MaxRate: u16,
},
},
};
pub const JOB_OBJECT_NET_RATE_CONTROL_FLAGS = enum(i32) {
ENABLE = 1,
MAX_BANDWIDTH = 2,
DSCP_TAG = 4,
VALID_FLAGS = 7,
};
pub const JOB_OBJECT_NET_RATE_CONTROL_ENABLE = JOB_OBJECT_NET_RATE_CONTROL_FLAGS.ENABLE;
pub const JOB_OBJECT_NET_RATE_CONTROL_MAX_BANDWIDTH = JOB_OBJECT_NET_RATE_CONTROL_FLAGS.MAX_BANDWIDTH;
pub const JOB_OBJECT_NET_RATE_CONTROL_DSCP_TAG = JOB_OBJECT_NET_RATE_CONTROL_FLAGS.DSCP_TAG;
pub const JOB_OBJECT_NET_RATE_CONTROL_VALID_FLAGS = JOB_OBJECT_NET_RATE_CONTROL_FLAGS.VALID_FLAGS;
pub const JOBOBJECT_NET_RATE_CONTROL_INFORMATION = extern struct {
MaxBandwidth: u64,
ControlFlags: JOB_OBJECT_NET_RATE_CONTROL_FLAGS,
DscpTag: u8,
};
pub const JOB_OBJECT_IO_RATE_CONTROL_FLAGS = enum(i32) {
ENABLE = 1,
STANDALONE_VOLUME = 2,
FORCE_UNIT_ACCESS_ALL = 4,
FORCE_UNIT_ACCESS_ON_SOFT_CAP = 8,
VALID_FLAGS = 15,
};
pub const JOB_OBJECT_IO_RATE_CONTROL_ENABLE = JOB_OBJECT_IO_RATE_CONTROL_FLAGS.ENABLE;
pub const JOB_OBJECT_IO_RATE_CONTROL_STANDALONE_VOLUME = JOB_OBJECT_IO_RATE_CONTROL_FLAGS.STANDALONE_VOLUME;
pub const JOB_OBJECT_IO_RATE_CONTROL_FORCE_UNIT_ACCESS_ALL = JOB_OBJECT_IO_RATE_CONTROL_FLAGS.FORCE_UNIT_ACCESS_ALL;
pub const JOB_OBJECT_IO_RATE_CONTROL_FORCE_UNIT_ACCESS_ON_SOFT_CAP = JOB_OBJECT_IO_RATE_CONTROL_FLAGS.FORCE_UNIT_ACCESS_ON_SOFT_CAP;
pub const JOB_OBJECT_IO_RATE_CONTROL_VALID_FLAGS = JOB_OBJECT_IO_RATE_CONTROL_FLAGS.VALID_FLAGS;
pub const JOBOBJECT_IO_RATE_CONTROL_INFORMATION_NATIVE = extern struct {
MaxIops: i64,
MaxBandwidth: i64,
ReservationIops: i64,
VolumeName: ?PWSTR,
BaseIoSize: u32,
ControlFlags: JOB_OBJECT_IO_RATE_CONTROL_FLAGS,
VolumeNameLength: u16,
};
pub const JOBOBJECT_IO_RATE_CONTROL_INFORMATION_NATIVE_V2 = extern struct {
MaxIops: i64,
MaxBandwidth: i64,
ReservationIops: i64,
VolumeName: ?PWSTR,
BaseIoSize: u32,
ControlFlags: JOB_OBJECT_IO_RATE_CONTROL_FLAGS,
VolumeNameLength: u16,
CriticalReservationIops: i64,
ReservationBandwidth: i64,
CriticalReservationBandwidth: i64,
MaxTimePercent: i64,
ReservationTimePercent: i64,
CriticalReservationTimePercent: i64,
};
pub const JOBOBJECT_IO_RATE_CONTROL_INFORMATION_NATIVE_V3 = extern struct {
MaxIops: i64,
MaxBandwidth: i64,
ReservationIops: i64,
VolumeName: ?PWSTR,
BaseIoSize: u32,
ControlFlags: JOB_OBJECT_IO_RATE_CONTROL_FLAGS,
VolumeNameLength: u16,
CriticalReservationIops: i64,
ReservationBandwidth: i64,
CriticalReservationBandwidth: i64,
MaxTimePercent: i64,
ReservationTimePercent: i64,
CriticalReservationTimePercent: i64,
SoftMaxIops: i64,
SoftMaxBandwidth: i64,
SoftMaxTimePercent: i64,
LimitExcessNotifyIops: i64,
LimitExcessNotifyBandwidth: i64,
LimitExcessNotifyTimePercent: i64,
};
pub const JOBOBJECT_IO_ATTRIBUTION_CONTROL_FLAGS = enum(i32) {
ENABLE = 1,
DISABLE = 2,
VALID_FLAGS = 3,
};
pub const JOBOBJECT_IO_ATTRIBUTION_CONTROL_ENABLE = JOBOBJECT_IO_ATTRIBUTION_CONTROL_FLAGS.ENABLE;
pub const JOBOBJECT_IO_ATTRIBUTION_CONTROL_DISABLE = JOBOBJECT_IO_ATTRIBUTION_CONTROL_FLAGS.DISABLE;
pub const JOBOBJECT_IO_ATTRIBUTION_CONTROL_VALID_FLAGS = JOBOBJECT_IO_ATTRIBUTION_CONTROL_FLAGS.VALID_FLAGS;
pub const JOBOBJECT_IO_ATTRIBUTION_STATS = extern struct {
IoCount: usize,
TotalNonOverlappedQueueTime: u64,
TotalNonOverlappedServiceTime: u64,
TotalSize: u64,
};
pub const JOBOBJECT_IO_ATTRIBUTION_INFORMATION = extern struct {
ControlFlags: u32,
ReadStats: JOBOBJECT_IO_ATTRIBUTION_STATS,
WriteStats: JOBOBJECT_IO_ATTRIBUTION_STATS,
};
pub const JOBOBJECTINFOCLASS = enum(i32) {
JobObjectBasicAccountingInformation = 1,
JobObjectBasicLimitInformation = 2,
JobObjectBasicProcessIdList = 3,
JobObjectBasicUIRestrictions = 4,
JobObjectSecurityLimitInformation = 5,
JobObjectEndOfJobTimeInformation = 6,
JobObjectAssociateCompletionPortInformation = 7,
JobObjectBasicAndIoAccountingInformation = 8,
JobObjectExtendedLimitInformation = 9,
JobObjectJobSetInformation = 10,
JobObjectGroupInformation = 11,
JobObjectNotificationLimitInformation = 12,
JobObjectLimitViolationInformation = 13,
JobObjectGroupInformationEx = 14,
JobObjectCpuRateControlInformation = 15,
JobObjectCompletionFilter = 16,
JobObjectCompletionCounter = 17,
JobObjectReserved1Information = 18,
JobObjectReserved2Information = 19,
JobObjectReserved3Information = 20,
JobObjectReserved4Information = 21,
JobObjectReserved5Information = 22,
JobObjectReserved6Information = 23,
JobObjectReserved7Information = 24,
JobObjectReserved8Information = 25,
JobObjectReserved9Information = 26,
JobObjectReserved10Information = 27,
JobObjectReserved11Information = 28,
JobObjectReserved12Information = 29,
JobObjectReserved13Information = 30,
JobObjectReserved14Information = 31,
JobObjectNetRateControlInformation = 32,
JobObjectNotificationLimitInformation2 = 33,
JobObjectLimitViolationInformation2 = 34,
JobObjectCreateSilo = 35,
JobObjectSiloBasicInformation = 36,
JobObjectReserved15Information = 37,
JobObjectReserved16Information = 38,
JobObjectReserved17Information = 39,
JobObjectReserved18Information = 40,
JobObjectReserved19Information = 41,
JobObjectReserved20Information = 42,
JobObjectReserved21Information = 43,
JobObjectReserved22Information = 44,
JobObjectReserved23Information = 45,
JobObjectReserved24Information = 46,
JobObjectReserved25Information = 47,
MaxJobObjectInfoClass = 48,
};
pub const JobObjectBasicAccountingInformation = JOBOBJECTINFOCLASS.JobObjectBasicAccountingInformation;
pub const JobObjectBasicLimitInformation = JOBOBJECTINFOCLASS.JobObjectBasicLimitInformation;
pub const JobObjectBasicProcessIdList = JOBOBJECTINFOCLASS.JobObjectBasicProcessIdList;
pub const JobObjectBasicUIRestrictions = JOBOBJECTINFOCLASS.JobObjectBasicUIRestrictions;
pub const JobObjectSecurityLimitInformation = JOBOBJECTINFOCLASS.JobObjectSecurityLimitInformation;
pub const JobObjectEndOfJobTimeInformation = JOBOBJECTINFOCLASS.JobObjectEndOfJobTimeInformation;
pub const JobObjectAssociateCompletionPortInformation = JOBOBJECTINFOCLASS.JobObjectAssociateCompletionPortInformation;
pub const JobObjectBasicAndIoAccountingInformation = JOBOBJECTINFOCLASS.JobObjectBasicAndIoAccountingInformation;
pub const JobObjectExtendedLimitInformation = JOBOBJECTINFOCLASS.JobObjectExtendedLimitInformation;
pub const JobObjectJobSetInformation = JOBOBJECTINFOCLASS.JobObjectJobSetInformation;
pub const JobObjectGroupInformation = JOBOBJECTINFOCLASS.JobObjectGroupInformation;
pub const JobObjectNotificationLimitInformation = JOBOBJECTINFOCLASS.JobObjectNotificationLimitInformation;
pub const JobObjectLimitViolationInformation = JOBOBJECTINFOCLASS.JobObjectLimitViolationInformation;
pub const JobObjectGroupInformationEx = JOBOBJECTINFOCLASS.JobObjectGroupInformationEx;
pub const JobObjectCpuRateControlInformation = JOBOBJECTINFOCLASS.JobObjectCpuRateControlInformation;
pub const JobObjectCompletionFilter = JOBOBJECTINFOCLASS.JobObjectCompletionFilter;
pub const JobObjectCompletionCounter = JOBOBJECTINFOCLASS.JobObjectCompletionCounter;
pub const JobObjectReserved1Information = JOBOBJECTINFOCLASS.JobObjectReserved1Information;
pub const JobObjectReserved2Information = JOBOBJECTINFOCLASS.JobObjectReserved2Information;
pub const JobObjectReserved3Information = JOBOBJECTINFOCLASS.JobObjectReserved3Information;
pub const JobObjectReserved4Information = JOBOBJECTINFOCLASS.JobObjectReserved4Information;
pub const JobObjectReserved5Information = JOBOBJECTINFOCLASS.JobObjectReserved5Information;
pub const JobObjectReserved6Information = JOBOBJECTINFOCLASS.JobObjectReserved6Information;
pub const JobObjectReserved7Information = JOBOBJECTINFOCLASS.JobObjectReserved7Information;
pub const JobObjectReserved8Information = JOBOBJECTINFOCLASS.JobObjectReserved8Information;
pub const JobObjectReserved9Information = JOBOBJECTINFOCLASS.JobObjectReserved9Information;
pub const JobObjectReserved10Information = JOBOBJECTINFOCLASS.JobObjectReserved10Information;
pub const JobObjectReserved11Information = JOBOBJECTINFOCLASS.JobObjectReserved11Information;
pub const JobObjectReserved12Information = JOBOBJECTINFOCLASS.JobObjectReserved12Information;
pub const JobObjectReserved13Information = JOBOBJECTINFOCLASS.JobObjectReserved13Information;
pub const JobObjectReserved14Information = JOBOBJECTINFOCLASS.JobObjectReserved14Information;
pub const JobObjectNetRateControlInformation = JOBOBJECTINFOCLASS.JobObjectNetRateControlInformation;
pub const JobObjectNotificationLimitInformation2 = JOBOBJECTINFOCLASS.JobObjectNotificationLimitInformation2;
pub const JobObjectLimitViolationInformation2 = JOBOBJECTINFOCLASS.JobObjectLimitViolationInformation2;
pub const JobObjectCreateSilo = JOBOBJECTINFOCLASS.JobObjectCreateSilo;
pub const JobObjectSiloBasicInformation = JOBOBJECTINFOCLASS.JobObjectSiloBasicInformation;
pub const JobObjectReserved15Information = JOBOBJECTINFOCLASS.JobObjectReserved15Information;
pub const JobObjectReserved16Information = JOBOBJECTINFOCLASS.JobObjectReserved16Information;
pub const JobObjectReserved17Information = JOBOBJECTINFOCLASS.JobObjectReserved17Information;
pub const JobObjectReserved18Information = JOBOBJECTINFOCLASS.JobObjectReserved18Information;
pub const JobObjectReserved19Information = JOBOBJECTINFOCLASS.JobObjectReserved19Information;
pub const JobObjectReserved20Information = JOBOBJECTINFOCLASS.JobObjectReserved20Information;
pub const JobObjectReserved21Information = JOBOBJECTINFOCLASS.JobObjectReserved21Information;
pub const JobObjectReserved22Information = JOBOBJECTINFOCLASS.JobObjectReserved22Information;
pub const JobObjectReserved23Information = JOBOBJECTINFOCLASS.JobObjectReserved23Information;
pub const JobObjectReserved24Information = JOBOBJECTINFOCLASS.JobObjectReserved24Information;
pub const JobObjectReserved25Information = JOBOBJECTINFOCLASS.JobObjectReserved25Information;
pub const MaxJobObjectInfoClass = JOBOBJECTINFOCLASS.MaxJobObjectInfoClass;
pub const SILOOBJECT_BASIC_INFORMATION = extern struct {
SiloId: u32,
SiloParentId: u32,
NumberOfProcesses: u32,
IsInServerSilo: BOOLEAN,
Reserved: [3]u8,
};
pub const SERVERSILO_STATE = enum(i32) {
INITING = 0,
STARTED = 1,
SHUTTING_DOWN = 2,
TERMINATING = 3,
TERMINATED = 4,
};
pub const SERVERSILO_INITING = SERVERSILO_STATE.INITING;
pub const SERVERSILO_STARTED = SERVERSILO_STATE.STARTED;
pub const SERVERSILO_SHUTTING_DOWN = SERVERSILO_STATE.SHUTTING_DOWN;
pub const SERVERSILO_TERMINATING = SERVERSILO_STATE.TERMINATING;
pub const SERVERSILO_TERMINATED = SERVERSILO_STATE.TERMINATED;
pub const SERVERSILO_BASIC_INFORMATION = extern struct {
ServiceSessionId: u32,
State: SERVERSILO_STATE,
ExitStatus: u32,
IsDownlevelContainer: BOOLEAN,
ApiSetSchema: ?*c_void,
HostApiSetSchema: ?*c_void,
};
pub const PROCESSOR_CACHE_TYPE = enum(i32) {
Unified = 0,
Instruction = 1,
Data = 2,
Trace = 3,
};
pub const CacheUnified = PROCESSOR_CACHE_TYPE.Unified;
pub const CacheInstruction = PROCESSOR_CACHE_TYPE.Instruction;
pub const CacheData = PROCESSOR_CACHE_TYPE.Data;
pub const CacheTrace = PROCESSOR_CACHE_TYPE.Trace;
pub const CACHE_DESCRIPTOR = extern struct {
Level: u8,
Associativity: u8,
LineSize: u16,
Size: u32,
Type: PROCESSOR_CACHE_TYPE,
};
pub const PROCESSOR_RELATIONSHIP = extern struct {
Flags: u8,
EfficiencyClass: u8,
Reserved: [20]u8,
GroupCount: u16,
GroupMask: [1]GROUP_AFFINITY,
};
pub const NUMA_NODE_RELATIONSHIP = extern struct {
NodeNumber: u32,
Reserved: [20]u8,
GroupMask: GROUP_AFFINITY,
};
pub const CACHE_RELATIONSHIP = extern struct {
Level: u8,
Associativity: u8,
LineSize: u16,
CacheSize: u32,
Type: PROCESSOR_CACHE_TYPE,
Reserved: [20]u8,
GroupMask: GROUP_AFFINITY,
};
pub const PROCESSOR_GROUP_INFO = extern struct {
MaximumProcessorCount: u8,
ActiveProcessorCount: u8,
Reserved: [38]u8,
ActiveProcessorMask: usize,
};
pub const GROUP_RELATIONSHIP = extern struct {
MaximumGroupCount: u16,
ActiveGroupCount: u16,
Reserved: [20]u8,
GroupInfo: [1]PROCESSOR_GROUP_INFO,
};
pub const SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX = extern struct {
Relationship: LOGICAL_PROCESSOR_RELATIONSHIP,
Size: u32,
Anonymous: extern union {
Processor: PROCESSOR_RELATIONSHIP,
NumaNode: NUMA_NODE_RELATIONSHIP,
Cache: CACHE_RELATIONSHIP,
Group: GROUP_RELATIONSHIP,
},
};
pub const CPU_SET_INFORMATION_TYPE = enum(i32) {
n = 0,
};
pub const CpuSetInformation = CPU_SET_INFORMATION_TYPE.n;
pub const SYSTEM_CPU_SET_INFORMATION = extern struct {
Size: u32,
Type: CPU_SET_INFORMATION_TYPE,
Anonymous: extern union {
CpuSet: extern struct {
Id: u32,
Group: u16,
LogicalProcessorIndex: u8,
CoreIndex: u8,
LastLevelCacheIndex: u8,
NumaNodeIndex: u8,
EfficiencyClass: u8,
Anonymous1: extern union {
AllFlags: u8,
Anonymous: extern struct {
_bitfield: u8,
},
},
Anonymous2: extern union {
Reserved: u32,
SchedulingClass: u8,
},
AllocationTag: u64,
},
},
};
pub const XSTATE_FEATURE = extern struct {
Offset: u32,
Size: u32,
};
pub const XSTATE_CONFIGURATION = extern struct {
EnabledFeatures: u64,
EnabledVolatileFeatures: u64,
Size: u32,
Anonymous: extern union {
ControlFlags: u32,
Anonymous: extern struct {
_bitfield: u32,
},
},
Features: [64]XSTATE_FEATURE,
EnabledSupervisorFeatures: u64,
AlignedFeatures: u64,
AllFeatureSize: u32,
AllFeatures: [64]u32,
EnabledUserVisibleSupervisorFeatures: u64,
};
pub const CFG_CALL_TARGET_INFO = extern struct {
Offset: usize,
Flags: usize,
};
pub const MEM_ADDRESS_REQUIREMENTS = extern struct {
LowestStartingAddress: ?*c_void,
HighestEndingAddress: ?*c_void,
Alignment: usize,
};
pub const MEM_EXTENDED_PARAMETER_TYPE = enum(i32) {
InvalidType = 0,
AddressRequirements = 1,
NumaNode = 2,
PartitionHandle = 3,
UserPhysicalHandle = 4,
AttributeFlags = 5,
Max = 6,
};
pub const MemExtendedParameterInvalidType = MEM_EXTENDED_PARAMETER_TYPE.InvalidType;
pub const MemExtendedParameterAddressRequirements = MEM_EXTENDED_PARAMETER_TYPE.AddressRequirements;
pub const MemExtendedParameterNumaNode = MEM_EXTENDED_PARAMETER_TYPE.NumaNode;
pub const MemExtendedParameterPartitionHandle = MEM_EXTENDED_PARAMETER_TYPE.PartitionHandle;
pub const MemExtendedParameterUserPhysicalHandle = MEM_EXTENDED_PARAMETER_TYPE.UserPhysicalHandle;
pub const MemExtendedParameterAttributeFlags = MEM_EXTENDED_PARAMETER_TYPE.AttributeFlags;
pub const MemExtendedParameterMax = MEM_EXTENDED_PARAMETER_TYPE.Max;
pub const MEM_EXTENDED_PARAMETER = extern struct {
Anonymous1: extern struct {
_bitfield: u64,
},
Anonymous2: extern union {
ULong64: u64,
Pointer: ?*c_void,
Size: usize,
Handle: ?HANDLE,
ULong: u32,
},
};
pub const MEM_SECTION_EXTENDED_PARAMETER_TYPE = enum(i32) {
InvalidType = 0,
UserPhysicalFlags = 1,
NumaNode = 2,
Max = 3,
};
pub const MemSectionExtendedParameterInvalidType = MEM_SECTION_EXTENDED_PARAMETER_TYPE.InvalidType;
pub const MemSectionExtendedParameterUserPhysicalFlags = MEM_SECTION_EXTENDED_PARAMETER_TYPE.UserPhysicalFlags;
pub const MemSectionExtendedParameterNumaNode = MEM_SECTION_EXTENDED_PARAMETER_TYPE.NumaNode;
pub const MemSectionExtendedParameterMax = MEM_SECTION_EXTENDED_PARAMETER_TYPE.Max;
pub const FILE_SEGMENT_ELEMENT = extern union {
Buffer: ?*c_void,
Alignment: u64,
};
pub const SCRUB_DATA_INPUT = extern struct {
Size: u32,
Flags: u32,
MaximumIos: u32,
ObjectId: [4]u32,
Reserved: [25]u32,
ResumeContext: [816]u8,
};
pub const SCRUB_PARITY_EXTENT = extern struct {
Offset: i64,
Length: u64,
};
pub const SCRUB_PARITY_EXTENT_DATA = extern struct {
Size: u16,
Flags: u16,
NumberOfParityExtents: u16,
MaximumNumberOfParityExtents: u16,
ParityExtents: [1]SCRUB_PARITY_EXTENT,
};
pub const SCRUB_DATA_OUTPUT = extern struct {
Size: u32,
Flags: u32,
Status: u32,
ErrorFileOffset: u64,
ErrorLength: u64,
NumberOfBytesRepaired: u64,
NumberOfBytesFailed: u64,
InternalFileReference: u64,
ResumeContextLength: u16,
ParityExtentDataOffset: u16,
Reserved: [9]u32,
NumberOfMetadataBytesProcessed: u64,
NumberOfDataBytesProcessed: u64,
TotalNumberOfMetadataBytesInUse: u64,
TotalNumberOfDataBytesInUse: u64,
ResumeContext: [816]u8,
};
pub const SharedVirtualDiskSupportType = enum(i32) {
sUnsupported = 0,
sSupported = 1,
SnapshotsSupported = 3,
CDPSnapshotsSupported = 7,
};
pub const SharedVirtualDisksUnsupported = SharedVirtualDiskSupportType.sUnsupported;
pub const SharedVirtualDisksSupported = SharedVirtualDiskSupportType.sSupported;
pub const SharedVirtualDiskSnapshotsSupported = SharedVirtualDiskSupportType.SnapshotsSupported;
pub const SharedVirtualDiskCDPSnapshotsSupported = SharedVirtualDiskSupportType.CDPSnapshotsSupported;
pub const SharedVirtualDiskHandleState = enum(i32) {
None = 0,
FileShared = 1,
HandleShared = 3,
};
pub const SharedVirtualDiskHandleStateNone = SharedVirtualDiskHandleState.None;
pub const SharedVirtualDiskHandleStateFileShared = SharedVirtualDiskHandleState.FileShared;
pub const SharedVirtualDiskHandleStateHandleShared = SharedVirtualDiskHandleState.HandleShared;
pub const SHARED_VIRTUAL_DISK_SUPPORT = extern struct {
SharedVirtualDiskSupport: SharedVirtualDiskSupportType,
HandleState: SharedVirtualDiskHandleState,
};
pub const REARRANGE_FILE_DATA = extern struct {
SourceStartingOffset: u64,
TargetOffset: u64,
SourceFileHandle: ?HANDLE,
Length: u32,
Flags: u32,
};
pub const SHUFFLE_FILE_DATA = extern struct {
StartingOffset: i64,
Length: i64,
Flags: u32,
};
pub const NETWORK_APP_INSTANCE_EA = extern struct {
AppInstanceID: Guid,
CsvFlags: u32,
};
pub const DEVICE_POWER_STATE = enum(i32) {
Unspecified = 0,
D0 = 1,
D1 = 2,
D2 = 3,
D3 = 4,
Maximum = 5,
};
pub const PowerDeviceUnspecified = DEVICE_POWER_STATE.Unspecified;
pub const PowerDeviceD0 = DEVICE_POWER_STATE.D0;
pub const PowerDeviceD1 = DEVICE_POWER_STATE.D1;
pub const PowerDeviceD2 = DEVICE_POWER_STATE.D2;
pub const PowerDeviceD3 = DEVICE_POWER_STATE.D3;
pub const PowerDeviceMaximum = DEVICE_POWER_STATE.Maximum;
pub const MONITOR_DISPLAY_STATE = enum(i32) {
Off = 0,
On = 1,
Dim = 2,
};
pub const PowerMonitorOff = MONITOR_DISPLAY_STATE.Off;
pub const PowerMonitorOn = MONITOR_DISPLAY_STATE.On;
pub const PowerMonitorDim = MONITOR_DISPLAY_STATE.Dim;
pub const USER_ACTIVITY_PRESENCE = enum(i32) {
Present = 0,
NotPresent = 1,
Inactive = 2,
Maximum = 3,
// Invalid = 3, this enum value conflicts with Maximum
};
pub const PowerUserPresent = USER_ACTIVITY_PRESENCE.Present;
pub const PowerUserNotPresent = USER_ACTIVITY_PRESENCE.NotPresent;
pub const PowerUserInactive = USER_ACTIVITY_PRESENCE.Inactive;
pub const PowerUserMaximum = USER_ACTIVITY_PRESENCE.Maximum;
pub const PowerUserInvalid = USER_ACTIVITY_PRESENCE.Maximum;
pub const POWER_REQUEST_TYPE = enum(i32) {
DisplayRequired = 0,
SystemRequired = 1,
AwayModeRequired = 2,
ExecutionRequired = 3,
};
pub const PowerRequestDisplayRequired = POWER_REQUEST_TYPE.DisplayRequired;
pub const PowerRequestSystemRequired = POWER_REQUEST_TYPE.SystemRequired;
pub const PowerRequestAwayModeRequired = POWER_REQUEST_TYPE.AwayModeRequired;
pub const PowerRequestExecutionRequired = POWER_REQUEST_TYPE.ExecutionRequired;
pub const CM_Power_Data_s = extern struct {
PD_Size: u32,
PD_MostRecentPowerState: DEVICE_POWER_STATE,
PD_Capabilities: u32,
PD_D1Latency: u32,
PD_D2Latency: u32,
PD_D3Latency: u32,
PD_PowerStateMapping: [7]DEVICE_POWER_STATE,
PD_DeepestSystemWake: SYSTEM_POWER_STATE,
};
pub const POWER_INFORMATION_LEVEL = enum(i32) {
SystemPowerPolicyAc = 0,
SystemPowerPolicyDc = 1,
VerifySystemPolicyAc = 2,
VerifySystemPolicyDc = 3,
SystemPowerCapabilities = 4,
SystemBatteryState = 5,
SystemPowerStateHandler = 6,
ProcessorStateHandler = 7,
SystemPowerPolicyCurrent = 8,
AdministratorPowerPolicy = 9,
SystemReserveHiberFile = 10,
ProcessorInformation = 11,
SystemPowerInformation = 12,
ProcessorStateHandler2 = 13,
LastWakeTime = 14,
LastSleepTime = 15,
SystemExecutionState = 16,
SystemPowerStateNotifyHandler = 17,
ProcessorPowerPolicyAc = 18,
ProcessorPowerPolicyDc = 19,
VerifyProcessorPowerPolicyAc = 20,
VerifyProcessorPowerPolicyDc = 21,
ProcessorPowerPolicyCurrent = 22,
SystemPowerStateLogging = 23,
SystemPowerLoggingEntry = 24,
SetPowerSettingValue = 25,
NotifyUserPowerSetting = 26,
PowerInformationLevelUnused0 = 27,
SystemMonitorHiberBootPowerOff = 28,
SystemVideoState = 29,
TraceApplicationPowerMessage = 30,
TraceApplicationPowerMessageEnd = 31,
ProcessorPerfStates = 32,
ProcessorIdleStates = 33,
ProcessorCap = 34,
SystemWakeSource = 35,
SystemHiberFileInformation = 36,
TraceServicePowerMessage = 37,
ProcessorLoad = 38,
PowerShutdownNotification = 39,
MonitorCapabilities = 40,
SessionPowerInit = 41,
SessionDisplayState = 42,
PowerRequestCreate = 43,
PowerRequestAction = 44,
GetPowerRequestList = 45,
ProcessorInformationEx = 46,
NotifyUserModeLegacyPowerEvent = 47,
GroupPark = 48,
ProcessorIdleDomains = 49,
WakeTimerList = 50,
SystemHiberFileSize = 51,
ProcessorIdleStatesHv = 52,
ProcessorPerfStatesHv = 53,
ProcessorPerfCapHv = 54,
ProcessorSetIdle = 55,
LogicalProcessorIdling = 56,
UserPresence = 57,
PowerSettingNotificationName = 58,
GetPowerSettingValue = 59,
IdleResiliency = 60,
SessionRITState = 61,
SessionConnectNotification = 62,
SessionPowerCleanup = 63,
SessionLockState = 64,
SystemHiberbootState = 65,
PlatformInformation = 66,
PdcInvocation = 67,
MonitorInvocation = 68,
FirmwareTableInformationRegistered = 69,
SetShutdownSelectedTime = 70,
SuspendResumeInvocation = 71,
PlmPowerRequestCreate = 72,
ScreenOff = 73,
CsDeviceNotification = 74,
PlatformRole = 75,
LastResumePerformance = 76,
DisplayBurst = 77,
ExitLatencySamplingPercentage = 78,
RegisterSpmPowerSettings = 79,
PlatformIdleStates = 80,
ProcessorIdleVeto = 81,
PlatformIdleVeto = 82,
SystemBatteryStatePrecise = 83,
ThermalEvent = 84,
PowerRequestActionInternal = 85,
BatteryDeviceState = 86,
PowerInformationInternal = 87,
ThermalStandby = 88,
SystemHiberFileType = 89,
PhysicalPowerButtonPress = 90,
QueryPotentialDripsConstraint = 91,
EnergyTrackerCreate = 92,
EnergyTrackerQuery = 93,
UpdateBlackBoxRecorder = 94,
SessionAllowExternalDmaDevices = 95,
PowerInformationLevelMaximum = 96,
};
pub const SystemPowerPolicyAc = POWER_INFORMATION_LEVEL.SystemPowerPolicyAc;
pub const SystemPowerPolicyDc = POWER_INFORMATION_LEVEL.SystemPowerPolicyDc;
pub const VerifySystemPolicyAc = POWER_INFORMATION_LEVEL.VerifySystemPolicyAc;
pub const VerifySystemPolicyDc = POWER_INFORMATION_LEVEL.VerifySystemPolicyDc;
pub const SystemPowerCapabilities = POWER_INFORMATION_LEVEL.SystemPowerCapabilities;
pub const SystemBatteryState = POWER_INFORMATION_LEVEL.SystemBatteryState;
pub const SystemPowerStateHandler = POWER_INFORMATION_LEVEL.SystemPowerStateHandler;
pub const ProcessorStateHandler = POWER_INFORMATION_LEVEL.ProcessorStateHandler;
pub const SystemPowerPolicyCurrent = POWER_INFORMATION_LEVEL.SystemPowerPolicyCurrent;
pub const AdministratorPowerPolicy = POWER_INFORMATION_LEVEL.AdministratorPowerPolicy;
pub const SystemReserveHiberFile = POWER_INFORMATION_LEVEL.SystemReserveHiberFile;
pub const ProcessorInformation = POWER_INFORMATION_LEVEL.ProcessorInformation;
pub const SystemPowerInformation = POWER_INFORMATION_LEVEL.SystemPowerInformation;
pub const ProcessorStateHandler2 = POWER_INFORMATION_LEVEL.ProcessorStateHandler2;
pub const LastWakeTime = POWER_INFORMATION_LEVEL.LastWakeTime;
pub const LastSleepTime = POWER_INFORMATION_LEVEL.LastSleepTime;
pub const SystemExecutionState = POWER_INFORMATION_LEVEL.SystemExecutionState;
pub const SystemPowerStateNotifyHandler = POWER_INFORMATION_LEVEL.SystemPowerStateNotifyHandler;
pub const ProcessorPowerPolicyAc = POWER_INFORMATION_LEVEL.ProcessorPowerPolicyAc;
pub const ProcessorPowerPolicyDc = POWER_INFORMATION_LEVEL.ProcessorPowerPolicyDc;
pub const VerifyProcessorPowerPolicyAc = POWER_INFORMATION_LEVEL.VerifyProcessorPowerPolicyAc;
pub const VerifyProcessorPowerPolicyDc = POWER_INFORMATION_LEVEL.VerifyProcessorPowerPolicyDc;
pub const ProcessorPowerPolicyCurrent = POWER_INFORMATION_LEVEL.ProcessorPowerPolicyCurrent;
pub const SystemPowerStateLogging = POWER_INFORMATION_LEVEL.SystemPowerStateLogging;
pub const SystemPowerLoggingEntry = POWER_INFORMATION_LEVEL.SystemPowerLoggingEntry;
pub const SetPowerSettingValue = POWER_INFORMATION_LEVEL.SetPowerSettingValue;
pub const NotifyUserPowerSetting = POWER_INFORMATION_LEVEL.NotifyUserPowerSetting;
pub const PowerInformationLevelUnused0 = POWER_INFORMATION_LEVEL.PowerInformationLevelUnused0;
pub const SystemMonitorHiberBootPowerOff = POWER_INFORMATION_LEVEL.SystemMonitorHiberBootPowerOff;
pub const SystemVideoState = POWER_INFORMATION_LEVEL.SystemVideoState;
pub const TraceApplicationPowerMessage = POWER_INFORMATION_LEVEL.TraceApplicationPowerMessage;
pub const TraceApplicationPowerMessageEnd = POWER_INFORMATION_LEVEL.TraceApplicationPowerMessageEnd;
pub const ProcessorPerfStates = POWER_INFORMATION_LEVEL.ProcessorPerfStates;
pub const ProcessorIdleStates = POWER_INFORMATION_LEVEL.ProcessorIdleStates;
pub const ProcessorCap = POWER_INFORMATION_LEVEL.ProcessorCap;
pub const SystemWakeSource = POWER_INFORMATION_LEVEL.SystemWakeSource;
pub const SystemHiberFileInformation = POWER_INFORMATION_LEVEL.SystemHiberFileInformation;
pub const TraceServicePowerMessage = POWER_INFORMATION_LEVEL.TraceServicePowerMessage;
pub const ProcessorLoad = POWER_INFORMATION_LEVEL.ProcessorLoad;
pub const PowerShutdownNotification = POWER_INFORMATION_LEVEL.PowerShutdownNotification;
pub const MonitorCapabilities = POWER_INFORMATION_LEVEL.MonitorCapabilities;
pub const SessionPowerInit = POWER_INFORMATION_LEVEL.SessionPowerInit;
pub const SessionDisplayState = POWER_INFORMATION_LEVEL.SessionDisplayState;
pub const PowerRequestCreate = POWER_INFORMATION_LEVEL.PowerRequestCreate;
pub const PowerRequestAction = POWER_INFORMATION_LEVEL.PowerRequestAction;
pub const GetPowerRequestList = POWER_INFORMATION_LEVEL.GetPowerRequestList;
pub const ProcessorInformationEx = POWER_INFORMATION_LEVEL.ProcessorInformationEx;
pub const NotifyUserModeLegacyPowerEvent = POWER_INFORMATION_LEVEL.NotifyUserModeLegacyPowerEvent;
pub const GroupPark = POWER_INFORMATION_LEVEL.GroupPark;
pub const ProcessorIdleDomains = POWER_INFORMATION_LEVEL.ProcessorIdleDomains;
pub const WakeTimerList = POWER_INFORMATION_LEVEL.WakeTimerList;
pub const SystemHiberFileSize = POWER_INFORMATION_LEVEL.SystemHiberFileSize;
pub const ProcessorIdleStatesHv = POWER_INFORMATION_LEVEL.ProcessorIdleStatesHv;
pub const ProcessorPerfStatesHv = POWER_INFORMATION_LEVEL.ProcessorPerfStatesHv;
pub const ProcessorPerfCapHv = POWER_INFORMATION_LEVEL.ProcessorPerfCapHv;
pub const ProcessorSetIdle = POWER_INFORMATION_LEVEL.ProcessorSetIdle;
pub const LogicalProcessorIdling = POWER_INFORMATION_LEVEL.LogicalProcessorIdling;
pub const UserPresence = POWER_INFORMATION_LEVEL.UserPresence;
pub const PowerSettingNotificationName = POWER_INFORMATION_LEVEL.PowerSettingNotificationName;
pub const GetPowerSettingValue = POWER_INFORMATION_LEVEL.GetPowerSettingValue;
pub const IdleResiliency = POWER_INFORMATION_LEVEL.IdleResiliency;
pub const SessionRITState = POWER_INFORMATION_LEVEL.SessionRITState;
pub const SessionConnectNotification = POWER_INFORMATION_LEVEL.SessionConnectNotification;
pub const SessionPowerCleanup = POWER_INFORMATION_LEVEL.SessionPowerCleanup;
pub const SessionLockState = POWER_INFORMATION_LEVEL.SessionLockState;
pub const SystemHiberbootState = POWER_INFORMATION_LEVEL.SystemHiberbootState;
pub const PlatformInformation = POWER_INFORMATION_LEVEL.PlatformInformation;
pub const PdcInvocation = POWER_INFORMATION_LEVEL.PdcInvocation;
pub const MonitorInvocation = POWER_INFORMATION_LEVEL.MonitorInvocation;
pub const FirmwareTableInformationRegistered = POWER_INFORMATION_LEVEL.FirmwareTableInformationRegistered;
pub const SetShutdownSelectedTime = POWER_INFORMATION_LEVEL.SetShutdownSelectedTime;
pub const SuspendResumeInvocation = POWER_INFORMATION_LEVEL.SuspendResumeInvocation;
pub const PlmPowerRequestCreate = POWER_INFORMATION_LEVEL.PlmPowerRequestCreate;
pub const ScreenOff = POWER_INFORMATION_LEVEL.ScreenOff;
pub const CsDeviceNotification = POWER_INFORMATION_LEVEL.CsDeviceNotification;
pub const PlatformRole = POWER_INFORMATION_LEVEL.PlatformRole;
pub const LastResumePerformance = POWER_INFORMATION_LEVEL.LastResumePerformance;
pub const DisplayBurst = POWER_INFORMATION_LEVEL.DisplayBurst;
pub const ExitLatencySamplingPercentage = POWER_INFORMATION_LEVEL.ExitLatencySamplingPercentage;
pub const RegisterSpmPowerSettings = POWER_INFORMATION_LEVEL.RegisterSpmPowerSettings;
pub const PlatformIdleStates = POWER_INFORMATION_LEVEL.PlatformIdleStates;
pub const ProcessorIdleVeto = POWER_INFORMATION_LEVEL.ProcessorIdleVeto;
pub const PlatformIdleVeto = POWER_INFORMATION_LEVEL.PlatformIdleVeto;
pub const SystemBatteryStatePrecise = POWER_INFORMATION_LEVEL.SystemBatteryStatePrecise;
pub const ThermalEvent = POWER_INFORMATION_LEVEL.ThermalEvent;
pub const PowerRequestActionInternal = POWER_INFORMATION_LEVEL.PowerRequestActionInternal;
pub const BatteryDeviceState = POWER_INFORMATION_LEVEL.BatteryDeviceState;
pub const PowerInformationInternal = POWER_INFORMATION_LEVEL.PowerInformationInternal;
pub const ThermalStandby = POWER_INFORMATION_LEVEL.ThermalStandby;
pub const SystemHiberFileType = POWER_INFORMATION_LEVEL.SystemHiberFileType;
pub const PhysicalPowerButtonPress = POWER_INFORMATION_LEVEL.PhysicalPowerButtonPress;
pub const QueryPotentialDripsConstraint = POWER_INFORMATION_LEVEL.QueryPotentialDripsConstraint;
pub const EnergyTrackerCreate = POWER_INFORMATION_LEVEL.EnergyTrackerCreate;
pub const EnergyTrackerQuery = POWER_INFORMATION_LEVEL.EnergyTrackerQuery;
pub const UpdateBlackBoxRecorder = POWER_INFORMATION_LEVEL.UpdateBlackBoxRecorder;
pub const SessionAllowExternalDmaDevices = POWER_INFORMATION_LEVEL.SessionAllowExternalDmaDevices;
pub const PowerInformationLevelMaximum = POWER_INFORMATION_LEVEL.PowerInformationLevelMaximum;
pub const POWER_USER_PRESENCE_TYPE = enum(i32) {
NotPresent = 0,
Present = 1,
Unknown = 255,
};
pub const UserNotPresent = POWER_USER_PRESENCE_TYPE.NotPresent;
pub const UserPresent = POWER_USER_PRESENCE_TYPE.Present;
pub const UserUnknown = POWER_USER_PRESENCE_TYPE.Unknown;
pub const POWER_USER_PRESENCE = extern struct {
UserPresence: POWER_USER_PRESENCE_TYPE,
};
pub const POWER_SESSION_CONNECT = extern struct {
Connected: BOOLEAN,
Console: BOOLEAN,
};
pub const POWER_SESSION_TIMEOUTS = extern struct {
InputTimeout: u32,
DisplayTimeout: u32,
};
pub const POWER_SESSION_RIT_STATE = extern struct {
Active: BOOLEAN,
LastInputTime: u32,
};
pub const POWER_SESSION_WINLOGON = extern struct {
SessionId: u32,
Console: BOOLEAN,
Locked: BOOLEAN,
};
pub const POWER_SESSION_ALLOW_EXTERNAL_DMA_DEVICES = extern struct {
IsAllowed: BOOLEAN,
};
pub const POWER_IDLE_RESILIENCY = extern struct {
CoalescingTimeout: u32,
IdleResiliencyPeriod: u32,
};
pub const POWER_MONITOR_REQUEST_REASON = enum(i32) {
Unknown = 0,
PowerButton = 1,
RemoteConnection = 2,
ScMonitorpower = 3,
UserInput = 4,
AcDcDisplayBurst = 5,
UserDisplayBurst = 6,
PoSetSystemState = 7,
SetThreadExecutionState = 8,
FullWake = 9,
SessionUnlock = 10,
ScreenOffRequest = 11,
IdleTimeout = 12,
PolicyChange = 13,
SleepButton = 14,
Lid = 15,
BatteryCountChange = 16,
GracePeriod = 17,
PnP = 18,
DP = 19,
SxTransition = 20,
SystemIdle = 21,
NearProximity = 22,
ThermalStandby = 23,
ResumePdc = 24,
ResumeS4 = 25,
Terminal = 26,
PdcSignal = 27,
AcDcDisplayBurstSuppressed = 28,
SystemStateEntered = 29,
Winrt = 30,
UserInputKeyboard = 31,
UserInputMouse = 32,
UserInputTouch = 33,
UserInputPen = 34,
UserInputAccelerometer = 35,
UserInputHid = 36,
UserInputPoUserPresent = 37,
UserInputSessionSwitch = 38,
UserInputInitialization = 39,
PdcSignalWindowsMobilePwrNotif = 40,
PdcSignalWindowsMobileShell = 41,
PdcSignalHeyCortana = 42,
PdcSignalHolographicShell = 43,
PdcSignalFingerprint = 44,
DirectedDrips = 45,
Dim = 46,
BuiltinPanel = 47,
DisplayRequiredUnDim = 48,
BatteryCountChangeSuppressed = 49,
ResumeModernStandby = 50,
Max = 51,
};
pub const MonitorRequestReasonUnknown = POWER_MONITOR_REQUEST_REASON.Unknown;
pub const MonitorRequestReasonPowerButton = POWER_MONITOR_REQUEST_REASON.PowerButton;
pub const MonitorRequestReasonRemoteConnection = POWER_MONITOR_REQUEST_REASON.RemoteConnection;
pub const MonitorRequestReasonScMonitorpower = POWER_MONITOR_REQUEST_REASON.ScMonitorpower;
pub const MonitorRequestReasonUserInput = POWER_MONITOR_REQUEST_REASON.UserInput;
pub const MonitorRequestReasonAcDcDisplayBurst = POWER_MONITOR_REQUEST_REASON.AcDcDisplayBurst;
pub const MonitorRequestReasonUserDisplayBurst = POWER_MONITOR_REQUEST_REASON.UserDisplayBurst;
pub const MonitorRequestReasonPoSetSystemState = POWER_MONITOR_REQUEST_REASON.PoSetSystemState;
pub const MonitorRequestReasonSetThreadExecutionState = POWER_MONITOR_REQUEST_REASON.SetThreadExecutionState;
pub const MonitorRequestReasonFullWake = POWER_MONITOR_REQUEST_REASON.FullWake;
pub const MonitorRequestReasonSessionUnlock = POWER_MONITOR_REQUEST_REASON.SessionUnlock;
pub const MonitorRequestReasonScreenOffRequest = POWER_MONITOR_REQUEST_REASON.ScreenOffRequest;
pub const MonitorRequestReasonIdleTimeout = POWER_MONITOR_REQUEST_REASON.IdleTimeout;
pub const MonitorRequestReasonPolicyChange = POWER_MONITOR_REQUEST_REASON.PolicyChange;
pub const MonitorRequestReasonSleepButton = POWER_MONITOR_REQUEST_REASON.SleepButton;
pub const MonitorRequestReasonLid = POWER_MONITOR_REQUEST_REASON.Lid;
pub const MonitorRequestReasonBatteryCountChange = POWER_MONITOR_REQUEST_REASON.BatteryCountChange;
pub const MonitorRequestReasonGracePeriod = POWER_MONITOR_REQUEST_REASON.GracePeriod;
pub const MonitorRequestReasonPnP = POWER_MONITOR_REQUEST_REASON.PnP;
pub const MonitorRequestReasonDP = POWER_MONITOR_REQUEST_REASON.DP;
pub const MonitorRequestReasonSxTransition = POWER_MONITOR_REQUEST_REASON.SxTransition;
pub const MonitorRequestReasonSystemIdle = POWER_MONITOR_REQUEST_REASON.SystemIdle;
pub const MonitorRequestReasonNearProximity = POWER_MONITOR_REQUEST_REASON.NearProximity;
pub const MonitorRequestReasonThermalStandby = POWER_MONITOR_REQUEST_REASON.ThermalStandby;
pub const MonitorRequestReasonResumePdc = POWER_MONITOR_REQUEST_REASON.ResumePdc;
pub const MonitorRequestReasonResumeS4 = POWER_MONITOR_REQUEST_REASON.ResumeS4;
pub const MonitorRequestReasonTerminal = POWER_MONITOR_REQUEST_REASON.Terminal;
pub const MonitorRequestReasonPdcSignal = POWER_MONITOR_REQUEST_REASON.PdcSignal;
pub const MonitorRequestReasonAcDcDisplayBurstSuppressed = POWER_MONITOR_REQUEST_REASON.AcDcDisplayBurstSuppressed;
pub const MonitorRequestReasonSystemStateEntered = POWER_MONITOR_REQUEST_REASON.SystemStateEntered;
pub const MonitorRequestReasonWinrt = POWER_MONITOR_REQUEST_REASON.Winrt;
pub const MonitorRequestReasonUserInputKeyboard = POWER_MONITOR_REQUEST_REASON.UserInputKeyboard;
pub const MonitorRequestReasonUserInputMouse = POWER_MONITOR_REQUEST_REASON.UserInputMouse;
pub const MonitorRequestReasonUserInputTouch = POWER_MONITOR_REQUEST_REASON.UserInputTouch;
pub const MonitorRequestReasonUserInputPen = POWER_MONITOR_REQUEST_REASON.UserInputPen;
pub const MonitorRequestReasonUserInputAccelerometer = POWER_MONITOR_REQUEST_REASON.UserInputAccelerometer;
pub const MonitorRequestReasonUserInputHid = POWER_MONITOR_REQUEST_REASON.UserInputHid;
pub const MonitorRequestReasonUserInputPoUserPresent = POWER_MONITOR_REQUEST_REASON.UserInputPoUserPresent;
pub const MonitorRequestReasonUserInputSessionSwitch = POWER_MONITOR_REQUEST_REASON.UserInputSessionSwitch;
pub const MonitorRequestReasonUserInputInitialization = POWER_MONITOR_REQUEST_REASON.UserInputInitialization;
pub const MonitorRequestReasonPdcSignalWindowsMobilePwrNotif = POWER_MONITOR_REQUEST_REASON.PdcSignalWindowsMobilePwrNotif;
pub const MonitorRequestReasonPdcSignalWindowsMobileShell = POWER_MONITOR_REQUEST_REASON.PdcSignalWindowsMobileShell;
pub const MonitorRequestReasonPdcSignalHeyCortana = POWER_MONITOR_REQUEST_REASON.PdcSignalHeyCortana;
pub const MonitorRequestReasonPdcSignalHolographicShell = POWER_MONITOR_REQUEST_REASON.PdcSignalHolographicShell;
pub const MonitorRequestReasonPdcSignalFingerprint = POWER_MONITOR_REQUEST_REASON.PdcSignalFingerprint;
pub const MonitorRequestReasonDirectedDrips = POWER_MONITOR_REQUEST_REASON.DirectedDrips;
pub const MonitorRequestReasonDim = POWER_MONITOR_REQUEST_REASON.Dim;
pub const MonitorRequestReasonBuiltinPanel = POWER_MONITOR_REQUEST_REASON.BuiltinPanel;
pub const MonitorRequestReasonDisplayRequiredUnDim = POWER_MONITOR_REQUEST_REASON.DisplayRequiredUnDim;
pub const MonitorRequestReasonBatteryCountChangeSuppressed = POWER_MONITOR_REQUEST_REASON.BatteryCountChangeSuppressed;
pub const MonitorRequestReasonResumeModernStandby = POWER_MONITOR_REQUEST_REASON.ResumeModernStandby;
pub const MonitorRequestReasonMax = POWER_MONITOR_REQUEST_REASON.Max;
pub const POWER_MONITOR_REQUEST_TYPE = enum(i32) {
Off = 0,
OnAndPresent = 1,
ToggleOn = 2,
};
pub const MonitorRequestTypeOff = POWER_MONITOR_REQUEST_TYPE.Off;
pub const MonitorRequestTypeOnAndPresent = POWER_MONITOR_REQUEST_TYPE.OnAndPresent;
pub const MonitorRequestTypeToggleOn = POWER_MONITOR_REQUEST_TYPE.ToggleOn;
pub const POWER_MONITOR_INVOCATION = extern struct {
Console: BOOLEAN,
RequestReason: POWER_MONITOR_REQUEST_REASON,
};
pub const RESUME_PERFORMANCE = extern struct {
PostTimeMs: u32,
TotalResumeTimeMs: u64,
ResumeCompleteTimestamp: u64,
};
pub const SET_POWER_SETTING_VALUE = extern struct {
Version: u32,
Guid: Guid,
PowerCondition: SYSTEM_POWER_CONDITION,
DataLength: u32,
Data: [1]u8,
};
pub const NOTIFY_USER_POWER_SETTING = extern struct {
Guid: Guid,
};
pub const APPLICATIONLAUNCH_SETTING_VALUE = extern struct {
ActivationTime: LARGE_INTEGER,
Flags: u32,
ButtonInstanceID: u32,
};
pub const POWER_PLATFORM_INFORMATION = extern struct {
AoAc: BOOLEAN,
};
pub const PPM_WMI_LEGACY_PERFSTATE = extern struct {
Frequency: u32,
Flags: u32,
PercentFrequency: u32,
};
pub const PPM_WMI_IDLE_STATE = extern struct {
Latency: u32,
Power: u32,
TimeCheck: u32,
PromotePercent: u8,
DemotePercent: u8,
StateType: u8,
Reserved: u8,
StateFlags: u32,
Context: u32,
IdleHandler: u32,
Reserved1: u32,
};
pub const PPM_WMI_IDLE_STATES = extern struct {
Type: u32,
Count: u32,
TargetState: u32,
OldState: u32,
TargetProcessors: u64,
State: [1]PPM_WMI_IDLE_STATE,
};
pub const PPM_WMI_IDLE_STATES_EX = extern struct {
Type: u32,
Count: u32,
TargetState: u32,
OldState: u32,
TargetProcessors: ?*c_void,
State: [1]PPM_WMI_IDLE_STATE,
};
pub const PPM_WMI_PERF_STATE = extern struct {
Frequency: u32,
Power: u32,
PercentFrequency: u8,
IncreaseLevel: u8,
DecreaseLevel: u8,
Type: u8,
IncreaseTime: u32,
DecreaseTime: u32,
Control: u64,
Status: u64,
HitCount: u32,
Reserved1: u32,
Reserved2: u64,
Reserved3: u64,
};
pub const PPM_WMI_PERF_STATES = extern struct {
Count: u32,
MaxFrequency: u32,
CurrentState: u32,
MaxPerfState: u32,
MinPerfState: u32,
LowestPerfState: u32,
ThermalConstraint: u32,
BusyAdjThreshold: u8,
PolicyType: u8,
Type: u8,
Reserved: u8,
TimerInterval: u32,
TargetProcessors: u64,
PStateHandler: u32,
PStateContext: u32,
TStateHandler: u32,
TStateContext: u32,
FeedbackHandler: u32,
Reserved1: u32,
Reserved2: u64,
State: [1]PPM_WMI_PERF_STATE,
};
pub const PPM_WMI_PERF_STATES_EX = extern struct {
Count: u32,
MaxFrequency: u32,
CurrentState: u32,
MaxPerfState: u32,
MinPerfState: u32,
LowestPerfState: u32,
ThermalConstraint: u32,
BusyAdjThreshold: u8,
PolicyType: u8,
Type: u8,
Reserved: u8,
TimerInterval: u32,
TargetProcessors: ?*c_void,
PStateHandler: u32,
PStateContext: u32,
TStateHandler: u32,
TStateContext: u32,
FeedbackHandler: u32,
Reserved1: u32,
Reserved2: u64,
State: [1]PPM_WMI_PERF_STATE,
};
pub const PPM_IDLE_STATE_ACCOUNTING = extern struct {
IdleTransitions: u32,
FailedTransitions: u32,
InvalidBucketIndex: u32,
TotalTime: u64,
IdleTimeBuckets: [6]u32,
};
pub const PPM_IDLE_ACCOUNTING = extern struct {
StateCount: u32,
TotalTransitions: u32,
ResetCount: u32,
StartTime: u64,
State: [1]PPM_IDLE_STATE_ACCOUNTING,
};
pub const PPM_IDLE_STATE_BUCKET_EX = extern struct {
TotalTimeUs: u64,
MinTimeUs: u32,
MaxTimeUs: u32,
Count: u32,
};
pub const PPM_IDLE_STATE_ACCOUNTING_EX = extern struct {
TotalTime: u64,
IdleTransitions: u32,
FailedTransitions: u32,
InvalidBucketIndex: u32,
MinTimeUs: u32,
MaxTimeUs: u32,
CancelledTransitions: u32,
IdleTimeBuckets: [16]PPM_IDLE_STATE_BUCKET_EX,
};
pub const PPM_IDLE_ACCOUNTING_EX = extern struct {
StateCount: u32,
TotalTransitions: u32,
ResetCount: u32,
AbortCount: u32,
StartTime: u64,
State: [1]PPM_IDLE_STATE_ACCOUNTING_EX,
};
pub const PPM_PERFSTATE_EVENT = extern struct {
State: u32,
Status: u32,
Latency: u32,
Speed: u32,
Processor: u32,
};
pub const PPM_PERFSTATE_DOMAIN_EVENT = extern struct {
State: u32,
Latency: u32,
Speed: u32,
Processors: u64,
};
pub const PPM_IDLESTATE_EVENT = extern struct {
NewState: u32,
OldState: u32,
Processors: u64,
};
pub const PPM_THERMALCHANGE_EVENT = extern struct {
ThermalConstraint: u32,
Processors: u64,
};
pub const PPM_THERMAL_POLICY_EVENT = extern struct {
Mode: u8,
Processors: u64,
};
pub const PROCESSOR_IDLESTATE_INFO = extern struct {
TimeCheck: u32,
DemotePercent: u8,
PromotePercent: u8,
Spare: [2]u8,
};
pub const PROCESSOR_IDLESTATE_POLICY = extern struct {
Revision: u16,
Flags: extern union {
AsWORD: u16,
Anonymous: extern struct {
_bitfield: u16,
},
},
PolicyCount: u32,
Policy: [3]PROCESSOR_IDLESTATE_INFO,
};
pub const PROCESSOR_PERFSTATE_POLICY = extern struct {
Revision: u32,
MaxThrottle: u8,
MinThrottle: u8,
BusyAdjThreshold: u8,
Anonymous: extern union {
Spare: u8,
Flags: extern union {
AsBYTE: u8,
Anonymous: extern struct {
_bitfield: u8,
},
},
},
TimeCheck: u32,
IncreaseTime: u32,
DecreaseTime: u32,
IncreasePercent: u32,
DecreasePercent: u32,
};
pub const HIBERFILE_BUCKET_SIZE = enum(i32) {
@"1GB" = 0,
@"2GB" = 1,
@"4GB" = 2,
@"8GB" = 3,
@"16GB" = 4,
@"32GB" = 5,
Unlimited = 6,
Max = 7,
};
pub const HiberFileBucket1GB = HIBERFILE_BUCKET_SIZE.@"1GB";
pub const HiberFileBucket2GB = HIBERFILE_BUCKET_SIZE.@"2GB";
pub const HiberFileBucket4GB = HIBERFILE_BUCKET_SIZE.@"4GB";
pub const HiberFileBucket8GB = HIBERFILE_BUCKET_SIZE.@"8GB";
pub const HiberFileBucket16GB = HIBERFILE_BUCKET_SIZE.@"16GB";
pub const HiberFileBucket32GB = HIBERFILE_BUCKET_SIZE.@"32GB";
pub const HiberFileBucketUnlimited = HIBERFILE_BUCKET_SIZE.Unlimited;
pub const HiberFileBucketMax = HIBERFILE_BUCKET_SIZE.Max;
pub const HIBERFILE_BUCKET = extern struct {
MaxPhysicalMemory: u64,
PhysicalMemoryPercent: [3]u32,
};
pub const IMAGE_DOS_HEADER = extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
e_magic: u16,
e_cblp: u16,
e_cp: u16,
e_crlc: u16,
e_cparhdr: u16,
e_minalloc: u16,
e_maxalloc: u16,
e_ss: u16,
e_sp: u16,
e_csum: u16,
e_ip: u16,
e_cs: u16,
e_lfarlc: u16,
e_ovno: u16,
e_res: [4]u16,
e_oemid: u16,
e_oeminfo: u16,
e_res2: [10]u16,
e_lfanew: i32,
};
pub const IMAGE_OS2_HEADER = extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
ne_magic: u16,
ne_ver: CHAR,
ne_rev: CHAR,
ne_enttab: u16,
ne_cbenttab: u16,
ne_crc: i32,
ne_flags: u16,
ne_autodata: u16,
ne_heap: u16,
ne_stack: u16,
ne_csip: i32,
ne_sssp: i32,
ne_cseg: u16,
ne_cmod: u16,
ne_cbnrestab: u16,
ne_segtab: u16,
ne_rsrctab: u16,
ne_restab: u16,
ne_modtab: u16,
ne_imptab: u16,
ne_nrestab: i32,
ne_cmovent: u16,
ne_align: u16,
ne_cres: u16,
ne_exetyp: u8,
ne_flagsothers: u8,
ne_pretthunks: u16,
ne_psegrefbytes: u16,
ne_swaparea: u16,
ne_expver: u16,
};
pub const IMAGE_VXD_HEADER = extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
e32_magic: u16,
e32_border: u8,
e32_worder: u8,
e32_level: u32,
e32_cpu: u16,
e32_os: u16,
e32_ver: u32,
e32_mflags: u32,
e32_mpages: u32,
e32_startobj: u32,
e32_eip: u32,
e32_stackobj: u32,
e32_esp: u32,
e32_pagesize: u32,
e32_lastpagesize: u32,
e32_fixupsize: u32,
e32_fixupsum: u32,
e32_ldrsize: u32,
e32_ldrsum: u32,
e32_objtab: u32,
e32_objcnt: u32,
e32_objmap: u32,
e32_itermap: u32,
e32_rsrctab: u32,
e32_rsrccnt: u32,
e32_restab: u32,
e32_enttab: u32,
e32_dirtab: u32,
e32_dircnt: u32,
e32_fpagetab: u32,
e32_frectab: u32,
e32_impmod: u32,
e32_impmodcnt: u32,
e32_impproc: u32,
e32_pagesum: u32,
e32_datapage: u32,
e32_preload: u32,
e32_nrestab: u32,
e32_cbnrestab: u32,
e32_nressum: u32,
e32_autodata: u32,
e32_debuginfo: u32,
e32_debuglen: u32,
e32_instpreload: u32,
e32_instdemand: u32,
e32_heapsize: u32,
e32_res3: [12]u8,
e32_winresoff: u32,
e32_winreslen: u32,
e32_devid: u16,
e32_ddkver: u16,
};
pub const IMAGE_ROM_OPTIONAL_HEADER = extern struct {
Magic: u16,
MajorLinkerVersion: u8,
MinorLinkerVersion: u8,
SizeOfCode: u32,
SizeOfInitializedData: u32,
SizeOfUninitializedData: u32,
AddressOfEntryPoint: u32,
BaseOfCode: u32,
BaseOfData: u32,
BaseOfBss: u32,
GprMask: u32,
CprMask: [4]u32,
GpValue: u32,
};
pub const IMAGE_ROM_HEADERS = extern struct {
FileHeader: IMAGE_FILE_HEADER,
OptionalHeader: IMAGE_ROM_OPTIONAL_HEADER,
};
pub const ANON_OBJECT_HEADER = extern struct {
Sig1: u16,
Sig2: u16,
Version: u16,
Machine: u16,
TimeDateStamp: u32,
ClassID: Guid,
SizeOfData: u32,
};
pub const ANON_OBJECT_HEADER_V2 = extern struct {
Sig1: u16,
Sig2: u16,
Version: u16,
Machine: u16,
TimeDateStamp: u32,
ClassID: Guid,
SizeOfData: u32,
Flags: u32,
MetaDataSize: u32,
MetaDataOffset: u32,
};
pub const ANON_OBJECT_HEADER_BIGOBJ = extern struct {
Sig1: u16,
Sig2: u16,
Version: u16,
Machine: u16,
TimeDateStamp: u32,
ClassID: Guid,
SizeOfData: u32,
Flags: u32,
MetaDataSize: u32,
MetaDataOffset: u32,
NumberOfSections: u32,
PointerToSymbolTable: u32,
NumberOfSymbols: u32,
};
pub const IMAGE_SYMBOL = extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
N: extern union {
// WARNING: unable to add field alignment because it's not implemented for unions
ShortName: [8]u8,
Name: extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
Short: u32,
Long: u32,
},
LongName: [2]u32,
},
Value: u32,
SectionNumber: i16,
Type: u16,
StorageClass: u8,
NumberOfAuxSymbols: u8,
};
pub const IMAGE_SYMBOL_EX = extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
N: extern union {
// WARNING: unable to add field alignment because it's not implemented for unions
ShortName: [8]u8,
Name: extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
Short: u32,
Long: u32,
},
LongName: [2]u32,
},
Value: u32,
SectionNumber: i32,
Type: u16,
StorageClass: u8,
NumberOfAuxSymbols: u8,
};
pub const IMAGE_AUX_SYMBOL_TOKEN_DEF = extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
bAuxType: u8,
bReserved: u8,
SymbolTableIndex: u32,
rgbReserved: [12]u8,
};
pub const IMAGE_AUX_SYMBOL = extern union {
Sym: extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
TagIndex: u32,
Misc: extern union {
// WARNING: unable to add field alignment because it's not implemented for unions
LnSz: extern struct {
Linenumber: u16,
Size: u16,
},
TotalSize: u32,
},
FcnAry: extern union {
Function: extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
PointerToLinenumber: u32,
PointerToNextFunction: u32,
},
Array: extern struct {
Dimension: [4]u16,
},
},
TvIndex: u16,
},
File: extern struct {
Name: [18]u8,
},
Section: extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
Length: u32,
NumberOfRelocations: u16,
NumberOfLinenumbers: u16,
CheckSum: u32,
Number: i16,
Selection: u8,
bReserved: u8,
HighNumber: i16,
},
TokenDef: IMAGE_AUX_SYMBOL_TOKEN_DEF,
CRC: extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
crc: u32,
rgbReserved: [14]u8,
},
};
pub const IMAGE_AUX_SYMBOL_EX = extern union {
Sym: extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
WeakDefaultSymIndex: u32,
WeakSearchType: u32,
rgbReserved: [12]u8,
},
File: extern struct {
Name: [20]u8,
},
Section: extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
Length: u32,
NumberOfRelocations: u16,
NumberOfLinenumbers: u16,
CheckSum: u32,
Number: i16,
Selection: u8,
bReserved: u8,
HighNumber: i16,
rgbReserved: [2]u8,
},
Anonymous: extern struct {
TokenDef: IMAGE_AUX_SYMBOL_TOKEN_DEF,
rgbReserved: [2]u8,
},
CRC: extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
crc: u32,
rgbReserved: [16]u8,
},
};
pub const IMAGE_AUX_SYMBOL_TYPE = enum(i32) {
F = 1,
};
pub const IMAGE_AUX_SYMBOL_TYPE_TOKEN_DEF = IMAGE_AUX_SYMBOL_TYPE.F;
pub const IMAGE_RELOCATION = extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
Anonymous: extern union {
// WARNING: unable to add field alignment because it's not implemented for unions
VirtualAddress: u32,
RelocCount: u32,
},
SymbolTableIndex: u32,
Type: u16,
};
pub const IMAGE_LINENUMBER = extern struct {
Type: extern union {
// WARNING: unable to add field alignment because it's not implemented for unions
SymbolTableIndex: u32,
VirtualAddress: u32,
},
Linenumber: u16,
};
pub const IMAGE_BASE_RELOCATION = extern struct {
VirtualAddress: u32,
SizeOfBlock: u32,
};
pub const IMAGE_ARCHIVE_MEMBER_HEADER = extern struct {
Name: [16]u8,
Date: [12]u8,
UserID: [6]u8,
GroupID: [6]u8,
Mode: [8]u8,
Size: [10]u8,
EndHeader: [2]u8,
};
pub const IMAGE_EXPORT_DIRECTORY = extern struct {
Characteristics: u32,
TimeDateStamp: u32,
MajorVersion: u16,
MinorVersion: u16,
Name: u32,
Base: u32,
NumberOfFunctions: u32,
NumberOfNames: u32,
AddressOfFunctions: u32,
AddressOfNames: u32,
AddressOfNameOrdinals: u32,
};
pub const IMAGE_IMPORT_BY_NAME = extern struct {
Hint: u16,
Name: [1]CHAR,
};
pub const IMAGE_THUNK_DATA64 = extern struct {
u1: extern union {
ForwarderString: u64,
Function: u64,
Ordinal: u64,
AddressOfData: u64,
},
};
pub const IMAGE_THUNK_DATA32 = extern struct {
u1: extern union {
ForwarderString: u32,
Function: u32,
Ordinal: u32,
AddressOfData: u32,
},
};
pub const PIMAGE_TLS_CALLBACK = fn(
DllHandle: ?*c_void,
Reason: u32,
Reserved: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
pub const IMAGE_TLS_DIRECTORY64 = extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
StartAddressOfRawData: u64,
EndAddressOfRawData: u64,
AddressOfIndex: u64,
AddressOfCallBacks: u64,
SizeOfZeroFill: u32,
Anonymous: extern union {
Characteristics: u32,
Anonymous: extern struct {
_bitfield: u32,
},
},
};
pub const IMAGE_TLS_DIRECTORY32 = extern struct {
StartAddressOfRawData: u32,
EndAddressOfRawData: u32,
AddressOfIndex: u32,
AddressOfCallBacks: u32,
SizeOfZeroFill: u32,
Anonymous: extern union {
Characteristics: u32,
Anonymous: extern struct {
_bitfield: u32,
},
},
};
pub const IMAGE_IMPORT_DESCRIPTOR = extern struct {
Anonymous: extern union {
Characteristics: u32,
OriginalFirstThunk: u32,
},
TimeDateStamp: u32,
ForwarderChain: u32,
Name: u32,
FirstThunk: u32,
};
pub const IMAGE_BOUND_IMPORT_DESCRIPTOR = extern struct {
TimeDateStamp: u32,
OffsetModuleName: u16,
NumberOfModuleForwarderRefs: u16,
};
pub const IMAGE_BOUND_FORWARDER_REF = extern struct {
TimeDateStamp: u32,
OffsetModuleName: u16,
Reserved: u16,
};
pub const IMAGE_DELAYLOAD_DESCRIPTOR = extern struct {
Attributes: extern union {
AllAttributes: u32,
Anonymous: extern struct {
_bitfield: u32,
},
},
DllNameRVA: u32,
ModuleHandleRVA: u32,
ImportAddressTableRVA: u32,
ImportNameTableRVA: u32,
BoundImportAddressTableRVA: u32,
UnloadInformationTableRVA: u32,
TimeDateStamp: u32,
};
pub const IMAGE_RESOURCE_DIRECTORY = extern struct {
Characteristics: u32,
TimeDateStamp: u32,
MajorVersion: u16,
MinorVersion: u16,
NumberOfNamedEntries: u16,
NumberOfIdEntries: u16,
};
pub const IMAGE_RESOURCE_DIRECTORY_ENTRY = extern struct {
Anonymous1: extern union {
Anonymous: extern struct {
_bitfield: u32,
},
Name: u32,
Id: u16,
},
Anonymous2: extern union {
OffsetToData: u32,
Anonymous: extern struct {
_bitfield: u32,
},
},
};
pub const IMAGE_RESOURCE_DIRECTORY_STRING = extern struct {
Length: u16,
NameString: [1]CHAR,
};
pub const IMAGE_RESOURCE_DIR_STRING_U = extern struct {
Length: u16,
NameString: [1]u16,
};
pub const IMAGE_RESOURCE_DATA_ENTRY = extern struct {
OffsetToData: u32,
Size: u32,
CodePage: u32,
Reserved: u32,
};
pub const IMAGE_LOAD_CONFIG_CODE_INTEGRITY = extern struct {
Flags: u16,
Catalog: u16,
CatalogOffset: u32,
Reserved: u32,
};
pub const IMAGE_DYNAMIC_RELOCATION_TABLE = extern struct {
Version: u32,
Size: u32,
};
pub const IMAGE_DYNAMIC_RELOCATION32 = packed struct {
Symbol: u32,
BaseRelocSize: u32,
};
pub const IMAGE_DYNAMIC_RELOCATION64 = packed struct {
Symbol: u64,
BaseRelocSize: u32,
};
pub const IMAGE_DYNAMIC_RELOCATION32_V2 = packed struct {
HeaderSize: u32,
FixupInfoSize: u32,
Symbol: u32,
SymbolGroup: u32,
Flags: u32,
};
pub const IMAGE_DYNAMIC_RELOCATION64_V2 = packed struct {
HeaderSize: u32,
FixupInfoSize: u32,
Symbol: u64,
SymbolGroup: u32,
Flags: u32,
};
pub const IMAGE_PROLOGUE_DYNAMIC_RELOCATION_HEADER = extern struct {
PrologueByteCount: u8,
};
pub const IMAGE_EPILOGUE_DYNAMIC_RELOCATION_HEADER = packed struct {
EpilogueCount: u32,
EpilogueByteCount: u8,
BranchDescriptorElementSize: u8,
BranchDescriptorCount: u16,
};
pub const IMAGE_IMPORT_CONTROL_TRANSFER_DYNAMIC_RELOCATION = packed struct {
_bitfield: u32,
};
pub const IMAGE_INDIR_CONTROL_TRANSFER_DYNAMIC_RELOCATION = packed struct {
_bitfield: u16,
};
pub const IMAGE_SWITCHTABLE_BRANCH_DYNAMIC_RELOCATION = packed struct {
_bitfield: u16,
};
pub const IMAGE_HOT_PATCH_INFO = extern struct {
Version: u32,
Size: u32,
SequenceNumber: u32,
BaseImageList: u32,
BaseImageCount: u32,
BufferOffset: u32,
ExtraPatchSize: u32,
};
pub const IMAGE_HOT_PATCH_BASE = extern struct {
SequenceNumber: u32,
Flags: u32,
OriginalTimeDateStamp: u32,
OriginalCheckSum: u32,
CodeIntegrityInfo: u32,
CodeIntegritySize: u32,
PatchTable: u32,
BufferOffset: u32,
};
pub const IMAGE_HOT_PATCH_HASHES = extern struct {
SHA256: [32]u8,
SHA1: [20]u8,
};
pub const IMAGE_CE_RUNTIME_FUNCTION_ENTRY = extern struct {
FuncStart: u32,
_bitfield: u32,
};
pub const IMAGE_ARM_RUNTIME_FUNCTION_ENTRY = extern struct {
BeginAddress: u32,
Anonymous: extern union {
UnwindData: u32,
Anonymous: extern struct {
_bitfield: u32,
},
},
};
pub const ARM64_FNPDATA_FLAGS = enum(i32) {
RefToFullXdata = 0,
PackedUnwindFunction = 1,
PackedUnwindFragment = 2,
};
pub const PdataRefToFullXdata = ARM64_FNPDATA_FLAGS.RefToFullXdata;
pub const PdataPackedUnwindFunction = ARM64_FNPDATA_FLAGS.PackedUnwindFunction;
pub const PdataPackedUnwindFragment = ARM64_FNPDATA_FLAGS.PackedUnwindFragment;
pub const ARM64_FNPDATA_CR = enum(i32) {
Unchained = 0,
UnchainedSavedLr = 1,
Chained = 3,
};
pub const PdataCrUnchained = ARM64_FNPDATA_CR.Unchained;
pub const PdataCrUnchainedSavedLr = ARM64_FNPDATA_CR.UnchainedSavedLr;
pub const PdataCrChained = ARM64_FNPDATA_CR.Chained;
pub const IMAGE_ARM64_RUNTIME_FUNCTION_ENTRY = extern struct {
BeginAddress: u32,
Anonymous: extern union {
UnwindData: u32,
Anonymous: extern struct {
_bitfield: u32,
},
},
};
pub const IMAGE_ARM64_RUNTIME_FUNCTION_ENTRY_XDATA = extern union {
HeaderData: u32,
Anonymous: extern struct {
_bitfield: u32,
},
};
pub const IMAGE_ALPHA64_RUNTIME_FUNCTION_ENTRY = extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
BeginAddress: u64,
EndAddress: u64,
ExceptionHandler: u64,
HandlerData: u64,
PrologEndAddress: u64,
};
pub const IMAGE_ALPHA_RUNTIME_FUNCTION_ENTRY = extern struct {
BeginAddress: u32,
EndAddress: u32,
ExceptionHandler: u32,
HandlerData: u32,
PrologEndAddress: u32,
};
pub const IMAGE_RUNTIME_FUNCTION_ENTRY = extern struct {
BeginAddress: u32,
EndAddress: u32,
Anonymous: extern union {
UnwindInfoAddress: u32,
UnwindData: u32,
},
};
pub const IMAGE_DEBUG_MISC = extern struct {
DataType: u32,
Length: u32,
Unicode: BOOLEAN,
Reserved: [3]u8,
Data: [1]u8,
};
pub const IMAGE_SEPARATE_DEBUG_HEADER = extern struct {
Signature: u16,
Flags: u16,
Machine: u16,
Characteristics: u16,
TimeDateStamp: u32,
CheckSum: u32,
ImageBase: u32,
SizeOfImage: u32,
NumberOfSections: u32,
ExportedNamesSize: u32,
DebugDirectorySize: u32,
SectionAlignment: u32,
Reserved: [2]u32,
};
pub const NON_PAGED_DEBUG_INFO = extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
Signature: u16,
Flags: u16,
Size: u32,
Machine: u16,
Characteristics: u16,
TimeDateStamp: u32,
CheckSum: u32,
SizeOfImage: u32,
ImageBase: u64,
};
pub const IMAGE_ARCHITECTURE_HEADER = extern struct {
_bitfield: u32,
FirstEntryRVA: u32,
};
pub const IMAGE_ARCHITECTURE_ENTRY = extern struct {
FixupInstRVA: u32,
NewInst: u32,
};
pub const IMPORT_OBJECT_HEADER = extern struct {
Sig1: u16,
Sig2: u16,
Version: u16,
Machine: u16,
TimeDateStamp: u32,
SizeOfData: u32,
Anonymous: extern union {
Ordinal: u16,
Hint: u16,
},
_bitfield: u16,
};
pub const IMPORT_OBJECT_TYPE = enum(i32) {
CODE = 0,
DATA = 1,
CONST = 2,
};
pub const IMPORT_OBJECT_CODE = IMPORT_OBJECT_TYPE.CODE;
pub const IMPORT_OBJECT_DATA = IMPORT_OBJECT_TYPE.DATA;
pub const IMPORT_OBJECT_CONST = IMPORT_OBJECT_TYPE.CONST;
pub const IMPORT_OBJECT_NAME_TYPE = enum(i32) {
ORDINAL = 0,
NAME = 1,
NAME_NO_PREFIX = 2,
NAME_UNDECORATE = 3,
NAME_EXPORTAS = 4,
};
pub const IMPORT_OBJECT_ORDINAL = IMPORT_OBJECT_NAME_TYPE.ORDINAL;
pub const IMPORT_OBJECT_NAME = IMPORT_OBJECT_NAME_TYPE.NAME;
pub const IMPORT_OBJECT_NAME_NO_PREFIX = IMPORT_OBJECT_NAME_TYPE.NAME_NO_PREFIX;
pub const IMPORT_OBJECT_NAME_UNDECORATE = IMPORT_OBJECT_NAME_TYPE.NAME_UNDECORATE;
pub const IMPORT_OBJECT_NAME_EXPORTAS = IMPORT_OBJECT_NAME_TYPE.NAME_EXPORTAS;
pub const ReplacesCorHdrNumericDefines = enum(i32) {
COMIMAGE_FLAGS_ILONLY = 1,
COMIMAGE_FLAGS_32BITREQUIRED = 2,
COMIMAGE_FLAGS_IL_LIBRARY = 4,
COMIMAGE_FLAGS_STRONGNAMESIGNED = 8,
COMIMAGE_FLAGS_NATIVE_ENTRYPOINT = 16,
COMIMAGE_FLAGS_TRACKDEBUGDATA = 65536,
COMIMAGE_FLAGS_32BITPREFERRED = 131072,
// COR_VERSION_MAJOR_V2 = 2, this enum value conflicts with COMIMAGE_FLAGS_32BITREQUIRED
// COR_VERSION_MAJOR = 2, this enum value conflicts with COMIMAGE_FLAGS_32BITREQUIRED
COR_VERSION_MINOR = 5,
// COR_DELETED_NAME_LENGTH = 8, this enum value conflicts with COMIMAGE_FLAGS_STRONGNAMESIGNED
// COR_VTABLEGAP_NAME_LENGTH = 8, this enum value conflicts with COMIMAGE_FLAGS_STRONGNAMESIGNED
// NATIVE_TYPE_MAX_CB = 1, this enum value conflicts with COMIMAGE_FLAGS_ILONLY
COR_ILMETHOD_SECT_SMALL_MAX_DATASIZE = 255,
// IMAGE_COR_MIH_METHODRVA = 1, this enum value conflicts with COMIMAGE_FLAGS_ILONLY
// IMAGE_COR_MIH_EHRVA = 2, this enum value conflicts with COMIMAGE_FLAGS_32BITREQUIRED
// IMAGE_COR_MIH_BASICBLOCK = 8, this enum value conflicts with COMIMAGE_FLAGS_STRONGNAMESIGNED
// COR_VTABLE_32BIT = 1, this enum value conflicts with COMIMAGE_FLAGS_ILONLY
// COR_VTABLE_64BIT = 2, this enum value conflicts with COMIMAGE_FLAGS_32BITREQUIRED
// COR_VTABLE_FROM_UNMANAGED = 4, this enum value conflicts with COMIMAGE_FLAGS_IL_LIBRARY
// COR_VTABLE_FROM_UNMANAGED_RETAIN_APPDOMAIN = 8, this enum value conflicts with COMIMAGE_FLAGS_STRONGNAMESIGNED
// COR_VTABLE_CALL_MOST_DERIVED = 16, this enum value conflicts with COMIMAGE_FLAGS_NATIVE_ENTRYPOINT
IMAGE_COR_EATJ_THUNK_SIZE = 32,
MAX_CLASS_NAME = 1024,
// MAX_PACKAGE_NAME = 1024, this enum value conflicts with MAX_CLASS_NAME
};
pub const COMIMAGE_FLAGS_ILONLY = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_ILONLY;
pub const COMIMAGE_FLAGS_32BITREQUIRED = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_32BITREQUIRED;
pub const COMIMAGE_FLAGS_IL_LIBRARY = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_IL_LIBRARY;
pub const COMIMAGE_FLAGS_STRONGNAMESIGNED = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_STRONGNAMESIGNED;
pub const COMIMAGE_FLAGS_NATIVE_ENTRYPOINT = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_NATIVE_ENTRYPOINT;
pub const COMIMAGE_FLAGS_TRACKDEBUGDATA = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_TRACKDEBUGDATA;
pub const COMIMAGE_FLAGS_32BITPREFERRED = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_32BITPREFERRED;
pub const COR_VERSION_MAJOR_V2 = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_32BITREQUIRED;
pub const COR_VERSION_MAJOR = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_32BITREQUIRED;
pub const COR_VERSION_MINOR = ReplacesCorHdrNumericDefines.COR_VERSION_MINOR;
pub const COR_DELETED_NAME_LENGTH = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_STRONGNAMESIGNED;
pub const COR_VTABLEGAP_NAME_LENGTH = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_STRONGNAMESIGNED;
pub const NATIVE_TYPE_MAX_CB = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_ILONLY;
pub const COR_ILMETHOD_SECT_SMALL_MAX_DATASIZE = ReplacesCorHdrNumericDefines.COR_ILMETHOD_SECT_SMALL_MAX_DATASIZE;
pub const IMAGE_COR_MIH_METHODRVA = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_ILONLY;
pub const IMAGE_COR_MIH_EHRVA = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_32BITREQUIRED;
pub const IMAGE_COR_MIH_BASICBLOCK = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_STRONGNAMESIGNED;
pub const COR_VTABLE_32BIT = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_ILONLY;
pub const COR_VTABLE_64BIT = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_32BITREQUIRED;
pub const COR_VTABLE_FROM_UNMANAGED = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_IL_LIBRARY;
pub const COR_VTABLE_FROM_UNMANAGED_RETAIN_APPDOMAIN = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_STRONGNAMESIGNED;
pub const COR_VTABLE_CALL_MOST_DERIVED = ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_NATIVE_ENTRYPOINT;
pub const IMAGE_COR_EATJ_THUNK_SIZE = ReplacesCorHdrNumericDefines.IMAGE_COR_EATJ_THUNK_SIZE;
pub const MAX_CLASS_NAME = ReplacesCorHdrNumericDefines.MAX_CLASS_NAME;
pub const MAX_PACKAGE_NAME = ReplacesCorHdrNumericDefines.MAX_CLASS_NAME;
pub const IMAGE_COR20_HEADER = extern struct {
cb: u32,
MajorRuntimeVersion: u16,
MinorRuntimeVersion: u16,
MetaData: IMAGE_DATA_DIRECTORY,
Flags: u32,
Anonymous: extern union {
EntryPointToken: u32,
EntryPointRVA: u32,
},
Resources: IMAGE_DATA_DIRECTORY,
StrongNameSignature: IMAGE_DATA_DIRECTORY,
CodeManagerTable: IMAGE_DATA_DIRECTORY,
VTableFixups: IMAGE_DATA_DIRECTORY,
ExportAddressTableJumps: IMAGE_DATA_DIRECTORY,
ManagedNativeHeader: IMAGE_DATA_DIRECTORY,
};
pub const RTL_RUN_ONCE = extern union {
Ptr: ?*c_void,
};
pub const RTL_BARRIER = extern struct {
Reserved1: u32,
Reserved2: u32,
Reserved3: [2]usize,
Reserved4: u32,
Reserved5: u32,
};
pub const RTL_UMS_THREAD_INFO_CLASS = enum(i32) {
InvalidInfoClass = 0,
UserContext = 1,
Priority = 2,
Affinity = 3,
Teb = 4,
IsSuspended = 5,
IsTerminated = 6,
MaxInfoClass = 7,
};
pub const UmsThreadInvalidInfoClass = RTL_UMS_THREAD_INFO_CLASS.InvalidInfoClass;
pub const UmsThreadUserContext = RTL_UMS_THREAD_INFO_CLASS.UserContext;
pub const UmsThreadPriority = RTL_UMS_THREAD_INFO_CLASS.Priority;
pub const UmsThreadAffinity = RTL_UMS_THREAD_INFO_CLASS.Affinity;
pub const UmsThreadTeb = RTL_UMS_THREAD_INFO_CLASS.Teb;
pub const UmsThreadIsSuspended = RTL_UMS_THREAD_INFO_CLASS.IsSuspended;
pub const UmsThreadIsTerminated = RTL_UMS_THREAD_INFO_CLASS.IsTerminated;
pub const UmsThreadMaxInfoClass = RTL_UMS_THREAD_INFO_CLASS.MaxInfoClass;
pub const RTL_UMS_SCHEDULER_REASON = enum(i32) {
Startup = 0,
ThreadBlocked = 1,
ThreadYield = 2,
};
pub const UmsSchedulerStartup = RTL_UMS_SCHEDULER_REASON.Startup;
pub const UmsSchedulerThreadBlocked = RTL_UMS_SCHEDULER_REASON.ThreadBlocked;
pub const UmsSchedulerThreadYield = RTL_UMS_SCHEDULER_REASON.ThreadYield;
pub const PRTL_UMS_SCHEDULER_ENTRY_POINT = fn(
Reason: RTL_UMS_SCHEDULER_REASON,
ActivationPayload: usize,
SchedulerParam: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
pub const OS_DEPLOYEMENT_STATE_VALUES = enum(i32) {
STANDARD = 1,
COMPACT = 2,
};
pub const OS_DEPLOYMENT_STANDARD = OS_DEPLOYEMENT_STATE_VALUES.STANDARD;
pub const OS_DEPLOYMENT_COMPACT = OS_DEPLOYEMENT_STATE_VALUES.COMPACT;
pub const NV_MEMORY_RANGE = extern struct {
BaseAddress: ?*c_void,
Length: usize,
};
pub const CORRELATION_VECTOR = extern struct {
Version: CHAR,
Vector: [129]CHAR,
};
pub const CUSTOM_SYSTEM_EVENT_TRIGGER_CONFIG = extern struct {
Size: u32,
TriggerId: ?[*:0]const u16,
};
pub const IMAGE_POLICY_ENTRY_TYPE = enum(i32) {
None = 0,
Bool = 1,
Int8 = 2,
UInt8 = 3,
Int16 = 4,
UInt16 = 5,
Int32 = 6,
UInt32 = 7,
Int64 = 8,
UInt64 = 9,
AnsiString = 10,
UnicodeString = 11,
Override = 12,
Maximum = 13,
};
pub const ImagePolicyEntryTypeNone = IMAGE_POLICY_ENTRY_TYPE.None;
pub const ImagePolicyEntryTypeBool = IMAGE_POLICY_ENTRY_TYPE.Bool;
pub const ImagePolicyEntryTypeInt8 = IMAGE_POLICY_ENTRY_TYPE.Int8;
pub const ImagePolicyEntryTypeUInt8 = IMAGE_POLICY_ENTRY_TYPE.UInt8;
pub const ImagePolicyEntryTypeInt16 = IMAGE_POLICY_ENTRY_TYPE.Int16;
pub const ImagePolicyEntryTypeUInt16 = IMAGE_POLICY_ENTRY_TYPE.UInt16;
pub const ImagePolicyEntryTypeInt32 = IMAGE_POLICY_ENTRY_TYPE.Int32;
pub const ImagePolicyEntryTypeUInt32 = IMAGE_POLICY_ENTRY_TYPE.UInt32;
pub const ImagePolicyEntryTypeInt64 = IMAGE_POLICY_ENTRY_TYPE.Int64;
pub const ImagePolicyEntryTypeUInt64 = IMAGE_POLICY_ENTRY_TYPE.UInt64;
pub const ImagePolicyEntryTypeAnsiString = IMAGE_POLICY_ENTRY_TYPE.AnsiString;
pub const ImagePolicyEntryTypeUnicodeString = IMAGE_POLICY_ENTRY_TYPE.UnicodeString;
pub const ImagePolicyEntryTypeOverride = IMAGE_POLICY_ENTRY_TYPE.Override;
pub const ImagePolicyEntryTypeMaximum = IMAGE_POLICY_ENTRY_TYPE.Maximum;
pub const IMAGE_POLICY_ID = enum(i32) {
None = 0,
Etw = 1,
Debug = 2,
CrashDump = 3,
CrashDumpKey = 4,
CrashDumpKeyGuid = 5,
ParentSd = 6,
ParentSdRev = 7,
Svn = 8,
DeviceId = 9,
Capability = 10,
ScenarioId = 11,
Maximum = 12,
};
pub const ImagePolicyIdNone = IMAGE_POLICY_ID.None;
pub const ImagePolicyIdEtw = IMAGE_POLICY_ID.Etw;
pub const ImagePolicyIdDebug = IMAGE_POLICY_ID.Debug;
pub const ImagePolicyIdCrashDump = IMAGE_POLICY_ID.CrashDump;
pub const ImagePolicyIdCrashDumpKey = IMAGE_POLICY_ID.CrashDumpKey;
pub const ImagePolicyIdCrashDumpKeyGuid = IMAGE_POLICY_ID.CrashDumpKeyGuid;
pub const ImagePolicyIdParentSd = IMAGE_POLICY_ID.ParentSd;
pub const ImagePolicyIdParentSdRev = IMAGE_POLICY_ID.ParentSdRev;
pub const ImagePolicyIdSvn = IMAGE_POLICY_ID.Svn;
pub const ImagePolicyIdDeviceId = IMAGE_POLICY_ID.DeviceId;
pub const ImagePolicyIdCapability = IMAGE_POLICY_ID.Capability;
pub const ImagePolicyIdScenarioId = IMAGE_POLICY_ID.ScenarioId;
pub const ImagePolicyIdMaximum = IMAGE_POLICY_ID.Maximum;
pub const IMAGE_POLICY_ENTRY = extern struct {
Type: IMAGE_POLICY_ENTRY_TYPE,
PolicyId: IMAGE_POLICY_ID,
u: extern union {
None: ?*const c_void,
BoolValue: BOOLEAN,
Int8Value: i8,
UInt8Value: u8,
Int16Value: i16,
UInt16Value: u16,
Int32Value: i32,
UInt32Value: u32,
Int64Value: i64,
UInt64Value: u64,
AnsiStringValue: ?[*:0]const u8,
UnicodeStringValue: ?[*:0]const u16,
},
};
pub const IMAGE_POLICY_METADATA = extern struct {
Version: u8,
Reserved0: [7]u8,
ApplicationId: u64,
Policies: [1]IMAGE_POLICY_ENTRY,
};
pub const RTL_CRITICAL_SECTION_DEBUG = extern struct {
Type: u16,
CreatorBackTraceIndex: u16,
CriticalSection: ?*RTL_CRITICAL_SECTION,
ProcessLocksList: LIST_ENTRY,
EntryCount: u32,
ContentionCount: u32,
Flags: u32,
CreatorBackTraceIndexHigh: u16,
SpareWORD: u16,
};
pub const RTL_CRITICAL_SECTION = extern struct {
DebugInfo: ?*RTL_CRITICAL_SECTION_DEBUG,
LockCount: i32,
RecursionCount: i32,
OwningThread: ?HANDLE,
LockSemaphore: ?HANDLE,
SpinCount: usize,
};
pub const RTL_SRWLOCK = extern struct {
Ptr: ?*c_void,
};
pub const RTL_CONDITION_VARIABLE = extern struct {
Ptr: ?*c_void,
};
pub const PAPCFUNC = fn(
Parameter: usize,
) callconv(@import("std").os.windows.WINAPI) void;
pub const HEAP_INFORMATION_CLASS = enum(i32) {
CompatibilityInformation = 0,
EnableTerminationOnCorruption = 1,
OptimizeResources = 3,
};
pub const HeapCompatibilityInformation = HEAP_INFORMATION_CLASS.CompatibilityInformation;
pub const HeapEnableTerminationOnCorruption = HEAP_INFORMATION_CLASS.EnableTerminationOnCorruption;
pub const HeapOptimizeResources = HEAP_INFORMATION_CLASS.OptimizeResources;
pub const HEAP_OPTIMIZE_RESOURCES_INFORMATION = extern struct {
Version: u32,
Flags: u32,
};
pub const WAITORTIMERCALLBACK = fn(
param0: ?*c_void,
param1: BOOLEAN,
) callconv(@import("std").os.windows.WINAPI) void;
pub const WORKERCALLBACKFUNC = fn(
param0: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
pub const APC_CALLBACK_FUNCTION = fn(
param0: u32,
param1: ?*c_void,
param2: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
pub const PFLS_CALLBACK_FUNCTION = fn(
lpFlsData: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
pub const ACTIVATION_CONTEXT_INFO_CLASS = enum(i32) {
ActivationContextBasicInformation = 1,
ActivationContextDetailedInformation = 2,
AssemblyDetailedInformationInActivationContext = 3,
FileInformationInAssemblyOfAssemblyInActivationContext = 4,
RunlevelInformationInActivationContext = 5,
CompatibilityInformationInActivationContext = 6,
ActivationContextManifestResourceName = 7,
MaxActivationContextInfoClass = 8,
// AssemblyDetailedInformationInActivationContxt = 3, this enum value conflicts with AssemblyDetailedInformationInActivationContext
// FileInformationInAssemblyOfAssemblyInActivationContxt = 4, this enum value conflicts with FileInformationInAssemblyOfAssemblyInActivationContext
};
pub const ActivationContextBasicInformation = ACTIVATION_CONTEXT_INFO_CLASS.ActivationContextBasicInformation;
pub const ActivationContextDetailedInformation = ACTIVATION_CONTEXT_INFO_CLASS.ActivationContextDetailedInformation;
pub const AssemblyDetailedInformationInActivationContext = ACTIVATION_CONTEXT_INFO_CLASS.AssemblyDetailedInformationInActivationContext;
pub const FileInformationInAssemblyOfAssemblyInActivationContext = ACTIVATION_CONTEXT_INFO_CLASS.FileInformationInAssemblyOfAssemblyInActivationContext;
pub const RunlevelInformationInActivationContext = ACTIVATION_CONTEXT_INFO_CLASS.RunlevelInformationInActivationContext;
pub const CompatibilityInformationInActivationContext = ACTIVATION_CONTEXT_INFO_CLASS.CompatibilityInformationInActivationContext;
pub const ActivationContextManifestResourceName = ACTIVATION_CONTEXT_INFO_CLASS.ActivationContextManifestResourceName;
pub const MaxActivationContextInfoClass = ACTIVATION_CONTEXT_INFO_CLASS.MaxActivationContextInfoClass;
pub const AssemblyDetailedInformationInActivationContxt = ACTIVATION_CONTEXT_INFO_CLASS.AssemblyDetailedInformationInActivationContext;
pub const FileInformationInAssemblyOfAssemblyInActivationContxt = ACTIVATION_CONTEXT_INFO_CLASS.FileInformationInAssemblyOfAssemblyInActivationContext;
pub const SUPPORTED_OS_INFO = extern struct {
MajorVersion: u16,
MinorVersion: u16,
};
pub const MAXVERSIONTESTED_INFO = extern struct {
MaxVersionTested: u64,
};
pub const EVENTLOGRECORD = extern struct {
Length: u32,
Reserved: u32,
RecordNumber: u32,
TimeGenerated: u32,
TimeWritten: u32,
EventID: u32,
EventType: REPORT_EVENT_TYPE,
NumStrings: u16,
EventCategory: u16,
ReservedFlags: u16,
ClosingRecordNumber: u32,
StringOffset: u32,
UserSidLength: u32,
UserSidOffset: u32,
DataLength: u32,
DataOffset: u32,
};
pub const EVENTSFORLOGFILE = extern struct {
ulSize: u32,
szLogicalLogFile: [256]u16,
ulNumRecords: u32,
pEventLogRecords: [1]EVENTLOGRECORD,
};
pub const PACKEDEVENTINFO = extern struct {
ulSize: u32,
ulNumEventsForLogFile: u32,
ulOffsets: [1]u32,
};
pub const CM_SERVICE_NODE_TYPE = enum(i32) {
DriverType = 1,
FileSystemType = 2,
Win32ServiceOwnProcess = 16,
Win32ServiceShareProcess = 32,
AdapterType = 4,
RecognizerType = 8,
};
pub const DriverType = CM_SERVICE_NODE_TYPE.DriverType;
pub const FileSystemType = CM_SERVICE_NODE_TYPE.FileSystemType;
pub const Win32ServiceOwnProcess = CM_SERVICE_NODE_TYPE.Win32ServiceOwnProcess;
pub const Win32ServiceShareProcess = CM_SERVICE_NODE_TYPE.Win32ServiceShareProcess;
pub const AdapterType = CM_SERVICE_NODE_TYPE.AdapterType;
pub const RecognizerType = CM_SERVICE_NODE_TYPE.RecognizerType;
pub const CM_SERVICE_LOAD_TYPE = enum(i32) {
BootLoad = 0,
SystemLoad = 1,
AutoLoad = 2,
DemandLoad = 3,
DisableLoad = 4,
};
pub const BootLoad = CM_SERVICE_LOAD_TYPE.BootLoad;
pub const SystemLoad = CM_SERVICE_LOAD_TYPE.SystemLoad;
pub const AutoLoad = CM_SERVICE_LOAD_TYPE.AutoLoad;
pub const DemandLoad = CM_SERVICE_LOAD_TYPE.DemandLoad;
pub const DisableLoad = CM_SERVICE_LOAD_TYPE.DisableLoad;
pub const CM_ERROR_CONTROL_TYPE = enum(i32) {
IgnoreError = 0,
NormalError = 1,
SevereError = 2,
CriticalError = 3,
};
pub const IgnoreError = CM_ERROR_CONTROL_TYPE.IgnoreError;
pub const NormalError = CM_ERROR_CONTROL_TYPE.NormalError;
pub const SevereError = CM_ERROR_CONTROL_TYPE.SevereError;
pub const CriticalError = CM_ERROR_CONTROL_TYPE.CriticalError;
pub const TAPE_ERASE = extern struct {
Type: ERASE_TAPE_TYPE,
Immediate: BOOLEAN,
};
pub const TAPE_PREPARE = extern struct {
Operation: PREPARE_TAPE_OPERATION,
Immediate: BOOLEAN,
};
pub const TAPE_WRITE_MARKS = extern struct {
Type: TAPEMARK_TYPE,
Count: u32,
Immediate: BOOLEAN,
};
pub const TAPE_GET_POSITION = extern struct {
Type: TAPE_POSITION_TYPE,
Partition: u32,
Offset: LARGE_INTEGER,
};
pub const TAPE_SET_POSITION = extern struct {
Method: TAPE_POSITION_METHOD,
Partition: u32,
Offset: LARGE_INTEGER,
Immediate: BOOLEAN,
};
pub const TAPE_GET_DRIVE_PARAMETERS = extern struct {
ECC: BOOLEAN,
Compression: BOOLEAN,
DataPadding: BOOLEAN,
ReportSetmarks: BOOLEAN,
DefaultBlockSize: u32,
MaximumBlockSize: u32,
MinimumBlockSize: u32,
MaximumPartitionCount: u32,
FeaturesLow: u32,
FeaturesHigh: TAPE_GET_DRIVE_PARAMETERS_FEATURES_HIGH,
EOTWarningZoneSize: u32,
};
pub const TAPE_SET_DRIVE_PARAMETERS = extern struct {
ECC: BOOLEAN,
Compression: BOOLEAN,
DataPadding: BOOLEAN,
ReportSetmarks: BOOLEAN,
EOTWarningZoneSize: u32,
};
pub const TAPE_GET_MEDIA_PARAMETERS = extern struct {
Capacity: LARGE_INTEGER,
Remaining: LARGE_INTEGER,
BlockSize: u32,
PartitionCount: u32,
WriteProtected: BOOLEAN,
};
pub const TAPE_SET_MEDIA_PARAMETERS = extern struct {
BlockSize: u32,
};
pub const TAPE_CREATE_PARTITION = extern struct {
Method: u32,
Count: u32,
Size: u32,
};
pub const TAPE_WMI_OPERATIONS = extern struct {
Method: u32,
DataBufferSize: u32,
DataBuffer: ?*c_void,
};
pub const TAPE_DRIVE_PROBLEM_TYPE = enum(i32) {
ProblemNone = 0,
ReadWriteWarning = 1,
ReadWriteError = 2,
ReadWarning = 3,
WriteWarning = 4,
ReadError = 5,
WriteError = 6,
HardwareError = 7,
UnsupportedMedia = 8,
ScsiConnectionError = 9,
TimetoClean = 10,
CleanDriveNow = 11,
MediaLifeExpired = 12,
SnappedTape = 13,
};
pub const TapeDriveProblemNone = TAPE_DRIVE_PROBLEM_TYPE.ProblemNone;
pub const TapeDriveReadWriteWarning = TAPE_DRIVE_PROBLEM_TYPE.ReadWriteWarning;
pub const TapeDriveReadWriteError = TAPE_DRIVE_PROBLEM_TYPE.ReadWriteError;
pub const TapeDriveReadWarning = TAPE_DRIVE_PROBLEM_TYPE.ReadWarning;
pub const TapeDriveWriteWarning = TAPE_DRIVE_PROBLEM_TYPE.WriteWarning;
pub const TapeDriveReadError = TAPE_DRIVE_PROBLEM_TYPE.ReadError;
pub const TapeDriveWriteError = TAPE_DRIVE_PROBLEM_TYPE.WriteError;
pub const TapeDriveHardwareError = TAPE_DRIVE_PROBLEM_TYPE.HardwareError;
pub const TapeDriveUnsupportedMedia = TAPE_DRIVE_PROBLEM_TYPE.UnsupportedMedia;
pub const TapeDriveScsiConnectionError = TAPE_DRIVE_PROBLEM_TYPE.ScsiConnectionError;
pub const TapeDriveTimetoClean = TAPE_DRIVE_PROBLEM_TYPE.TimetoClean;
pub const TapeDriveCleanDriveNow = TAPE_DRIVE_PROBLEM_TYPE.CleanDriveNow;
pub const TapeDriveMediaLifeExpired = TAPE_DRIVE_PROBLEM_TYPE.MediaLifeExpired;
pub const TapeDriveSnappedTape = TAPE_DRIVE_PROBLEM_TYPE.SnappedTape;
pub const TRANSACTION_STATE = enum(i32) {
Normal = 1,
Indoubt = 2,
CommittedNotify = 3,
};
pub const TransactionStateNormal = TRANSACTION_STATE.Normal;
pub const TransactionStateIndoubt = TRANSACTION_STATE.Indoubt;
pub const TransactionStateCommittedNotify = TRANSACTION_STATE.CommittedNotify;
pub const TRANSACTION_BASIC_INFORMATION = extern struct {
TransactionId: Guid,
State: u32,
Outcome: u32,
};
pub const TRANSACTIONMANAGER_BASIC_INFORMATION = extern struct {
TmIdentity: Guid,
VirtualClock: LARGE_INTEGER,
};
pub const TRANSACTIONMANAGER_LOG_INFORMATION = extern struct {
LogIdentity: Guid,
};
pub const TRANSACTIONMANAGER_LOGPATH_INFORMATION = extern struct {
LogPathLength: u32,
LogPath: [1]u16,
};
pub const TRANSACTIONMANAGER_RECOVERY_INFORMATION = extern struct {
LastRecoveredLsn: u64,
};
pub const TRANSACTIONMANAGER_OLDEST_INFORMATION = extern struct {
OldestTransactionGuid: Guid,
};
pub const TRANSACTION_PROPERTIES_INFORMATION = extern struct {
IsolationLevel: u32,
IsolationFlags: u32,
Timeout: LARGE_INTEGER,
Outcome: u32,
DescriptionLength: u32,
Description: [1]u16,
};
pub const TRANSACTION_BIND_INFORMATION = extern struct {
TmHandle: ?HANDLE,
};
pub const TRANSACTION_ENLISTMENT_PAIR = extern struct {
EnlistmentId: Guid,
ResourceManagerId: Guid,
};
pub const TRANSACTION_ENLISTMENTS_INFORMATION = extern struct {
NumberOfEnlistments: u32,
EnlistmentPair: [1]TRANSACTION_ENLISTMENT_PAIR,
};
pub const TRANSACTION_SUPERIOR_ENLISTMENT_INFORMATION = extern struct {
SuperiorEnlistmentPair: TRANSACTION_ENLISTMENT_PAIR,
};
pub const RESOURCEMANAGER_BASIC_INFORMATION = extern struct {
ResourceManagerId: Guid,
DescriptionLength: u32,
Description: [1]u16,
};
pub const RESOURCEMANAGER_COMPLETION_INFORMATION = extern struct {
IoCompletionPortHandle: ?HANDLE,
CompletionKey: usize,
};
pub const TRANSACTION_INFORMATION_CLASS = enum(i32) {
BasicInformation = 0,
PropertiesInformation = 1,
EnlistmentInformation = 2,
SuperiorEnlistmentInformation = 3,
BindInformation = 4,
DTCPrivateInformation = 5,
};
pub const TransactionBasicInformation = TRANSACTION_INFORMATION_CLASS.BasicInformation;
pub const TransactionPropertiesInformation = TRANSACTION_INFORMATION_CLASS.PropertiesInformation;
pub const TransactionEnlistmentInformation = TRANSACTION_INFORMATION_CLASS.EnlistmentInformation;
pub const TransactionSuperiorEnlistmentInformation = TRANSACTION_INFORMATION_CLASS.SuperiorEnlistmentInformation;
pub const TransactionBindInformation = TRANSACTION_INFORMATION_CLASS.BindInformation;
pub const TransactionDTCPrivateInformation = TRANSACTION_INFORMATION_CLASS.DTCPrivateInformation;
pub const TRANSACTIONMANAGER_INFORMATION_CLASS = enum(i32) {
BasicInformation = 0,
LogInformation = 1,
LogPathInformation = 2,
RecoveryInformation = 4,
OnlineProbeInformation = 3,
OldestTransactionInformation = 5,
};
pub const TransactionManagerBasicInformation = TRANSACTIONMANAGER_INFORMATION_CLASS.BasicInformation;
pub const TransactionManagerLogInformation = TRANSACTIONMANAGER_INFORMATION_CLASS.LogInformation;
pub const TransactionManagerLogPathInformation = TRANSACTIONMANAGER_INFORMATION_CLASS.LogPathInformation;
pub const TransactionManagerRecoveryInformation = TRANSACTIONMANAGER_INFORMATION_CLASS.RecoveryInformation;
pub const TransactionManagerOnlineProbeInformation = TRANSACTIONMANAGER_INFORMATION_CLASS.OnlineProbeInformation;
pub const TransactionManagerOldestTransactionInformation = TRANSACTIONMANAGER_INFORMATION_CLASS.OldestTransactionInformation;
pub const RESOURCEMANAGER_INFORMATION_CLASS = enum(i32) {
BasicInformation = 0,
CompletionInformation = 1,
};
pub const ResourceManagerBasicInformation = RESOURCEMANAGER_INFORMATION_CLASS.BasicInformation;
pub const ResourceManagerCompletionInformation = RESOURCEMANAGER_INFORMATION_CLASS.CompletionInformation;
pub const ENLISTMENT_BASIC_INFORMATION = extern struct {
EnlistmentId: Guid,
TransactionId: Guid,
ResourceManagerId: Guid,
};
pub const ENLISTMENT_CRM_INFORMATION = extern struct {
CrmTransactionManagerId: Guid,
CrmResourceManagerId: Guid,
CrmEnlistmentId: Guid,
};
pub const ENLISTMENT_INFORMATION_CLASS = enum(i32) {
BasicInformation = 0,
RecoveryInformation = 1,
CrmInformation = 2,
};
pub const EnlistmentBasicInformation = ENLISTMENT_INFORMATION_CLASS.BasicInformation;
pub const EnlistmentRecoveryInformation = ENLISTMENT_INFORMATION_CLASS.RecoveryInformation;
pub const EnlistmentCrmInformation = ENLISTMENT_INFORMATION_CLASS.CrmInformation;
pub const TRANSACTION_LIST_ENTRY = extern struct {
UOW: Guid,
};
pub const TRANSACTION_LIST_INFORMATION = extern struct {
NumberOfTransactions: u32,
TransactionInformation: [1]TRANSACTION_LIST_ENTRY,
};
pub const KTMOBJECT_TYPE = enum(i32) {
TRANSACTION = 0,
TRANSACTION_MANAGER = 1,
RESOURCE_MANAGER = 2,
ENLISTMENT = 3,
INVALID = 4,
};
pub const KTMOBJECT_TRANSACTION = KTMOBJECT_TYPE.TRANSACTION;
pub const KTMOBJECT_TRANSACTION_MANAGER = KTMOBJECT_TYPE.TRANSACTION_MANAGER;
pub const KTMOBJECT_RESOURCE_MANAGER = KTMOBJECT_TYPE.RESOURCE_MANAGER;
pub const KTMOBJECT_ENLISTMENT = KTMOBJECT_TYPE.ENLISTMENT;
pub const KTMOBJECT_INVALID = KTMOBJECT_TYPE.INVALID;
pub const KTMOBJECT_CURSOR = extern struct {
LastQuery: Guid,
ObjectIdCount: u32,
ObjectIds: [1]Guid,
};
pub const PTP_SIMPLE_CALLBACK = fn(
Instance: ?*TP_CALLBACK_INSTANCE,
Context: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
pub const TP_CALLBACK_PRIORITY = enum(i32) {
HIGH = 0,
NORMAL = 1,
LOW = 2,
INVALID = 3,
// COUNT = 3, this enum value conflicts with INVALID
};
pub const TP_CALLBACK_PRIORITY_HIGH = TP_CALLBACK_PRIORITY.HIGH;
pub const TP_CALLBACK_PRIORITY_NORMAL = TP_CALLBACK_PRIORITY.NORMAL;
pub const TP_CALLBACK_PRIORITY_LOW = TP_CALLBACK_PRIORITY.LOW;
pub const TP_CALLBACK_PRIORITY_INVALID = TP_CALLBACK_PRIORITY.INVALID;
pub const TP_CALLBACK_PRIORITY_COUNT = TP_CALLBACK_PRIORITY.INVALID;
pub const TP_POOL_STACK_INFORMATION = extern struct {
StackReserve: usize,
StackCommit: usize,
};
pub const PTP_CLEANUP_GROUP_CANCEL_CALLBACK = fn(
ObjectContext: ?*c_void,
CleanupContext: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
pub const TP_CALLBACK_ENVIRON_V3 = extern struct {
pub const _ACTIVATION_CONTEXT = extern struct {
placeholder: usize, // TODO: why is this type empty?
};
Version: u32,
Pool: PTP_POOL,
CleanupGroup: isize,
CleanupGroupCancelCallback: ?PTP_CLEANUP_GROUP_CANCEL_CALLBACK,
RaceDll: ?*c_void,
ActivationContext: isize,
FinalizationCallback: ?PTP_SIMPLE_CALLBACK,
u: extern union {
Flags: u32,
s: extern struct {
_bitfield: u32,
},
},
CallbackPriority: TP_CALLBACK_PRIORITY,
Size: u32,
};
pub const PTP_WORK_CALLBACK = fn(
Instance: ?*TP_CALLBACK_INSTANCE,
Context: ?*c_void,
Work: ?*TP_WORK,
) callconv(@import("std").os.windows.WINAPI) void;
pub const PTP_TIMER_CALLBACK = fn(
Instance: ?*TP_CALLBACK_INSTANCE,
Context: ?*c_void,
Timer: ?*TP_TIMER,
) callconv(@import("std").os.windows.WINAPI) void;
pub const PTP_WAIT_CALLBACK = fn(
Instance: ?*TP_CALLBACK_INSTANCE,
Context: ?*c_void,
Wait: ?*TP_WAIT,
WaitResult: u32,
) callconv(@import("std").os.windows.WINAPI) void;
pub const OVERLAPPED = extern struct {
Internal: usize,
InternalHigh: usize,
Anonymous: extern union {
Anonymous: extern struct {
Offset: u32,
OffsetHigh: u32,
},
Pointer: ?*c_void,
},
hEvent: ?HANDLE,
};
pub const PROCESS_HEAP_ENTRY = extern struct {
lpData: ?*c_void,
cbData: u32,
cbOverhead: u8,
iRegionIndex: u8,
wFlags: u16,
Anonymous: extern union {
Block: extern struct {
hMem: ?HANDLE,
dwReserved: [3]u32,
},
Region: extern struct {
dwCommittedSize: u32,
dwUnCommittedSize: u32,
lpFirstBlock: ?*c_void,
lpLastBlock: ?*c_void,
},
},
};
pub const REASON_CONTEXT = extern struct {
Version: u32,
Flags: POWER_REQUEST_CONTEXT_FLAGS,
Reason: extern union {
Detailed: extern struct {
LocalizedReasonModule: ?HINSTANCE,
LocalizedReasonId: u32,
ReasonStringCount: u32,
ReasonStrings: ?*?PWSTR,
},
SimpleReasonString: ?PWSTR,
},
};
pub const LPTHREAD_START_ROUTINE = fn(
lpThreadParameter: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const RPC_IMPORT_CONTEXT_P = extern struct {
LookupContext: ?*c_void,
ProposedHandle: ?*c_void,
Bindings: ?*RPC_BINDING_VECTOR,
};
pub const RemHGLOBAL = extern struct {
fNullHGlobal: i32,
cbData: u32,
data: [1]u8,
};
pub const RemHMETAFILEPICT = extern struct {
mm: i32,
xExt: i32,
yExt: i32,
cbData: u32,
data: [1]u8,
};
pub const RemHENHMETAFILE = extern struct {
cbData: u32,
data: [1]u8,
};
pub const RemHBITMAP = extern struct {
cbData: u32,
data: [1]u8,
};
pub const RemHPALETTE = extern struct {
cbData: u32,
data: [1]u8,
};
pub const RemBRUSH = extern struct {
cbData: u32,
data: [1]u8,
};
pub const userCLIPFORMAT = extern struct {
fContext: i32,
u: extern struct {
dwValue: u32,
pwszName: ?PWSTR,
},
};
pub const GDI_NONREMOTE = extern struct {
fContext: i32,
u: extern struct {
hInproc: i32,
hRemote: ?*DWORD_BLOB,
},
};
pub const userHGLOBAL = extern struct {
fContext: i32,
u: extern struct {
hInproc: i32,
hRemote: ?*FLAGGED_BYTE_BLOB,
hInproc64: i64,
},
};
pub const userHMETAFILE = extern struct {
fContext: i32,
u: extern struct {
hInproc: i32,
hRemote: ?*BYTE_BLOB,
hInproc64: i64,
},
};
pub const remoteMETAFILEPICT = extern struct {
mm: i32,
xExt: i32,
yExt: i32,
hMF: ?*userHMETAFILE,
};
pub const userHMETAFILEPICT = extern struct {
fContext: i32,
u: extern struct {
hInproc: i32,
hRemote: ?*remoteMETAFILEPICT,
hInproc64: i64,
},
};
pub const userHENHMETAFILE = extern struct {
fContext: i32,
u: extern struct {
hInproc: i32,
hRemote: ?*BYTE_BLOB,
hInproc64: i64,
},
};
pub const userBITMAP = extern struct {
bmType: i32,
bmWidth: i32,
bmHeight: i32,
bmWidthBytes: i32,
bmPlanes: u16,
bmBitsPixel: u16,
cbSize: u32,
pBuffer: [1]u8,
};
pub const userHBITMAP = extern struct {
fContext: i32,
u: extern struct {
hInproc: i32,
hRemote: ?*userBITMAP,
hInproc64: i64,
},
};
pub const userHPALETTE = extern struct {
fContext: i32,
u: extern struct {
hInproc: i32,
hRemote: ?*LOGPALETTE,
hInproc64: i64,
},
};
pub const RemotableHandle = extern struct {
fContext: i32,
u: extern struct {
hInproc: i32,
hRemote: i32,
},
};
pub const CY = extern union {
Anonymous: extern struct {
Lo: u32,
Hi: i32,
},
int64: i64,
};
pub const DECIMAL = extern struct {
wReserved: u16,
Anonymous1: extern union {
Anonymous: extern struct {
scale: u8,
sign: u8,
},
signscale: u16,
},
Hi32: u32,
Anonymous2: extern union {
Anonymous: extern struct {
Lo32: u32,
Mid32: u32,
},
Lo64: u64,
},
};
pub const BSTRBLOB = extern struct {
cbSize: u32,
pData: ?*u8,
};
pub const CLIPDATA = extern struct {
cbSize: u32,
ulClipFmt: i32,
pClipData: ?*u8,
};
pub const uCLSSPEC = extern struct {
tyspec: u32,
tagged_union: extern struct {
clsid: Guid,
pFileExt: ?PWSTR,
pMimeType: ?PWSTR,
pProgId: ?PWSTR,
pFileName: ?PWSTR,
ByName: extern struct {
pPackageName: ?PWSTR,
PolicyId: Guid,
},
ByObjectId: extern struct {
ObjectId: Guid,
PolicyId: Guid,
},
},
};
const IID_IServiceProvider_Value = @import("../zig.zig").Guid.initString("6d5140c1-7436-11ce-8034-00aa006009fa");
pub const IID_IServiceProvider = &IID_IServiceProvider_Value;
pub const IServiceProvider = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
QueryService: fn(
self: *const IServiceProvider,
guidService: ?*const Guid,
riid: ?*const Guid,
ppvObject: ?*?*c_void,
) 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 IServiceProvider_QueryService(self: *const T, guidService: ?*const Guid, riid: ?*const Guid, ppvObject: ?*?*c_void) callconv(.Inline) HRESULT {
return @ptrCast(*const IServiceProvider.VTable, self.vtable).QueryService(@ptrCast(*const IServiceProvider, self), guidService, riid, ppvObject);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const LPTIMECALLBACK = fn(
uTimerID: u32,
uMsg: u32,
dwUser: usize,
dw1: usize,
dw2: usize,
) callconv(@import("std").os.windows.WINAPI) void;
pub const LPD3DVALIDATECALLBACK = fn(
lpUserArg: ?*c_void,
dwOffset: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const LPD3DENUMTEXTUREFORMATSCALLBACK = fn(
lpDdsd: ?*DDSURFACEDESC,
lpContext: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const LPD3DENUMPIXELFORMATSCALLBACK = fn(
lpDDPixFmt: ?*DDPIXELFORMAT,
lpContext: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const D3DHVERTEX = extern struct {
dwFlags: u32,
Anonymous1: extern union {
hx: f32,
dvHX: f32,
},
Anonymous2: extern union {
hy: f32,
dvHY: f32,
},
Anonymous3: extern union {
hz: f32,
dvHZ: f32,
},
};
pub const D3DTLVERTEX = extern struct {
Anonymous1: extern union {
sx: f32,
dvSX: f32,
},
Anonymous2: extern union {
sy: f32,
dvSY: f32,
},
Anonymous3: extern union {
sz: f32,
dvSZ: f32,
},
Anonymous4: extern union {
rhw: f32,
dvRHW: f32,
},
Anonymous5: extern union {
color: u32,
dcColor: u32,
},
Anonymous6: extern union {
specular: u32,
dcSpecular: u32,
},
Anonymous7: extern union {
tu: f32,
dvTU: f32,
},
Anonymous8: extern union {
tv: f32,
dvTV: f32,
},
};
pub const D3DLVERTEX = extern struct {
Anonymous1: extern union {
x: f32,
dvX: f32,
},
Anonymous2: extern union {
y: f32,
dvY: f32,
},
Anonymous3: extern union {
z: f32,
dvZ: f32,
},
dwReserved: u32,
Anonymous4: extern union {
color: u32,
dcColor: u32,
},
Anonymous5: extern union {
specular: u32,
dcSpecular: u32,
},
Anonymous6: extern union {
tu: f32,
dvTU: f32,
},
Anonymous7: extern union {
tv: f32,
dvTV: f32,
},
};
pub const D3DVERTEX = extern struct {
Anonymous1: extern union {
x: f32,
dvX: f32,
},
Anonymous2: extern union {
y: f32,
dvY: f32,
},
Anonymous3: extern union {
z: f32,
dvZ: f32,
},
Anonymous4: extern union {
nx: f32,
dvNX: f32,
},
Anonymous5: extern union {
ny: f32,
dvNY: f32,
},
Anonymous6: extern union {
nz: f32,
dvNZ: f32,
},
Anonymous7: extern union {
tu: f32,
dvTU: f32,
},
Anonymous8: extern union {
tv: f32,
dvTV: f32,
},
};
pub const D3DVIEWPORT = extern struct {
dwSize: u32,
dwX: u32,
dwY: u32,
dwWidth: u32,
dwHeight: u32,
dvScaleX: f32,
dvScaleY: f32,
dvMaxX: f32,
dvMaxY: f32,
dvMinZ: f32,
dvMaxZ: f32,
};
pub const D3DVIEWPORT2 = extern struct {
dwSize: u32,
dwX: u32,
dwY: u32,
dwWidth: u32,
dwHeight: u32,
dvClipX: f32,
dvClipY: f32,
dvClipWidth: f32,
dvClipHeight: f32,
dvMinZ: f32,
dvMaxZ: f32,
};
pub const D3DVIEWPORT7 = extern struct {
dwX: u32,
dwY: u32,
dwWidth: u32,
dwHeight: u32,
dvMinZ: f32,
dvMaxZ: f32,
};
pub const D3DTRANSFORMDATA = extern struct {
dwSize: u32,
lpIn: ?*c_void,
dwInSize: u32,
lpOut: ?*c_void,
dwOutSize: u32,
lpHOut: ?*D3DHVERTEX,
dwClip: u32,
dwClipIntersection: u32,
dwClipUnion: u32,
drExtent: D3DRECT,
};
pub const D3DLIGHTINGELEMENT = extern struct {
dvPosition: D3DVECTOR,
dvNormal: D3DVECTOR,
};
pub const D3DMATERIAL = extern struct {
dwSize: u32,
Anonymous1: extern union {
diffuse: D3DCOLORVALUE,
dcvDiffuse: D3DCOLORVALUE,
},
Anonymous2: extern union {
ambient: D3DCOLORVALUE,
dcvAmbient: D3DCOLORVALUE,
},
Anonymous3: extern union {
specular: D3DCOLORVALUE,
dcvSpecular: D3DCOLORVALUE,
},
Anonymous4: extern union {
emissive: D3DCOLORVALUE,
dcvEmissive: D3DCOLORVALUE,
},
Anonymous5: extern union {
power: f32,
dvPower: f32,
},
hTexture: u32,
dwRampSize: u32,
};
pub const D3DMATERIAL7 = extern struct {
Anonymous1: extern union {
diffuse: D3DCOLORVALUE,
dcvDiffuse: D3DCOLORVALUE,
},
Anonymous2: extern union {
ambient: D3DCOLORVALUE,
dcvAmbient: D3DCOLORVALUE,
},
Anonymous3: extern union {
specular: D3DCOLORVALUE,
dcvSpecular: D3DCOLORVALUE,
},
Anonymous4: extern union {
emissive: D3DCOLORVALUE,
dcvEmissive: D3DCOLORVALUE,
},
Anonymous5: extern union {
power: f32,
dvPower: f32,
},
};
pub const D3DLIGHT = extern struct {
dwSize: u32,
dltType: D3DLIGHTTYPE,
dcvColor: D3DCOLORVALUE,
dvPosition: D3DVECTOR,
dvDirection: D3DVECTOR,
dvRange: f32,
dvFalloff: f32,
dvAttenuation0: f32,
dvAttenuation1: f32,
dvAttenuation2: f32,
dvTheta: f32,
dvPhi: f32,
};
pub const D3DLIGHT7 = extern struct {
dltType: D3DLIGHTTYPE,
dcvDiffuse: D3DCOLORVALUE,
dcvSpecular: D3DCOLORVALUE,
dcvAmbient: D3DCOLORVALUE,
dvPosition: D3DVECTOR,
dvDirection: D3DVECTOR,
dvRange: f32,
dvFalloff: f32,
dvAttenuation0: f32,
dvAttenuation1: f32,
dvAttenuation2: f32,
dvTheta: f32,
dvPhi: f32,
};
pub const D3DLIGHT2 = extern struct {
dwSize: u32,
dltType: D3DLIGHTTYPE,
dcvColor: D3DCOLORVALUE,
dvPosition: D3DVECTOR,
dvDirection: D3DVECTOR,
dvRange: f32,
dvFalloff: f32,
dvAttenuation0: f32,
dvAttenuation1: f32,
dvAttenuation2: f32,
dvTheta: f32,
dvPhi: f32,
dwFlags: u32,
};
pub const D3DLIGHTDATA = extern struct {
dwSize: u32,
lpIn: ?*D3DLIGHTINGELEMENT,
dwInSize: u32,
lpOut: ?*D3DTLVERTEX,
dwOutSize: u32,
};
pub const D3DOPCODE = enum(i32) {
POINT = 1,
LINE = 2,
TRIANGLE = 3,
MATRIXLOAD = 4,
MATRIXMULTIPLY = 5,
STATETRANSFORM = 6,
STATELIGHT = 7,
STATERENDER = 8,
PROCESSVERTICES = 9,
TEXTURELOAD = 10,
EXIT = 11,
BRANCHFORWARD = 12,
SPAN = 13,
SETSTATUS = 14,
FORCE_DWORD = 2147483647,
};
pub const D3DOP_POINT = D3DOPCODE.POINT;
pub const D3DOP_LINE = D3DOPCODE.LINE;
pub const D3DOP_TRIANGLE = D3DOPCODE.TRIANGLE;
pub const D3DOP_MATRIXLOAD = D3DOPCODE.MATRIXLOAD;
pub const D3DOP_MATRIXMULTIPLY = D3DOPCODE.MATRIXMULTIPLY;
pub const D3DOP_STATETRANSFORM = D3DOPCODE.STATETRANSFORM;
pub const D3DOP_STATELIGHT = D3DOPCODE.STATELIGHT;
pub const D3DOP_STATERENDER = D3DOPCODE.STATERENDER;
pub const D3DOP_PROCESSVERTICES = D3DOPCODE.PROCESSVERTICES;
pub const D3DOP_TEXTURELOAD = D3DOPCODE.TEXTURELOAD;
pub const D3DOP_EXIT = D3DOPCODE.EXIT;
pub const D3DOP_BRANCHFORWARD = D3DOPCODE.BRANCHFORWARD;
pub const D3DOP_SPAN = D3DOPCODE.SPAN;
pub const D3DOP_SETSTATUS = D3DOPCODE.SETSTATUS;
pub const D3DOP_FORCE_DWORD = D3DOPCODE.FORCE_DWORD;
pub const D3DINSTRUCTION = extern struct {
bOpcode: u8,
bSize: u8,
wCount: u16,
};
pub const D3DTEXTURELOAD = extern struct {
hDestTexture: u32,
hSrcTexture: u32,
};
pub const D3DPICKRECORD = extern struct {
bOpcode: u8,
bPad: u8,
dwOffset: u32,
dvZ: f32,
};
pub const D3DLINEPATTERN = extern struct {
wRepeatFactor: u16,
wLinePattern: u16,
};
pub const D3DTEXTUREFILTER = enum(i32) {
NEAREST = 1,
LINEAR = 2,
MIPNEAREST = 3,
MIPLINEAR = 4,
LINEARMIPNEAREST = 5,
LINEARMIPLINEAR = 6,
FORCE_DWORD = 2147483647,
};
pub const D3DFILTER_NEAREST = D3DTEXTUREFILTER.NEAREST;
pub const D3DFILTER_LINEAR = D3DTEXTUREFILTER.LINEAR;
pub const D3DFILTER_MIPNEAREST = D3DTEXTUREFILTER.MIPNEAREST;
pub const D3DFILTER_MIPLINEAR = D3DTEXTUREFILTER.MIPLINEAR;
pub const D3DFILTER_LINEARMIPNEAREST = D3DTEXTUREFILTER.LINEARMIPNEAREST;
pub const D3DFILTER_LINEARMIPLINEAR = D3DTEXTUREFILTER.LINEARMIPLINEAR;
pub const D3DFILTER_FORCE_DWORD = D3DTEXTUREFILTER.FORCE_DWORD;
pub const D3DTEXTUREBLEND = enum(i32) {
DECAL = 1,
MODULATE = 2,
DECALALPHA = 3,
MODULATEALPHA = 4,
DECALMASK = 5,
MODULATEMASK = 6,
COPY = 7,
ADD = 8,
FORCE_DWORD = 2147483647,
};
pub const D3DTBLEND_DECAL = D3DTEXTUREBLEND.DECAL;
pub const D3DTBLEND_MODULATE = D3DTEXTUREBLEND.MODULATE;
pub const D3DTBLEND_DECALALPHA = D3DTEXTUREBLEND.DECALALPHA;
pub const D3DTBLEND_MODULATEALPHA = D3DTEXTUREBLEND.MODULATEALPHA;
pub const D3DTBLEND_DECALMASK = D3DTEXTUREBLEND.DECALMASK;
pub const D3DTBLEND_MODULATEMASK = D3DTEXTUREBLEND.MODULATEMASK;
pub const D3DTBLEND_COPY = D3DTEXTUREBLEND.COPY;
pub const D3DTBLEND_ADD = D3DTEXTUREBLEND.ADD;
pub const D3DTBLEND_FORCE_DWORD = D3DTEXTUREBLEND.FORCE_DWORD;
pub const D3DANTIALIASMODE = enum(i32) {
NONE = 0,
SORTDEPENDENT = 1,
SORTINDEPENDENT = 2,
FORCE_DWORD = 2147483647,
};
pub const D3DANTIALIAS_NONE = D3DANTIALIASMODE.NONE;
pub const D3DANTIALIAS_SORTDEPENDENT = D3DANTIALIASMODE.SORTDEPENDENT;
pub const D3DANTIALIAS_SORTINDEPENDENT = D3DANTIALIASMODE.SORTINDEPENDENT;
pub const D3DANTIALIAS_FORCE_DWORD = D3DANTIALIASMODE.FORCE_DWORD;
pub const D3DVERTEXTYPE = enum(i32) {
VERTEX = 1,
LVERTEX = 2,
TLVERTEX = 3,
FORCE_DWORD = 2147483647,
};
pub const D3DVT_VERTEX = D3DVERTEXTYPE.VERTEX;
pub const D3DVT_LVERTEX = D3DVERTEXTYPE.LVERTEX;
pub const D3DVT_TLVERTEX = D3DVERTEXTYPE.TLVERTEX;
pub const D3DVT_FORCE_DWORD = D3DVERTEXTYPE.FORCE_DWORD;
pub const D3DLIGHTSTATETYPE = enum(i32) {
MATERIAL = 1,
AMBIENT = 2,
COLORMODEL = 3,
FOGMODE = 4,
FOGSTART = 5,
FOGEND = 6,
FOGDENSITY = 7,
COLORVERTEX = 8,
FORCE_DWORD = 2147483647,
};
pub const D3DLIGHTSTATE_MATERIAL = D3DLIGHTSTATETYPE.MATERIAL;
pub const D3DLIGHTSTATE_AMBIENT = D3DLIGHTSTATETYPE.AMBIENT;
pub const D3DLIGHTSTATE_COLORMODEL = D3DLIGHTSTATETYPE.COLORMODEL;
pub const D3DLIGHTSTATE_FOGMODE = D3DLIGHTSTATETYPE.FOGMODE;
pub const D3DLIGHTSTATE_FOGSTART = D3DLIGHTSTATETYPE.FOGSTART;
pub const D3DLIGHTSTATE_FOGEND = D3DLIGHTSTATETYPE.FOGEND;
pub const D3DLIGHTSTATE_FOGDENSITY = D3DLIGHTSTATETYPE.FOGDENSITY;
pub const D3DLIGHTSTATE_COLORVERTEX = D3DLIGHTSTATETYPE.COLORVERTEX;
pub const D3DLIGHTSTATE_FORCE_DWORD = D3DLIGHTSTATETYPE.FORCE_DWORD;
pub const D3DSTATE = extern struct {
Anonymous1: extern union {
dtstTransformStateType: D3DTRANSFORMSTATETYPE,
dlstLightStateType: D3DLIGHTSTATETYPE,
drstRenderStateType: D3DRENDERSTATETYPE,
},
Anonymous2: extern union {
dwArg: [1]u32,
dvArg: [1]f32,
},
};
pub const D3DMATRIXLOAD = extern struct {
hDestMatrix: u32,
hSrcMatrix: u32,
};
pub const D3DMATRIXMULTIPLY = extern struct {
hDestMatrix: u32,
hSrcMatrix1: u32,
hSrcMatrix2: u32,
};
pub const D3DPROCESSVERTICES = extern struct {
dwFlags: u32,
wStart: u16,
wDest: u16,
dwCount: u32,
dwReserved: u32,
};
pub const D3DTEXTUREMAGFILTER = enum(i32) {
POINT = 1,
LINEAR = 2,
FLATCUBIC = 3,
GAUSSIANCUBIC = 4,
ANISOTROPIC = 5,
FORCE_DWORD = 2147483647,
};
pub const D3DTFG_POINT = D3DTEXTUREMAGFILTER.POINT;
pub const D3DTFG_LINEAR = D3DTEXTUREMAGFILTER.LINEAR;
pub const D3DTFG_FLATCUBIC = D3DTEXTUREMAGFILTER.FLATCUBIC;
pub const D3DTFG_GAUSSIANCUBIC = D3DTEXTUREMAGFILTER.GAUSSIANCUBIC;
pub const D3DTFG_ANISOTROPIC = D3DTEXTUREMAGFILTER.ANISOTROPIC;
pub const D3DTFG_FORCE_DWORD = D3DTEXTUREMAGFILTER.FORCE_DWORD;
pub const D3DTEXTUREMINFILTER = enum(i32) {
POINT = 1,
LINEAR = 2,
ANISOTROPIC = 3,
FORCE_DWORD = 2147483647,
};
pub const D3DTFN_POINT = D3DTEXTUREMINFILTER.POINT;
pub const D3DTFN_LINEAR = D3DTEXTUREMINFILTER.LINEAR;
pub const D3DTFN_ANISOTROPIC = D3DTEXTUREMINFILTER.ANISOTROPIC;
pub const D3DTFN_FORCE_DWORD = D3DTEXTUREMINFILTER.FORCE_DWORD;
pub const D3DTEXTUREMIPFILTER = enum(i32) {
NONE = 1,
POINT = 2,
LINEAR = 3,
FORCE_DWORD = 2147483647,
};
pub const D3DTFP_NONE = D3DTEXTUREMIPFILTER.NONE;
pub const D3DTFP_POINT = D3DTEXTUREMIPFILTER.POINT;
pub const D3DTFP_LINEAR = D3DTEXTUREMIPFILTER.LINEAR;
pub const D3DTFP_FORCE_DWORD = D3DTEXTUREMIPFILTER.FORCE_DWORD;
pub const D3DTRIANGLE = extern struct {
Anonymous1: extern union {
v1: u16,
wV1: u16,
},
Anonymous2: extern union {
v2: u16,
wV2: u16,
},
Anonymous3: extern union {
v3: u16,
wV3: u16,
},
wFlags: u16,
};
pub const D3DLINE = extern struct {
Anonymous1: extern union {
v1: u16,
wV1: u16,
},
Anonymous2: extern union {
v2: u16,
wV2: u16,
},
};
pub const D3DSPAN = extern struct {
wCount: u16,
wFirst: u16,
};
pub const D3DPOINT = extern struct {
wCount: u16,
wFirst: u16,
};
pub const D3DBRANCH = extern struct {
dwMask: u32,
dwValue: u32,
bNegate: BOOL,
dwOffset: u32,
};
pub const D3DSTATUS = extern struct {
dwFlags: u32,
dwStatus: u32,
drExtent: D3DRECT,
};
pub const D3DCLIPSTATUS = extern struct {
dwFlags: u32,
dwStatus: u32,
minx: f32,
maxx: f32,
miny: f32,
maxy: f32,
minz: f32,
maxz: f32,
};
pub const D3DSTATS = extern struct {
dwSize: u32,
dwTrianglesDrawn: u32,
dwLinesDrawn: u32,
dwPointsDrawn: u32,
dwSpansDrawn: u32,
dwVerticesProcessed: u32,
};
pub const D3DEXECUTEDATA = extern struct {
dwSize: u32,
dwVertexOffset: u32,
dwVertexCount: u32,
dwInstructionOffset: u32,
dwInstructionLength: u32,
dwHVertexOffset: u32,
dsStatus: D3DSTATUS,
};
pub const D3DVERTEXBUFFERDESC = extern struct {
dwSize: u32,
dwCaps: u32,
dwFVF: u32,
dwNumVertices: u32,
};
pub const D3DDP_PTRSTRIDE = extern struct {
lpvData: ?*c_void,
dwStride: u32,
};
pub const D3DDRAWPRIMITIVESTRIDEDDATA = extern struct {
position: D3DDP_PTRSTRIDE,
normal: D3DDP_PTRSTRIDE,
diffuse: D3DDP_PTRSTRIDE,
specular: D3DDP_PTRSTRIDE,
textureCoords: [8]D3DDP_PTRSTRIDE,
};
pub const D3DTRANSFORMCAPS = extern struct {
dwSize: u32,
dwCaps: u32,
};
pub const D3DLIGHTINGCAPS = extern struct {
dwSize: u32,
dwCaps: u32,
dwLightingModel: u32,
dwNumLights: u32,
};
pub const _D3DPrimCaps = extern struct {
dwSize: u32,
dwMiscCaps: u32,
dwRasterCaps: u32,
dwZCmpCaps: u32,
dwSrcBlendCaps: u32,
dwDestBlendCaps: u32,
dwAlphaCmpCaps: u32,
dwShadeCaps: u32,
dwTextureCaps: u32,
dwTextureFilterCaps: u32,
dwTextureBlendCaps: u32,
dwTextureAddressCaps: u32,
dwStippleWidth: u32,
dwStippleHeight: u32,
};
pub const _D3DDeviceDesc = extern struct {
dwSize: u32,
dwFlags: u32,
dcmColorModel: u32,
dwDevCaps: u32,
dtcTransformCaps: D3DTRANSFORMCAPS,
bClipping: BOOL,
dlcLightingCaps: D3DLIGHTINGCAPS,
dpcLineCaps: _D3DPrimCaps,
dpcTriCaps: _D3DPrimCaps,
dwDeviceRenderBitDepth: u32,
dwDeviceZBufferBitDepth: u32,
dwMaxBufferSize: u32,
dwMaxVertexCount: u32,
dwMinTextureWidth: u32,
dwMinTextureHeight: u32,
dwMaxTextureWidth: u32,
dwMaxTextureHeight: u32,
dwMinStippleWidth: u32,
dwMaxStippleWidth: u32,
dwMinStippleHeight: u32,
dwMaxStippleHeight: u32,
dwMaxTextureRepeat: u32,
dwMaxTextureAspectRatio: u32,
dwMaxAnisotropy: u32,
dvGuardBandLeft: f32,
dvGuardBandTop: f32,
dvGuardBandRight: f32,
dvGuardBandBottom: f32,
dvExtentsAdjust: f32,
dwStencilCaps: u32,
dwFVFCaps: u32,
dwTextureOpCaps: u32,
wMaxTextureBlendStages: u16,
wMaxSimultaneousTextures: u16,
};
pub const _D3DDeviceDesc7 = extern struct {
dwDevCaps: u32,
dpcLineCaps: _D3DPrimCaps,
dpcTriCaps: _D3DPrimCaps,
dwDeviceRenderBitDepth: u32,
dwDeviceZBufferBitDepth: u32,
dwMinTextureWidth: u32,
dwMinTextureHeight: u32,
dwMaxTextureWidth: u32,
dwMaxTextureHeight: u32,
dwMaxTextureRepeat: u32,
dwMaxTextureAspectRatio: u32,
dwMaxAnisotropy: u32,
dvGuardBandLeft: f32,
dvGuardBandTop: f32,
dvGuardBandRight: f32,
dvGuardBandBottom: f32,
dvExtentsAdjust: f32,
dwStencilCaps: u32,
dwFVFCaps: u32,
dwTextureOpCaps: u32,
wMaxTextureBlendStages: u16,
wMaxSimultaneousTextures: u16,
dwMaxActiveLights: u32,
dvMaxVertexW: f32,
deviceGUID: Guid,
wMaxUserClipPlanes: u16,
wMaxVertexBlendMatrices: u16,
dwVertexProcessingCaps: u32,
dwReserved1: u32,
dwReserved2: u32,
dwReserved3: u32,
dwReserved4: u32,
};
pub const LPD3DENUMDEVICESCALLBACK = fn(
lpGuid: ?*Guid,
lpDeviceDescription: ?PSTR,
lpDeviceName: ?PSTR,
param3: ?*_D3DDeviceDesc,
param4: ?*_D3DDeviceDesc,
param5: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const LPD3DENUMDEVICESCALLBACK7 = fn(
lpDeviceDescription: ?PSTR,
lpDeviceName: ?PSTR,
param2: ?*_D3DDeviceDesc7,
param3: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const D3DFINDDEVICESEARCH = extern struct {
dwSize: u32,
dwFlags: u32,
bHardware: BOOL,
dcmColorModel: u32,
guid: Guid,
dwCaps: u32,
dpcPrimCaps: _D3DPrimCaps,
};
pub const D3DFINDDEVICERESULT = extern struct {
dwSize: u32,
guid: Guid,
ddHwDesc: _D3DDeviceDesc,
ddSwDesc: _D3DDeviceDesc,
};
pub const _D3DExecuteBufferDesc = extern struct {
dwSize: u32,
dwFlags: u32,
dwCaps: u32,
dwBufferSize: u32,
lpData: ?*c_void,
};
pub const D3DDEVINFO_TEXTUREMANAGER = extern struct {
bThrashing: BOOL,
dwApproxBytesDownloaded: u32,
dwNumEvicts: u32,
dwNumVidCreates: u32,
dwNumTexturesUsed: u32,
dwNumUsedTexInVid: u32,
dwWorkingSet: u32,
dwWorkingSetBytes: u32,
dwTotalManaged: u32,
dwTotalBytes: u32,
dwLastPri: u32,
};
pub const D3DDEVINFO_TEXTURING = extern struct {
dwNumLoads: u32,
dwApproxBytesLoaded: u32,
dwNumPreLoads: u32,
dwNumSet: u32,
dwNumCreates: u32,
dwNumDestroys: u32,
dwNumSetPriorities: u32,
dwNumSetLODs: u32,
dwNumLocks: u32,
dwNumGetDCs: u32,
};
pub const _D3DNTHALDeviceDesc_V1 = extern struct {
dwSize: u32,
dwFlags: u32,
dcmColorModel: u32,
dwDevCaps: u32,
dtcTransformCaps: D3DTRANSFORMCAPS,
bClipping: BOOL,
dlcLightingCaps: D3DLIGHTINGCAPS,
dpcLineCaps: _D3DPrimCaps,
dpcTriCaps: _D3DPrimCaps,
dwDeviceRenderBitDepth: u32,
dwDeviceZBufferBitDepth: u32,
dwMaxBufferSize: u32,
dwMaxVertexCount: u32,
};
pub const _D3DNTHALDeviceDesc_V2 = extern struct {
dwSize: u32,
dwFlags: u32,
dcmColorModel: u32,
dwDevCaps: u32,
dtcTransformCaps: D3DTRANSFORMCAPS,
bClipping: BOOL,
dlcLightingCaps: D3DLIGHTINGCAPS,
dpcLineCaps: _D3DPrimCaps,
dpcTriCaps: _D3DPrimCaps,
dwDeviceRenderBitDepth: u32,
dwDeviceZBufferBitDepth: u32,
dwMaxBufferSize: u32,
dwMaxVertexCount: u32,
dwMinTextureWidth: u32,
dwMinTextureHeight: u32,
dwMaxTextureWidth: u32,
dwMaxTextureHeight: u32,
dwMinStippleWidth: u32,
dwMaxStippleWidth: u32,
dwMinStippleHeight: u32,
dwMaxStippleHeight: u32,
};
pub const _D3DNTDeviceDesc_V3 = extern struct {
dwSize: u32,
dwFlags: u32,
dcmColorModel: u32,
dwDevCaps: u32,
dtcTransformCaps: D3DTRANSFORMCAPS,
bClipping: BOOL,
dlcLightingCaps: D3DLIGHTINGCAPS,
dpcLineCaps: _D3DPrimCaps,
dpcTriCaps: _D3DPrimCaps,
dwDeviceRenderBitDepth: u32,
dwDeviceZBufferBitDepth: u32,
dwMaxBufferSize: u32,
dwMaxVertexCount: u32,
dwMinTextureWidth: u32,
dwMinTextureHeight: u32,
dwMaxTextureWidth: u32,
dwMaxTextureHeight: u32,
dwMinStippleWidth: u32,
dwMaxStippleWidth: u32,
dwMinStippleHeight: u32,
dwMaxStippleHeight: u32,
dwMaxTextureRepeat: u32,
dwMaxTextureAspectRatio: u32,
dwMaxAnisotropy: u32,
dvGuardBandLeft: f32,
dvGuardBandTop: f32,
dvGuardBandRight: f32,
dvGuardBandBottom: f32,
dvExtentsAdjust: f32,
dwStencilCaps: u32,
dwFVFCaps: u32,
dwTextureOpCaps: u32,
wMaxTextureBlendStages: u16,
wMaxSimultaneousTextures: u16,
};
pub const D3DNTHAL_GLOBALDRIVERDATA = extern struct {
dwSize: u32,
hwCaps: _D3DNTHALDeviceDesc_V1,
dwNumVertices: u32,
dwNumClipVertices: u32,
dwNumTextureFormats: u32,
lpTextureFormats: ?*DDSURFACEDESC,
};
pub const D3DNTHAL_D3DDX6EXTENDEDCAPS = extern struct {
dwSize: u32,
dwMinTextureWidth: u32,
dwMaxTextureWidth: u32,
dwMinTextureHeight: u32,
dwMaxTextureHeight: u32,
dwMinStippleWidth: u32,
dwMaxStippleWidth: u32,
dwMinStippleHeight: u32,
dwMaxStippleHeight: u32,
dwMaxTextureRepeat: u32,
dwMaxTextureAspectRatio: u32,
dwMaxAnisotropy: u32,
dvGuardBandLeft: f32,
dvGuardBandTop: f32,
dvGuardBandRight: f32,
dvGuardBandBottom: f32,
dvExtentsAdjust: f32,
dwStencilCaps: u32,
dwFVFCaps: u32,
dwTextureOpCaps: u32,
wMaxTextureBlendStages: u16,
wMaxSimultaneousTextures: u16,
};
pub const D3DNTHAL_D3DEXTENDEDCAPS = extern struct {
dwSize: u32,
dwMinTextureWidth: u32,
dwMaxTextureWidth: u32,
dwMinTextureHeight: u32,
dwMaxTextureHeight: u32,
dwMinStippleWidth: u32,
dwMaxStippleWidth: u32,
dwMinStippleHeight: u32,
dwMaxStippleHeight: u32,
dwMaxTextureRepeat: u32,
dwMaxTextureAspectRatio: u32,
dwMaxAnisotropy: u32,
dvGuardBandLeft: f32,
dvGuardBandTop: f32,
dvGuardBandRight: f32,
dvGuardBandBottom: f32,
dvExtentsAdjust: f32,
dwStencilCaps: u32,
dwFVFCaps: u32,
dwTextureOpCaps: u32,
wMaxTextureBlendStages: u16,
wMaxSimultaneousTextures: u16,
dwMaxActiveLights: u32,
dvMaxVertexW: f32,
wMaxUserClipPlanes: u16,
wMaxVertexBlendMatrices: u16,
dwVertexProcessingCaps: u32,
dwReserved1: u32,
dwReserved2: u32,
dwReserved3: u32,
dwReserved4: u32,
};
pub const D3DNTHAL_CONTEXTCREATEDATA = extern struct {
Anonymous1: extern union {
lpDDGbl: ?*DD_DIRECTDRAW_GLOBAL,
lpDDLcl: ?*DD_DIRECTDRAW_LOCAL,
},
Anonymous2: extern union {
lpDDS: ?*DD_SURFACE_LOCAL,
lpDDSLcl: ?*DD_SURFACE_LOCAL,
},
Anonymous3: extern union {
lpDDSZ: ?*DD_SURFACE_LOCAL,
lpDDSZLcl: ?*DD_SURFACE_LOCAL,
},
dwPID: u32,
dwhContext: usize,
ddrval: HRESULT,
};
pub const D3DNTHAL_CONTEXTDESTROYDATA = extern struct {
dwhContext: usize,
ddrval: HRESULT,
};
pub const D3DNTHAL_CONTEXTDESTROYALLDATA = extern struct {
dwPID: u32,
ddrval: HRESULT,
};
pub const D3DNTHAL_SCENECAPTUREDATA = extern struct {
dwhContext: usize,
dwFlag: u32,
ddrval: HRESULT,
};
pub const D3DNTHAL_TEXTURECREATEDATA = extern struct {
dwhContext: usize,
hDDS: ?HANDLE,
dwHandle: usize,
ddrval: HRESULT,
};
pub const D3DNTHAL_TEXTUREDESTROYDATA = extern struct {
dwhContext: usize,
dwHandle: usize,
ddrval: HRESULT,
};
pub const D3DNTHAL_TEXTURESWAPDATA = extern struct {
dwhContext: usize,
dwHandle1: usize,
dwHandle2: usize,
ddrval: HRESULT,
};
pub const D3DNTHAL_TEXTUREGETSURFDATA = extern struct {
dwhContext: usize,
hDDS: ?HANDLE,
dwHandle: usize,
ddrval: HRESULT,
};
pub const LPD3DNTHAL_CONTEXTCREATECB = fn(
param0: ?*D3DNTHAL_CONTEXTCREATEDATA,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const LPD3DNTHAL_CONTEXTDESTROYCB = fn(
param0: ?*D3DNTHAL_CONTEXTDESTROYDATA,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const LPD3DNTHAL_CONTEXTDESTROYALLCB = fn(
param0: ?*D3DNTHAL_CONTEXTDESTROYALLDATA,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const LPD3DNTHAL_SCENECAPTURECB = fn(
param0: ?*D3DNTHAL_SCENECAPTUREDATA,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const LPD3DNTHAL_TEXTURECREATECB = fn(
param0: ?*D3DNTHAL_TEXTURECREATEDATA,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const LPD3DNTHAL_TEXTUREDESTROYCB = fn(
param0: ?*D3DNTHAL_TEXTUREDESTROYDATA,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const LPD3DNTHAL_TEXTURESWAPCB = fn(
param0: ?*D3DNTHAL_TEXTURESWAPDATA,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const LPD3DNTHAL_TEXTUREGETSURFCB = fn(
param0: ?*D3DNTHAL_TEXTUREGETSURFDATA,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const D3DNTHAL_CALLBACKS = extern struct {
dwSize: u32,
ContextCreate: ?LPD3DNTHAL_CONTEXTCREATECB,
ContextDestroy: ?LPD3DNTHAL_CONTEXTDESTROYCB,
ContextDestroyAll: ?LPD3DNTHAL_CONTEXTDESTROYALLCB,
SceneCapture: ?LPD3DNTHAL_SCENECAPTURECB,
dwReserved10: ?*c_void,
dwReserved11: ?*c_void,
dwReserved22: ?*c_void,
dwReserved23: ?*c_void,
dwReserved: usize,
TextureCreate: ?LPD3DNTHAL_TEXTURECREATECB,
TextureDestroy: ?LPD3DNTHAL_TEXTUREDESTROYCB,
TextureSwap: ?LPD3DNTHAL_TEXTURESWAPCB,
TextureGetSurf: ?LPD3DNTHAL_TEXTUREGETSURFCB,
dwReserved12: ?*c_void,
dwReserved13: ?*c_void,
dwReserved14: ?*c_void,
dwReserved15: ?*c_void,
dwReserved16: ?*c_void,
dwReserved17: ?*c_void,
dwReserved18: ?*c_void,
dwReserved19: ?*c_void,
dwReserved20: ?*c_void,
dwReserved21: ?*c_void,
dwReserved24: ?*c_void,
dwReserved0: usize,
dwReserved1: usize,
dwReserved2: usize,
dwReserved3: usize,
dwReserved4: usize,
dwReserved5: usize,
dwReserved6: usize,
dwReserved7: usize,
dwReserved8: usize,
dwReserved9: usize,
};
pub const D3DNTHAL_SETRENDERTARGETDATA = extern struct {
dwhContext: usize,
lpDDS: ?*DD_SURFACE_LOCAL,
lpDDSZ: ?*DD_SURFACE_LOCAL,
ddrval: HRESULT,
};
pub const LPD3DNTHAL_SETRENDERTARGETCB = fn(
param0: ?*D3DNTHAL_SETRENDERTARGETDATA,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const D3DNTHAL_CALLBACKS2 = extern struct {
dwSize: u32,
dwFlags: u32,
SetRenderTarget: ?LPD3DNTHAL_SETRENDERTARGETCB,
dwReserved1: ?*c_void,
dwReserved2: ?*c_void,
dwReserved3: ?*c_void,
dwReserved4: ?*c_void,
};
pub const D3DNTHAL_CLEAR2DATA = extern struct {
dwhContext: usize,
dwFlags: u32,
dwFillColor: u32,
dvFillDepth: f32,
dwFillStencil: u32,
lpRects: ?*D3DRECT,
dwNumRects: u32,
ddrval: HRESULT,
};
pub const D3DNTHAL_VALIDATETEXTURESTAGESTATEDATA = extern struct {
dwhContext: usize,
dwFlags: u32,
dwReserved: usize,
dwNumPasses: u32,
ddrval: HRESULT,
};
pub const D3DNTHAL_DP2COMMAND = extern struct {
bCommand: u8,
bReserved: u8,
Anonymous: extern union {
wPrimitiveCount: u16,
wStateCount: u16,
},
};
pub const D3DNTHAL_DP2OPERATION = enum(i32) {
POINTS = 1,
INDEXEDLINELIST = 2,
INDEXEDTRIANGLELIST = 3,
RENDERSTATE = 8,
LINELIST = 15,
LINESTRIP = 16,
INDEXEDLINESTRIP = 17,
TRIANGLELIST = 18,
TRIANGLESTRIP = 19,
INDEXEDTRIANGLESTRIP = 20,
TRIANGLEFAN = 21,
INDEXEDTRIANGLEFAN = 22,
TRIANGLEFAN_IMM = 23,
LINELIST_IMM = 24,
TEXTURESTAGESTATE = 25,
INDEXEDTRIANGLELIST2 = 26,
INDEXEDLINELIST2 = 27,
VIEWPORTINFO = 28,
WINFO = 29,
SETPALETTE = 30,
UPDATEPALETTE = 31,
ZRANGE = 32,
SETMATERIAL = 33,
SETLIGHT = 34,
CREATELIGHT = 35,
SETTRANSFORM = 36,
TEXBLT = 38,
STATESET = 39,
SETPRIORITY = 40,
SETRENDERTARGET = 41,
CLEAR = 42,
SETTEXLOD = 43,
SETCLIPPLANE = 44,
};
pub const D3DNTDP2OP_POINTS = D3DNTHAL_DP2OPERATION.POINTS;
pub const D3DNTDP2OP_INDEXEDLINELIST = D3DNTHAL_DP2OPERATION.INDEXEDLINELIST;
pub const D3DNTDP2OP_INDEXEDTRIANGLELIST = D3DNTHAL_DP2OPERATION.INDEXEDTRIANGLELIST;
pub const D3DNTDP2OP_RENDERSTATE = D3DNTHAL_DP2OPERATION.RENDERSTATE;
pub const D3DNTDP2OP_LINELIST = D3DNTHAL_DP2OPERATION.LINELIST;
pub const D3DNTDP2OP_LINESTRIP = D3DNTHAL_DP2OPERATION.LINESTRIP;
pub const D3DNTDP2OP_INDEXEDLINESTRIP = D3DNTHAL_DP2OPERATION.INDEXEDLINESTRIP;
pub const D3DNTDP2OP_TRIANGLELIST = D3DNTHAL_DP2OPERATION.TRIANGLELIST;
pub const D3DNTDP2OP_TRIANGLESTRIP = D3DNTHAL_DP2OPERATION.TRIANGLESTRIP;
pub const D3DNTDP2OP_INDEXEDTRIANGLESTRIP = D3DNTHAL_DP2OPERATION.INDEXEDTRIANGLESTRIP;
pub const D3DNTDP2OP_TRIANGLEFAN = D3DNTHAL_DP2OPERATION.TRIANGLEFAN;
pub const D3DNTDP2OP_INDEXEDTRIANGLEFAN = D3DNTHAL_DP2OPERATION.INDEXEDTRIANGLEFAN;
pub const D3DNTDP2OP_TRIANGLEFAN_IMM = D3DNTHAL_DP2OPERATION.TRIANGLEFAN_IMM;
pub const D3DNTDP2OP_LINELIST_IMM = D3DNTHAL_DP2OPERATION.LINELIST_IMM;
pub const D3DNTDP2OP_TEXTURESTAGESTATE = D3DNTHAL_DP2OPERATION.TEXTURESTAGESTATE;
pub const D3DNTDP2OP_INDEXEDTRIANGLELIST2 = D3DNTHAL_DP2OPERATION.INDEXEDTRIANGLELIST2;
pub const D3DNTDP2OP_INDEXEDLINELIST2 = D3DNTHAL_DP2OPERATION.INDEXEDLINELIST2;
pub const D3DNTDP2OP_VIEWPORTINFO = D3DNTHAL_DP2OPERATION.VIEWPORTINFO;
pub const D3DNTDP2OP_WINFO = D3DNTHAL_DP2OPERATION.WINFO;
pub const D3DNTDP2OP_SETPALETTE = D3DNTHAL_DP2OPERATION.SETPALETTE;
pub const D3DNTDP2OP_UPDATEPALETTE = D3DNTHAL_DP2OPERATION.UPDATEPALETTE;
pub const D3DNTDP2OP_ZRANGE = D3DNTHAL_DP2OPERATION.ZRANGE;
pub const D3DNTDP2OP_SETMATERIAL = D3DNTHAL_DP2OPERATION.SETMATERIAL;
pub const D3DNTDP2OP_SETLIGHT = D3DNTHAL_DP2OPERATION.SETLIGHT;
pub const D3DNTDP2OP_CREATELIGHT = D3DNTHAL_DP2OPERATION.CREATELIGHT;
pub const D3DNTDP2OP_SETTRANSFORM = D3DNTHAL_DP2OPERATION.SETTRANSFORM;
pub const D3DNTDP2OP_TEXBLT = D3DNTHAL_DP2OPERATION.TEXBLT;
pub const D3DNTDP2OP_STATESET = D3DNTHAL_DP2OPERATION.STATESET;
pub const D3DNTDP2OP_SETPRIORITY = D3DNTHAL_DP2OPERATION.SETPRIORITY;
pub const D3DNTDP2OP_SETRENDERTARGET = D3DNTHAL_DP2OPERATION.SETRENDERTARGET;
pub const D3DNTDP2OP_CLEAR = D3DNTHAL_DP2OPERATION.CLEAR;
pub const D3DNTDP2OP_SETTEXLOD = D3DNTHAL_DP2OPERATION.SETTEXLOD;
pub const D3DNTDP2OP_SETCLIPPLANE = D3DNTHAL_DP2OPERATION.SETCLIPPLANE;
pub const D3DNTHAL_DP2POINTS = extern struct {
wCount: u16,
wVStart: u16,
};
pub const D3DNTHAL_DP2STARTVERTEX = extern struct {
wVStart: u16,
};
pub const D3DNTHAL_DP2LINELIST = extern struct {
wVStart: u16,
};
pub const D3DNTHAL_DP2INDEXEDLINELIST = extern struct {
wV1: u16,
wV2: u16,
};
pub const D3DNTHAL_DP2LINESTRIP = extern struct {
wVStart: u16,
};
pub const D3DNTHAL_DP2INDEXEDLINESTRIP = extern struct {
wV: [2]u16,
};
pub const D3DNTHAL_DP2TRIANGLELIST = extern struct {
wVStart: u16,
};
pub const D3DNTHAL_DP2INDEXEDTRIANGLELIST = extern struct {
wV1: u16,
wV2: u16,
wV3: u16,
wFlags: u16,
};
pub const D3DNTHAL_DP2INDEXEDTRIANGLELIST2 = extern struct {
wV1: u16,
wV2: u16,
wV3: u16,
};
pub const D3DNTHAL_DP2TRIANGLESTRIP = extern struct {
wVStart: u16,
};
pub const D3DNTHAL_DP2INDEXEDTRIANGLESTRIP = extern struct {
wV: [3]u16,
};
pub const D3DNTHAL_DP2TRIANGLEFAN = extern struct {
wVStart: u16,
};
pub const D3DNTHAL_DP2INDEXEDTRIANGLEFAN = extern struct {
wV: [3]u16,
};
pub const D3DNTHAL_DP2TRIANGLEFAN_IMM = extern struct {
dwEdgeFlags: u32,
};
pub const D3DNTHAL_DP2RENDERSTATE = extern struct {
RenderState: D3DRENDERSTATETYPE,
Anonymous: extern union {
fState: f32,
dwState: u32,
},
};
pub const D3DNTHAL_DP2TEXTURESTAGESTATE = extern struct {
wStage: u16,
TSState: u16,
dwValue: u32,
};
pub const D3DNTHAL_DP2VIEWPORTINFO = extern struct {
dwX: u32,
dwY: u32,
dwWidth: u32,
dwHeight: u32,
};
pub const D3DNTHAL_DP2WINFO = extern struct {
dvWNear: f32,
dvWFar: f32,
};
pub const D3DNTHAL_DP2SETPALETTE = extern struct {
dwPaletteHandle: u32,
dwPaletteFlags: u32,
dwSurfaceHandle: u32,
};
pub const D3DNTHAL_DP2UPDATEPALETTE = extern struct {
dwPaletteHandle: u32,
wStartIndex: u16,
wNumEntries: u16,
};
pub const D3DNTHAL_DP2SETRENDERTARGET = extern struct {
hRenderTarget: u32,
hZBuffer: u32,
};
pub const D3DNTHAL_DP2STATESET = extern struct {
dwOperation: u32,
dwParam: u32,
sbType: D3DSTATEBLOCKTYPE,
};
pub const D3DNTHAL_DP2ZRANGE = extern struct {
dvMinZ: f32,
dvMaxZ: f32,
};
pub const D3DNTHAL_DP2SETLIGHT = extern struct {
dwIndex: u32,
Anonymous: extern union {
lightData: u32,
dwDataType: u32,
},
};
pub const D3DNTHAL_DP2SETCLIPPLANE = extern struct {
dwIndex: u32,
plane: [4]f32,
};
pub const D3DNTHAL_DP2CREATELIGHT = extern struct {
dwIndex: u32,
};
pub const D3DNTHAL_DP2SETTRANSFORM = extern struct {
xfrmType: D3DTRANSFORMSTATETYPE,
matrix: D3DMATRIX,
};
pub const D3DNTHAL_DP2EXT = extern struct {
dwExtToken: u32,
dwSize: u32,
};
pub const D3DNTHAL_DP2TEXBLT = extern struct {
dwDDDestSurface: u32,
dwDDSrcSurface: u32,
pDest: POINT,
rSrc: RECTL,
dwFlags: u32,
};
pub const D3DNTHAL_DP2SETPRIORITY = extern struct {
dwDDDestSurface: u32,
dwPriority: u32,
};
pub const D3DNTHAL_DP2CLEAR = extern struct {
dwFlags: u32,
dwFillColor: u32,
dvFillDepth: f32,
dwFillStencil: u32,
Rects: [1]RECT,
};
pub const D3DNTHAL_DP2SETTEXLOD = extern struct {
dwDDSurface: u32,
dwLOD: u32,
};
pub const D3DNTHAL_DRAWPRIMITIVES2DATA = extern struct {
dwhContext: usize,
dwFlags: u32,
dwVertexType: u32,
lpDDCommands: ?*DD_SURFACE_LOCAL,
dwCommandOffset: u32,
dwCommandLength: u32,
Anonymous1: extern union {
lpDDVertex: ?*DD_SURFACE_LOCAL,
lpVertices: ?*c_void,
},
dwVertexOffset: u32,
dwVertexLength: u32,
dwReqVertexBufSize: u32,
dwReqCommandBufSize: u32,
lpdwRStates: ?*u32,
Anonymous2: extern union {
dwVertexSize: u32,
ddrval: HRESULT,
},
dwErrorOffset: u32,
};
pub const LPD3DNTHAL_CLEAR2CB = fn(
param0: ?*D3DNTHAL_CLEAR2DATA,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const LPD3DNTHAL_VALIDATETEXTURESTAGESTATECB = fn(
param0: ?*D3DNTHAL_VALIDATETEXTURESTAGESTATEDATA,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const LPD3DNTHAL_DRAWPRIMITIVES2CB = fn(
param0: ?*D3DNTHAL_DRAWPRIMITIVES2DATA,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const D3DNTHAL_CALLBACKS3 = extern struct {
dwSize: u32,
dwFlags: u32,
Clear2: ?LPD3DNTHAL_CLEAR2CB,
lpvReserved: ?*c_void,
ValidateTextureStageState: ?LPD3DNTHAL_VALIDATETEXTURESTAGESTATECB,
DrawPrimitives2: ?LPD3DNTHAL_DRAWPRIMITIVES2CB,
};
pub const PFND3DNTPARSEUNKNOWNCOMMAND = fn(
lpvCommands: ?*c_void,
lplpvReturnedCommand: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const POINTE = extern struct {
x: f32,
y: f32,
};
pub const FLOAT_LONG = extern union {
e: f32,
l: i32,
};
pub const POINTFIX = extern struct {
x: i32,
y: i32,
};
pub const RECTFX = extern struct {
xLeft: i32,
yTop: i32,
xRight: i32,
yBottom: i32,
};
pub const LIGATURE = extern struct {
culSize: u32,
pwsz: ?PWSTR,
chglyph: u32,
ahglyph: [1]u32,
};
pub const FD_LIGATURE = extern struct {
culThis: u32,
ulType: u32,
cLigatures: u32,
alig: [1]LIGATURE,
};
pub const POINTQF = extern struct {
x: LARGE_INTEGER,
y: LARGE_INTEGER,
};
pub const PFN = fn(
) callconv(@import("std").os.windows.WINAPI) isize;
pub const CDDDXGK_REDIRBITMAPPRESENTINFO = extern struct {
NumDirtyRects: u32,
DirtyRect: ?*RECT,
NumContexts: u32,
hContext: [65]?HANDLE,
bDoNotSynchronizeWithDxContent: BOOLEAN,
};
// TODO: this function pointer causes dependency loop problems, so it's stubbed out
pub const FREEOBJPROC = fn() callconv(@import("std").os.windows.WINAPI) void;
pub const XFORMOBJ = extern struct {
ulReserved: u32,
};
pub const WNDOBJCHANGEPROC = fn(
pwo: ?*WNDOBJ,
fl: u32,
) callconv(@import("std").os.windows.WINAPI) void;
pub const HSEMAPHORE__ = extern struct {
unused: i32,
};
pub const SORTCOMP = fn(
pv1: ?*const c_void,
pv2: ?*const c_void,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const ENG_SYSTEM_ATTRIBUTE = enum(i32) {
ProcessorFeature = 1,
NumberOfProcessors = 2,
OptimumAvailableUserMemory = 3,
OptimumAvailableSystemMemory = 4,
};
pub const EngProcessorFeature = ENG_SYSTEM_ATTRIBUTE.ProcessorFeature;
pub const EngNumberOfProcessors = ENG_SYSTEM_ATTRIBUTE.NumberOfProcessors;
pub const EngOptimumAvailableUserMemory = ENG_SYSTEM_ATTRIBUTE.OptimumAvailableUserMemory;
pub const EngOptimumAvailableSystemMemory = ENG_SYSTEM_ATTRIBUTE.OptimumAvailableSystemMemory;
pub const ENG_DEVICE_ATTRIBUTE = enum(i32) {
RESERVED = 0,
ACCELERATION_LEVEL = 1,
};
pub const QDA_RESERVED = ENG_DEVICE_ATTRIBUTE.RESERVED;
pub const QDA_ACCELERATION_LEVEL = ENG_DEVICE_ATTRIBUTE.ACCELERATION_LEVEL;
pub const EMFINFO = extern struct {
nSize: u32,
hdc: ?HDC,
pvEMF: ?*u8,
pvCurrentRecord: ?*u8,
};
pub const PFN_DrvEnableDriver = fn(
param0: u32,
param1: u32,
param2: ?*DRVENABLEDATA,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvEnablePDEV = fn(
param0: ?*DEVMODEW,
param1: ?PWSTR,
param2: u32,
param3: ?*?HSURF,
param4: u32,
param5: ?*GDIINFO,
param6: u32,
param7: ?*DEVINFO,
param8: ?HDEV,
param9: ?PWSTR,
param10: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) DHPDEV;
pub const PFN_DrvCompletePDEV = fn(
param0: DHPDEV,
param1: ?HDEV,
) callconv(@import("std").os.windows.WINAPI) void;
pub const PFN_DrvResetDevice = fn(
param0: DHPDEV,
param1: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const PFN_DrvDisablePDEV = fn(
param0: DHPDEV,
) callconv(@import("std").os.windows.WINAPI) void;
pub const PFN_DrvSynchronize = fn(
param0: DHPDEV,
param1: ?*RECTL,
) callconv(@import("std").os.windows.WINAPI) void;
pub const PFN_DrvEnableSurface = fn(
param0: DHPDEV,
) callconv(@import("std").os.windows.WINAPI) ?HSURF;
pub const PFN_DrvDisableDriver = fn(
) callconv(@import("std").os.windows.WINAPI) void;
pub const PFN_DrvDisableSurface = fn(
param0: DHPDEV,
) callconv(@import("std").os.windows.WINAPI) void;
pub const PFN_DrvAssertMode = fn(
param0: DHPDEV,
param1: BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvTextOut = fn(
param0: ?*SURFOBJ,
param1: ?*STROBJ,
param2: ?*FONTOBJ,
param3: ?*CLIPOBJ,
param4: ?*RECTL,
param5: ?*RECTL,
param6: ?*BRUSHOBJ,
param7: ?*BRUSHOBJ,
param8: ?*POINTL,
param9: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvStretchBlt = fn(
param0: ?*SURFOBJ,
param1: ?*SURFOBJ,
param2: ?*SURFOBJ,
param3: ?*CLIPOBJ,
param4: ?*XLATEOBJ,
param5: ?*COLORADJUSTMENT,
param6: ?*POINTL,
param7: ?*RECTL,
param8: ?*RECTL,
param9: ?*POINTL,
param10: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvStretchBltROP = fn(
param0: ?*SURFOBJ,
param1: ?*SURFOBJ,
param2: ?*SURFOBJ,
param3: ?*CLIPOBJ,
param4: ?*XLATEOBJ,
param5: ?*COLORADJUSTMENT,
param6: ?*POINTL,
param7: ?*RECTL,
param8: ?*RECTL,
param9: ?*POINTL,
param10: u32,
param11: ?*BRUSHOBJ,
param12: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvTransparentBlt = fn(
param0: ?*SURFOBJ,
param1: ?*SURFOBJ,
param2: ?*CLIPOBJ,
param3: ?*XLATEOBJ,
param4: ?*RECTL,
param5: ?*RECTL,
param6: u32,
param7: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvPlgBlt = fn(
param0: ?*SURFOBJ,
param1: ?*SURFOBJ,
param2: ?*SURFOBJ,
param3: ?*CLIPOBJ,
param4: ?*XLATEOBJ,
param5: ?*COLORADJUSTMENT,
param6: ?*POINTL,
param7: ?*POINTFIX,
param8: ?*RECTL,
param9: ?*POINTL,
param10: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvBitBlt = fn(
param0: ?*SURFOBJ,
param1: ?*SURFOBJ,
param2: ?*SURFOBJ,
param3: ?*CLIPOBJ,
param4: ?*XLATEOBJ,
param5: ?*RECTL,
param6: ?*POINTL,
param7: ?*POINTL,
param8: ?*BRUSHOBJ,
param9: ?*POINTL,
param10: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvRealizeBrush = fn(
param0: ?*BRUSHOBJ,
param1: ?*SURFOBJ,
param2: ?*SURFOBJ,
param3: ?*SURFOBJ,
param4: ?*XLATEOBJ,
param5: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvCopyBits = fn(
param0: ?*SURFOBJ,
param1: ?*SURFOBJ,
param2: ?*CLIPOBJ,
param3: ?*XLATEOBJ,
param4: ?*RECTL,
param5: ?*POINTL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvDitherColor = fn(
param0: DHPDEV,
param1: u32,
param2: u32,
param3: ?*u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const PFN_DrvCreateDeviceBitmap = fn(
param0: DHPDEV,
param1: SIZE,
param2: u32,
) callconv(@import("std").os.windows.WINAPI) ?HBITMAP;
pub const PFN_DrvDeleteDeviceBitmap = fn(
param0: DHSURF,
) callconv(@import("std").os.windows.WINAPI) void;
pub const PFN_DrvSetPalette = fn(
param0: DHPDEV,
param1: ?*PALOBJ,
param2: u32,
param3: u32,
param4: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvEscape = fn(
param0: ?*SURFOBJ,
param1: u32,
param2: u32,
param3: ?*c_void,
param4: u32,
param5: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const PFN_DrvDrawEscape = fn(
param0: ?*SURFOBJ,
param1: u32,
param2: ?*CLIPOBJ,
param3: ?*RECTL,
param4: u32,
param5: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const PFN_DrvQueryFont = fn(
param0: DHPDEV,
param1: usize,
param2: u32,
param3: ?*usize,
) callconv(@import("std").os.windows.WINAPI) ?*IFIMETRICS;
pub const PFN_DrvQueryFontTree = fn(
param0: DHPDEV,
param1: usize,
param2: u32,
param3: u32,
param4: ?*usize,
) callconv(@import("std").os.windows.WINAPI) ?*c_void;
pub const PFN_DrvQueryFontData = fn(
param0: DHPDEV,
param1: ?*FONTOBJ,
param2: u32,
param3: u32,
param4: ?*GLYPHDATA,
param5: ?*c_void,
param6: u32,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const PFN_DrvFree = fn(
param0: ?*c_void,
param1: usize,
) callconv(@import("std").os.windows.WINAPI) void;
pub const PFN_DrvDestroyFont = fn(
param0: ?*FONTOBJ,
) callconv(@import("std").os.windows.WINAPI) void;
pub const PFN_DrvQueryFontCaps = fn(
param0: u32,
param1: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const PFN_DrvLoadFontFile = fn(
param0: u32,
param1: ?*usize,
param2: ?*?*c_void,
param3: ?*u32,
param4: ?*DESIGNVECTOR,
param5: u32,
param6: u32,
) callconv(@import("std").os.windows.WINAPI) usize;
pub const PFN_DrvUnloadFontFile = fn(
param0: usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvSetPointerShape = fn(
param0: ?*SURFOBJ,
param1: ?*SURFOBJ,
param2: ?*SURFOBJ,
param3: ?*XLATEOBJ,
param4: i32,
param5: i32,
param6: i32,
param7: i32,
param8: ?*RECTL,
param9: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const PFN_DrvMovePointer = fn(
pso: ?*SURFOBJ,
x: i32,
y: i32,
prcl: ?*RECTL,
) callconv(@import("std").os.windows.WINAPI) void;
pub const PFN_DrvSendPage = fn(
param0: ?*SURFOBJ,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvStartPage = fn(
pso: ?*SURFOBJ,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvStartDoc = fn(
pso: ?*SURFOBJ,
pwszDocName: ?PWSTR,
dwJobId: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvEndDoc = fn(
pso: ?*SURFOBJ,
fl: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvQuerySpoolType = fn(
dhpdev: DHPDEV,
pwchType: ?PWSTR,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvLineTo = fn(
param0: ?*SURFOBJ,
param1: ?*CLIPOBJ,
param2: ?*BRUSHOBJ,
param3: i32,
param4: i32,
param5: i32,
param6: i32,
param7: ?*RECTL,
param8: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvStrokePath = fn(
param0: ?*SURFOBJ,
param1: ?*PATHOBJ,
param2: ?*CLIPOBJ,
param3: ?*XFORMOBJ,
param4: ?*BRUSHOBJ,
param5: ?*POINTL,
param6: ?*LINEATTRS,
param7: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvFillPath = fn(
param0: ?*SURFOBJ,
param1: ?*PATHOBJ,
param2: ?*CLIPOBJ,
param3: ?*BRUSHOBJ,
param4: ?*POINTL,
param5: u32,
param6: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvStrokeAndFillPath = fn(
param0: ?*SURFOBJ,
param1: ?*PATHOBJ,
param2: ?*CLIPOBJ,
param3: ?*XFORMOBJ,
param4: ?*BRUSHOBJ,
param5: ?*LINEATTRS,
param6: ?*BRUSHOBJ,
param7: ?*POINTL,
param8: u32,
param9: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvPaint = fn(
param0: ?*SURFOBJ,
param1: ?*CLIPOBJ,
param2: ?*BRUSHOBJ,
param3: ?*POINTL,
param4: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvGetGlyphMode = fn(
dhpdev: DHPDEV,
pfo: ?*FONTOBJ,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const PFN_DrvResetPDEV = fn(
dhpdevOld: DHPDEV,
dhpdevNew: DHPDEV,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvSaveScreenBits = fn(
param0: ?*SURFOBJ,
param1: u32,
param2: usize,
param3: ?*RECTL,
) callconv(@import("std").os.windows.WINAPI) usize;
pub const PFN_DrvGetModes = fn(
param0: ?HANDLE,
param1: u32,
param2: ?*DEVMODEW,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const PFN_DrvQueryTrueTypeTable = fn(
param0: usize,
param1: u32,
param2: u32,
param3: i32,
param4: u32,
param5: ?*u8,
param6: ?*?*u8,
param7: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const PFN_DrvQueryTrueTypeSection = fn(
param0: u32,
param1: u32,
param2: u32,
param3: ?*?HANDLE,
param4: ?*i32,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const PFN_DrvQueryTrueTypeOutline = fn(
param0: DHPDEV,
param1: ?*FONTOBJ,
param2: u32,
param3: BOOL,
param4: ?*GLYPHDATA,
param5: u32,
param6: ?*TTPOLYGONHEADER,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const PFN_DrvGetTrueTypeFile = fn(
param0: usize,
param1: ?*u32,
) callconv(@import("std").os.windows.WINAPI) ?*c_void;
pub const PFN_DrvQueryFontFile = fn(
param0: usize,
param1: u32,
param2: u32,
param3: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const PFN_DrvQueryAdvanceWidths = fn(
param0: DHPDEV,
param1: ?*FONTOBJ,
param2: u32,
param3: ?*u32,
param4: ?*c_void,
param5: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvFontManagement = fn(
param0: ?*SURFOBJ,
param1: ?*FONTOBJ,
param2: u32,
param3: u32,
param4: ?*c_void,
param5: u32,
param6: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const PFN_DrvSetPixelFormat = fn(
param0: ?*SURFOBJ,
param1: i32,
param2: ?HWND,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvDescribePixelFormat = fn(
param0: DHPDEV,
param1: i32,
param2: u32,
param3: ?*PIXELFORMATDESCRIPTOR,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const PFN_DrvSwapBuffers = fn(
param0: ?*SURFOBJ,
param1: ?*WNDOBJ,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvStartBanding = fn(
param0: ?*SURFOBJ,
ppointl: ?*POINTL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvNextBand = fn(
param0: ?*SURFOBJ,
ppointl: ?*POINTL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvQueryPerBandInfo = fn(
param0: ?*SURFOBJ,
param1: ?*PERBANDINFO,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvEnableDirectDraw = fn(
param0: DHPDEV,
param1: ?*DD_CALLBACKS,
param2: ?*DD_SURFACECALLBACKS,
param3: ?*DD_PALETTECALLBACKS,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvDisableDirectDraw = fn(
param0: DHPDEV,
) callconv(@import("std").os.windows.WINAPI) void;
pub const PFN_DrvGetDirectDrawInfo = fn(
param0: DHPDEV,
param1: ?*DD_HALINFO,
param2: ?*u32,
param3: ?*VIDEOMEMORY,
param4: ?*u32,
param5: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvIcmCreateColorTransform = fn(
param0: DHPDEV,
param1: ?*LOGCOLORSPACEW,
param2: ?*c_void,
param3: u32,
param4: ?*c_void,
param5: u32,
param6: ?*c_void,
param7: u32,
param8: u32,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
pub const PFN_DrvIcmDeleteColorTransform = fn(
param0: DHPDEV,
param1: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvIcmCheckBitmapBits = fn(
param0: DHPDEV,
param1: ?HANDLE,
param2: ?*SURFOBJ,
param3: ?*u8,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvIcmSetDeviceGammaRamp = fn(
param0: DHPDEV,
param1: u32,
param2: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvAlphaBlend = fn(
param0: ?*SURFOBJ,
param1: ?*SURFOBJ,
param2: ?*CLIPOBJ,
param3: ?*XLATEOBJ,
param4: ?*RECTL,
param5: ?*RECTL,
param6: ?*BLENDOBJ,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvGradientFill = fn(
param0: ?*SURFOBJ,
param1: ?*CLIPOBJ,
param2: ?*XLATEOBJ,
param3: ?*TRIVERTEX,
param4: u32,
param5: ?*c_void,
param6: u32,
param7: ?*RECTL,
param8: ?*POINTL,
param9: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvQueryDeviceSupport = fn(
param0: ?*SURFOBJ,
param1: ?*XLATEOBJ,
param2: ?*XFORMOBJ,
param3: u32,
param4: u32,
param5: ?*c_void,
param6: u32,
param7: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvDeriveSurface = fn(
param0: ?*DD_DIRECTDRAW_GLOBAL,
param1: ?*DD_SURFACE_LOCAL,
) callconv(@import("std").os.windows.WINAPI) ?HBITMAP;
pub const PFN_DrvSynchronizeSurface = fn(
param0: ?*SURFOBJ,
param1: ?*RECTL,
param2: u32,
) callconv(@import("std").os.windows.WINAPI) void;
pub const PFN_DrvNotify = fn(
param0: ?*SURFOBJ,
param1: u32,
param2: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
pub const PFN_DrvRenderHint = fn(
dhpdev: DHPDEV,
NotifyCode: u32,
Length: usize,
// TODO: what to do with BytesParamIndex 2?
Data: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const DRH_APIBITMAPDATA = extern struct {
pso: ?*SURFOBJ,
b: BOOL,
};
pub const PFN_EngCreateRectRgn = fn(
left: i32,
top: i32,
right: i32,
bottom: i32,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
pub const PFN_EngDeleteRgn = fn(
hrgn: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) void;
pub const PFN_EngCombineRgn = fn(
hrgnTrg: ?HANDLE,
hrgnSrc1: ?HANDLE,
hrgnSrc2: ?HANDLE,
imode: i32,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const PFN_EngCopyRgn = fn(
hrgnDst: ?HANDLE,
hrgnSrc: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const PFN_EngIntersectRgn = fn(
hrgnResult: ?HANDLE,
hRgnA: ?HANDLE,
hRgnB: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const PFN_EngSubtractRgn = fn(
hrgnResult: ?HANDLE,
hRgnA: ?HANDLE,
hRgnB: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const PFN_EngUnionRgn = fn(
hrgnResult: ?HANDLE,
hRgnA: ?HANDLE,
hRgnB: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const PFN_EngXorRgn = fn(
hrgnResult: ?HANDLE,
hRgnA: ?HANDLE,
hRgnB: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const PFN_DrvCreateDeviceBitmapEx = fn(
param0: DHPDEV,
param1: SIZE,
param2: u32,
param3: u32,
param4: DHSURF,
param5: u32,
param6: u32,
param7: ?*?HANDLE,
) callconv(@import("std").os.windows.WINAPI) ?HBITMAP;
pub const PFN_DrvDeleteDeviceBitmapEx = fn(
param0: DHSURF,
) callconv(@import("std").os.windows.WINAPI) void;
pub const PFN_DrvAssociateSharedSurface = fn(
param0: ?*SURFOBJ,
param1: ?HANDLE,
param2: ?HANDLE,
param3: SIZE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvSynchronizeRedirectionBitmaps = fn(
param0: DHPDEV,
param1: ?*u64,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub const PFN_DrvAccumulateD3DDirtyRect = fn(
param0: ?*SURFOBJ,
param1: ?*CDDDXGK_REDIRBITMAPPRESENTINFO,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvStartDxInterop = fn(
param0: ?*SURFOBJ,
param1: BOOL,
KernelModeDeviceHandle: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvEndDxInterop = fn(
param0: ?*SURFOBJ,
param1: BOOL,
param2: ?*BOOL,
KernelModeDeviceHandle: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PFN_DrvLockDisplayArea = fn(
param0: DHPDEV,
param1: ?*RECTL,
) callconv(@import("std").os.windows.WINAPI) void;
pub const PFN_DrvUnlockDisplayArea = fn(
param0: DHPDEV,
param1: ?*RECTL,
) callconv(@import("std").os.windows.WINAPI) void;
pub const PFN_DrvSurfaceComplete = fn(
param0: DHPDEV,
param1: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const STORAGE_HOTPLUG_INFO = extern struct {
Size: u32,
MediaRemovable: BOOLEAN,
MediaHotplug: BOOLEAN,
DeviceHotplug: BOOLEAN,
WriteCacheEnableOverride: BOOLEAN,
};
pub const STORAGE_DEVICE_NUMBER = extern struct {
DeviceType: u32,
DeviceNumber: u32,
PartitionNumber: u32,
};
pub const STORAGE_DEVICE_NUMBERS = extern struct {
Version: u32,
Size: u32,
NumberOfDevices: u32,
Devices: [1]STORAGE_DEVICE_NUMBER,
};
pub const STORAGE_DEVICE_NUMBER_EX = extern struct {
Version: u32,
Size: u32,
Flags: u32,
DeviceType: u32,
DeviceNumber: u32,
DeviceGuid: Guid,
PartitionNumber: u32,
};
pub const STORAGE_BUS_RESET_REQUEST = extern struct {
PathId: u8,
};
pub const STORAGE_BREAK_RESERVATION_REQUEST = extern struct {
Length: u32,
_unused: u8,
PathId: u8,
TargetId: u8,
Lun: u8,
};
pub const PREVENT_MEDIA_REMOVAL = extern struct {
PreventMediaRemoval: BOOLEAN,
};
pub const CLASS_MEDIA_CHANGE_CONTEXT = extern struct {
MediaChangeCount: u32,
NewState: u32,
};
pub const TAPE_STATISTICS = extern struct {
Version: u32,
Flags: u32,
RecoveredWrites: LARGE_INTEGER,
UnrecoveredWrites: LARGE_INTEGER,
RecoveredReads: LARGE_INTEGER,
UnrecoveredReads: LARGE_INTEGER,
CompressionRatioReads: u8,
CompressionRatioWrites: u8,
};
pub const TAPE_GET_STATISTICS = extern struct {
Operation: u32,
};
pub const STORAGE_MEDIA_TYPE = enum(i32) {
DDS_4mm = 32,
MiniQic = 33,
Travan = 34,
QIC = 35,
MP_8mm = 36,
AME_8mm = 37,
AIT1_8mm = 38,
DLT = 39,
NCTP = 40,
IBM_3480 = 41,
IBM_3490E = 42,
IBM_Magstar_3590 = 43,
IBM_Magstar_MP = 44,
STK_DATA_D3 = 45,
SONY_DTF = 46,
DV_6mm = 47,
DMI = 48,
SONY_D2 = 49,
CLEANER_CARTRIDGE = 50,
CD_ROM = 51,
CD_R = 52,
CD_RW = 53,
DVD_ROM = 54,
DVD_R = 55,
DVD_RW = 56,
MO_3_RW = 57,
MO_5_WO = 58,
MO_5_RW = 59,
MO_5_LIMDOW = 60,
PC_5_WO = 61,
PC_5_RW = 62,
PD_5_RW = 63,
ABL_5_WO = 64,
PINNACLE_APEX_5_RW = 65,
SONY_12_WO = 66,
PHILIPS_12_WO = 67,
HITACHI_12_WO = 68,
CYGNET_12_WO = 69,
KODAK_14_WO = 70,
MO_NFR_525 = 71,
NIKON_12_RW = 72,
IOMEGA_ZIP = 73,
IOMEGA_JAZ = 74,
SYQUEST_EZ135 = 75,
SYQUEST_EZFLYER = 76,
SYQUEST_SYJET = 77,
AVATAR_F2 = 78,
MP2_8mm = 79,
DST_S = 80,
DST_M = 81,
DST_L = 82,
VXATape_1 = 83,
VXATape_2 = 84,
STK_9840 = 85,
LTO_Ultrium = 86,
LTO_Accelis = 87,
DVD_RAM = 88,
AIT_8mm = 89,
ADR_1 = 90,
ADR_2 = 91,
STK_9940 = 92,
SAIT = 93,
VXATape = 94,
};
pub const DDS_4mm = STORAGE_MEDIA_TYPE.DDS_4mm;
pub const MiniQic = STORAGE_MEDIA_TYPE.MiniQic;
pub const Travan = STORAGE_MEDIA_TYPE.Travan;
pub const QIC = STORAGE_MEDIA_TYPE.QIC;
pub const MP_8mm = STORAGE_MEDIA_TYPE.MP_8mm;
pub const AME_8mm = STORAGE_MEDIA_TYPE.AME_8mm;
pub const AIT1_8mm = STORAGE_MEDIA_TYPE.AIT1_8mm;
pub const DLT = STORAGE_MEDIA_TYPE.DLT;
pub const NCTP = STORAGE_MEDIA_TYPE.NCTP;
pub const IBM_3480 = STORAGE_MEDIA_TYPE.IBM_3480;
pub const IBM_3490E = STORAGE_MEDIA_TYPE.IBM_3490E;
pub const IBM_Magstar_3590 = STORAGE_MEDIA_TYPE.IBM_Magstar_3590;
pub const IBM_Magstar_MP = STORAGE_MEDIA_TYPE.IBM_Magstar_MP;
pub const STK_DATA_D3 = STORAGE_MEDIA_TYPE.STK_DATA_D3;
pub const SONY_DTF = STORAGE_MEDIA_TYPE.SONY_DTF;
pub const DV_6mm = STORAGE_MEDIA_TYPE.DV_6mm;
pub const DMI = STORAGE_MEDIA_TYPE.DMI;
pub const SONY_D2 = STORAGE_MEDIA_TYPE.SONY_D2;
pub const CLEANER_CARTRIDGE = STORAGE_MEDIA_TYPE.CLEANER_CARTRIDGE;
pub const CD_ROM = STORAGE_MEDIA_TYPE.CD_ROM;
pub const CD_R = STORAGE_MEDIA_TYPE.CD_R;
pub const CD_RW = STORAGE_MEDIA_TYPE.CD_RW;
pub const DVD_ROM = STORAGE_MEDIA_TYPE.DVD_ROM;
pub const DVD_R = STORAGE_MEDIA_TYPE.DVD_R;
pub const DVD_RW = STORAGE_MEDIA_TYPE.DVD_RW;
pub const MO_3_RW = STORAGE_MEDIA_TYPE.MO_3_RW;
pub const MO_5_WO = STORAGE_MEDIA_TYPE.MO_5_WO;
pub const MO_5_RW = STORAGE_MEDIA_TYPE.MO_5_RW;
pub const MO_5_LIMDOW = STORAGE_MEDIA_TYPE.MO_5_LIMDOW;
pub const PC_5_WO = STORAGE_MEDIA_TYPE.PC_5_WO;
pub const PC_5_RW = STORAGE_MEDIA_TYPE.PC_5_RW;
pub const PD_5_RW = STORAGE_MEDIA_TYPE.PD_5_RW;
pub const ABL_5_WO = STORAGE_MEDIA_TYPE.ABL_5_WO;
pub const PINNACLE_APEX_5_RW = STORAGE_MEDIA_TYPE.PINNACLE_APEX_5_RW;
pub const SONY_12_WO = STORAGE_MEDIA_TYPE.SONY_12_WO;
pub const PHILIPS_12_WO = STORAGE_MEDIA_TYPE.PHILIPS_12_WO;
pub const HITACHI_12_WO = STORAGE_MEDIA_TYPE.HITACHI_12_WO;
pub const CYGNET_12_WO = STORAGE_MEDIA_TYPE.CYGNET_12_WO;
pub const KODAK_14_WO = STORAGE_MEDIA_TYPE.KODAK_14_WO;
pub const MO_NFR_525 = STORAGE_MEDIA_TYPE.MO_NFR_525;
pub const NIKON_12_RW = STORAGE_MEDIA_TYPE.NIKON_12_RW;
pub const IOMEGA_ZIP = STORAGE_MEDIA_TYPE.IOMEGA_ZIP;
pub const IOMEGA_JAZ = STORAGE_MEDIA_TYPE.IOMEGA_JAZ;
pub const SYQUEST_EZ135 = STORAGE_MEDIA_TYPE.SYQUEST_EZ135;
pub const SYQUEST_EZFLYER = STORAGE_MEDIA_TYPE.SYQUEST_EZFLYER;
pub const SYQUEST_SYJET = STORAGE_MEDIA_TYPE.SYQUEST_SYJET;
pub const AVATAR_F2 = STORAGE_MEDIA_TYPE.AVATAR_F2;
pub const MP2_8mm = STORAGE_MEDIA_TYPE.MP2_8mm;
pub const DST_S = STORAGE_MEDIA_TYPE.DST_S;
pub const DST_M = STORAGE_MEDIA_TYPE.DST_M;
pub const DST_L = STORAGE_MEDIA_TYPE.DST_L;
pub const VXATape_1 = STORAGE_MEDIA_TYPE.VXATape_1;
pub const VXATape_2 = STORAGE_MEDIA_TYPE.VXATape_2;
pub const STK_9840 = STORAGE_MEDIA_TYPE.STK_9840;
pub const LTO_Ultrium = STORAGE_MEDIA_TYPE.LTO_Ultrium;
pub const LTO_Accelis = STORAGE_MEDIA_TYPE.LTO_Accelis;
pub const DVD_RAM = STORAGE_MEDIA_TYPE.DVD_RAM;
pub const AIT_8mm = STORAGE_MEDIA_TYPE.AIT_8mm;
pub const ADR_1 = STORAGE_MEDIA_TYPE.ADR_1;
pub const ADR_2 = STORAGE_MEDIA_TYPE.ADR_2;
pub const STK_9940 = STORAGE_MEDIA_TYPE.STK_9940;
pub const SAIT = STORAGE_MEDIA_TYPE.SAIT;
pub const VXATape = STORAGE_MEDIA_TYPE.VXATape;
pub const STORAGE_BUS_TYPE = enum(i32) {
Unknown = 0,
Scsi = 1,
Atapi = 2,
Ata = 3,
@"1394" = 4,
Ssa = 5,
Fibre = 6,
Usb = 7,
RAID = 8,
iScsi = 9,
Sas = 10,
Sata = 11,
Sd = 12,
Mmc = 13,
Virtual = 14,
FileBackedVirtual = 15,
Spaces = 16,
Nvme = 17,
SCM = 18,
Ufs = 19,
Max = 20,
MaxReserved = 127,
};
pub const BusTypeUnknown = STORAGE_BUS_TYPE.Unknown;
pub const BusTypeScsi = STORAGE_BUS_TYPE.Scsi;
pub const BusTypeAtapi = STORAGE_BUS_TYPE.Atapi;
pub const BusTypeAta = STORAGE_BUS_TYPE.Ata;
pub const BusType1394 = STORAGE_BUS_TYPE.@"1394";
pub const BusTypeSsa = STORAGE_BUS_TYPE.Ssa;
pub const BusTypeFibre = STORAGE_BUS_TYPE.Fibre;
pub const BusTypeUsb = STORAGE_BUS_TYPE.Usb;
pub const BusTypeRAID = STORAGE_BUS_TYPE.RAID;
pub const BusTypeiScsi = STORAGE_BUS_TYPE.iScsi;
pub const BusTypeSas = STORAGE_BUS_TYPE.Sas;
pub const BusTypeSata = STORAGE_BUS_TYPE.Sata;
pub const BusTypeSd = STORAGE_BUS_TYPE.Sd;
pub const BusTypeMmc = STORAGE_BUS_TYPE.Mmc;
pub const BusTypeVirtual = STORAGE_BUS_TYPE.Virtual;
pub const BusTypeFileBackedVirtual = STORAGE_BUS_TYPE.FileBackedVirtual;
pub const BusTypeSpaces = STORAGE_BUS_TYPE.Spaces;
pub const BusTypeNvme = STORAGE_BUS_TYPE.Nvme;
pub const BusTypeSCM = STORAGE_BUS_TYPE.SCM;
pub const BusTypeUfs = STORAGE_BUS_TYPE.Ufs;
pub const BusTypeMax = STORAGE_BUS_TYPE.Max;
pub const BusTypeMaxReserved = STORAGE_BUS_TYPE.MaxReserved;
pub const DEVICE_MEDIA_INFO = extern struct {
DeviceSpecific: extern union {
DiskInfo: extern struct {
Cylinders: LARGE_INTEGER,
MediaType: STORAGE_MEDIA_TYPE,
TracksPerCylinder: u32,
SectorsPerTrack: u32,
BytesPerSector: u32,
NumberMediaSides: u32,
MediaCharacteristics: u32,
},
RemovableDiskInfo: extern struct {
Cylinders: LARGE_INTEGER,
MediaType: STORAGE_MEDIA_TYPE,
TracksPerCylinder: u32,
SectorsPerTrack: u32,
BytesPerSector: u32,
NumberMediaSides: u32,
MediaCharacteristics: u32,
},
TapeInfo: extern struct {
MediaType: STORAGE_MEDIA_TYPE,
MediaCharacteristics: u32,
CurrentBlockSize: u32,
BusType: STORAGE_BUS_TYPE,
BusSpecificData: extern union {
ScsiInformation: extern struct {
MediumType: u8,
DensityCode: u8,
},
},
},
},
};
pub const GET_MEDIA_TYPES = extern struct {
DeviceType: u32,
MediaInfoCount: u32,
MediaInfo: [1]DEVICE_MEDIA_INFO,
};
pub const STORAGE_PREDICT_FAILURE = extern struct {
PredictFailure: u32,
VendorSpecific: [512]u8,
};
pub const STORAGE_FAILURE_PREDICTION_CONFIG = extern struct {
Version: u32,
Size: u32,
Set: BOOLEAN,
Enabled: BOOLEAN,
Reserved: u16,
};
pub const STORAGE_SET_TYPE = enum(i32) {
StandardSet = 0,
ExistsSet = 1,
SetMaxDefined = 2,
};
pub const PropertyStandardSet = STORAGE_SET_TYPE.StandardSet;
pub const PropertyExistsSet = STORAGE_SET_TYPE.ExistsSet;
pub const PropertySetMaxDefined = STORAGE_SET_TYPE.SetMaxDefined;
pub const STORAGE_PROPERTY_SET = extern struct {
PropertyId: STORAGE_PROPERTY_ID,
SetType: STORAGE_SET_TYPE,
AdditionalParameters: [1]u8,
};
pub const STORAGE_IDENTIFIER_CODE_SET = enum(i32) {
Reserved = 0,
Binary = 1,
Ascii = 2,
Utf8 = 3,
};
pub const StorageIdCodeSetReserved = STORAGE_IDENTIFIER_CODE_SET.Reserved;
pub const StorageIdCodeSetBinary = STORAGE_IDENTIFIER_CODE_SET.Binary;
pub const StorageIdCodeSetAscii = STORAGE_IDENTIFIER_CODE_SET.Ascii;
pub const StorageIdCodeSetUtf8 = STORAGE_IDENTIFIER_CODE_SET.Utf8;
pub const STORAGE_IDENTIFIER_TYPE = enum(i32) {
VendorSpecific = 0,
VendorId = 1,
EUI64 = 2,
FCPHName = 3,
PortRelative = 4,
TargetPortGroup = 5,
LogicalUnitGroup = 6,
MD5LogicalUnitIdentifier = 7,
ScsiNameString = 8,
};
pub const StorageIdTypeVendorSpecific = STORAGE_IDENTIFIER_TYPE.VendorSpecific;
pub const StorageIdTypeVendorId = STORAGE_IDENTIFIER_TYPE.VendorId;
pub const StorageIdTypeEUI64 = STORAGE_IDENTIFIER_TYPE.EUI64;
pub const StorageIdTypeFCPHName = STORAGE_IDENTIFIER_TYPE.FCPHName;
pub const StorageIdTypePortRelative = STORAGE_IDENTIFIER_TYPE.PortRelative;
pub const StorageIdTypeTargetPortGroup = STORAGE_IDENTIFIER_TYPE.TargetPortGroup;
pub const StorageIdTypeLogicalUnitGroup = STORAGE_IDENTIFIER_TYPE.LogicalUnitGroup;
pub const StorageIdTypeMD5LogicalUnitIdentifier = STORAGE_IDENTIFIER_TYPE.MD5LogicalUnitIdentifier;
pub const StorageIdTypeScsiNameString = STORAGE_IDENTIFIER_TYPE.ScsiNameString;
pub const STORAGE_ID_NAA_FORMAT = enum(i32) {
Extended = 2,
Registered = 3,
ERegisteredExtended = 5,
};
pub const StorageIdNAAFormatIEEEExtended = STORAGE_ID_NAA_FORMAT.Extended;
pub const StorageIdNAAFormatIEEERegistered = STORAGE_ID_NAA_FORMAT.Registered;
pub const StorageIdNAAFormatIEEEERegisteredExtended = STORAGE_ID_NAA_FORMAT.ERegisteredExtended;
pub const STORAGE_ASSOCIATION_TYPE = enum(i32) {
Device = 0,
Port = 1,
Target = 2,
};
pub const StorageIdAssocDevice = STORAGE_ASSOCIATION_TYPE.Device;
pub const StorageIdAssocPort = STORAGE_ASSOCIATION_TYPE.Port;
pub const StorageIdAssocTarget = STORAGE_ASSOCIATION_TYPE.Target;
pub const STORAGE_IDENTIFIER = extern struct {
CodeSet: STORAGE_IDENTIFIER_CODE_SET,
Type: STORAGE_IDENTIFIER_TYPE,
IdentifierSize: u16,
NextOffset: u16,
Association: STORAGE_ASSOCIATION_TYPE,
Identifier: [1]u8,
};
pub const STORAGE_LB_PROVISIONING_MAP_RESOURCES = extern struct {
Size: u32,
Version: u32,
_bitfield1: u8,
Reserved1: [3]u8,
_bitfield2: u8,
Reserved3: [3]u8,
AvailableMappingResources: u64,
UsedMappingResources: u64,
};
pub const STORAGE_RPMB_FRAME_TYPE = enum(i32) {
Unknown = 0,
Standard = 1,
Max = 2,
};
pub const StorageRpmbFrameTypeUnknown = STORAGE_RPMB_FRAME_TYPE.Unknown;
pub const StorageRpmbFrameTypeStandard = STORAGE_RPMB_FRAME_TYPE.Standard;
pub const StorageRpmbFrameTypeMax = STORAGE_RPMB_FRAME_TYPE.Max;
pub const STORAGE_RPMB_DESCRIPTOR = extern struct {
Version: u32,
Size: u32,
SizeInBytes: u32,
MaxReliableWriteSizeInBytes: u32,
FrameFormat: STORAGE_RPMB_FRAME_TYPE,
};
pub const STORAGE_CRYPTO_ALGORITHM_ID = enum(i32) {
Unknown = 0,
XTSAES = 1,
BitlockerAESCBC = 2,
AESECB = 3,
ESSIVAESCBC = 4,
Max = 5,
};
pub const StorageCryptoAlgorithmUnknown = STORAGE_CRYPTO_ALGORITHM_ID.Unknown;
pub const StorageCryptoAlgorithmXTSAES = STORAGE_CRYPTO_ALGORITHM_ID.XTSAES;
pub const StorageCryptoAlgorithmBitlockerAESCBC = STORAGE_CRYPTO_ALGORITHM_ID.BitlockerAESCBC;
pub const StorageCryptoAlgorithmAESECB = STORAGE_CRYPTO_ALGORITHM_ID.AESECB;
pub const StorageCryptoAlgorithmESSIVAESCBC = STORAGE_CRYPTO_ALGORITHM_ID.ESSIVAESCBC;
pub const StorageCryptoAlgorithmMax = STORAGE_CRYPTO_ALGORITHM_ID.Max;
pub const STORAGE_CRYPTO_KEY_SIZE = enum(i32) {
Unknown = 0,
@"128Bits" = 1,
@"192Bits" = 2,
@"256Bits" = 3,
@"512Bits" = 4,
};
pub const StorageCryptoKeySizeUnknown = STORAGE_CRYPTO_KEY_SIZE.Unknown;
pub const StorageCryptoKeySize128Bits = STORAGE_CRYPTO_KEY_SIZE.@"128Bits";
pub const StorageCryptoKeySize192Bits = STORAGE_CRYPTO_KEY_SIZE.@"192Bits";
pub const StorageCryptoKeySize256Bits = STORAGE_CRYPTO_KEY_SIZE.@"256Bits";
pub const StorageCryptoKeySize512Bits = STORAGE_CRYPTO_KEY_SIZE.@"512Bits";
pub const STORAGE_CRYPTO_CAPABILITY = extern struct {
Version: u32,
Size: u32,
CryptoCapabilityIndex: u32,
AlgorithmId: STORAGE_CRYPTO_ALGORITHM_ID,
KeySize: STORAGE_CRYPTO_KEY_SIZE,
DataUnitSizeBitmask: u32,
};
pub const STORAGE_CRYPTO_DESCRIPTOR = extern struct {
Version: u32,
Size: u32,
NumKeysSupported: u32,
NumCryptoCapabilities: u32,
CryptoCapabilities: [1]STORAGE_CRYPTO_CAPABILITY,
};
pub const STORAGE_TIER_MEDIA_TYPE = enum(i32) {
Unspecified = 0,
Disk = 1,
Ssd = 2,
Scm = 4,
Max = 5,
};
pub const StorageTierMediaTypeUnspecified = STORAGE_TIER_MEDIA_TYPE.Unspecified;
pub const StorageTierMediaTypeDisk = STORAGE_TIER_MEDIA_TYPE.Disk;
pub const StorageTierMediaTypeSsd = STORAGE_TIER_MEDIA_TYPE.Ssd;
pub const StorageTierMediaTypeScm = STORAGE_TIER_MEDIA_TYPE.Scm;
pub const StorageTierMediaTypeMax = STORAGE_TIER_MEDIA_TYPE.Max;
pub const STORAGE_TIER_CLASS = enum(i32) {
Unspecified = 0,
Capacity = 1,
Performance = 2,
Max = 3,
};
pub const StorageTierClassUnspecified = STORAGE_TIER_CLASS.Unspecified;
pub const StorageTierClassCapacity = STORAGE_TIER_CLASS.Capacity;
pub const StorageTierClassPerformance = STORAGE_TIER_CLASS.Performance;
pub const StorageTierClassMax = STORAGE_TIER_CLASS.Max;
pub const STORAGE_TIER = extern struct {
Id: Guid,
Name: [256]u16,
Description: [256]u16,
Flags: u64,
ProvisionedCapacity: u64,
MediaType: STORAGE_TIER_MEDIA_TYPE,
Class: STORAGE_TIER_CLASS,
};
pub const STORAGE_DEVICE_TIERING_DESCRIPTOR = extern struct {
Version: u32,
Size: u32,
Flags: u32,
TotalNumberOfTiers: u32,
NumberOfTiersReturned: u32,
Tiers: [1]STORAGE_TIER,
};
pub const STORAGE_DEVICE_FAULT_DOMAIN_DESCRIPTOR = extern struct {
Version: u32,
Size: u32,
NumberOfFaultDomains: u32,
FaultDomainIds: [1]Guid,
};
pub const STORAGE_PROTOCOL_UFS_DATA_TYPE = enum(i32) {
Unknown = 0,
QueryDescriptor = 1,
Max = 2,
};
pub const UfsDataTypeUnknown = STORAGE_PROTOCOL_UFS_DATA_TYPE.Unknown;
pub const UfsDataTypeQueryDescriptor = STORAGE_PROTOCOL_UFS_DATA_TYPE.QueryDescriptor;
pub const UfsDataTypeMax = STORAGE_PROTOCOL_UFS_DATA_TYPE.Max;
pub const STORAGE_PROTOCOL_SPECIFIC_DATA_EXT = extern struct {
ProtocolType: STORAGE_PROTOCOL_TYPE,
DataType: u32,
ProtocolDataValue: u32,
ProtocolDataSubValue: u32,
ProtocolDataOffset: u32,
ProtocolDataLength: u32,
FixedProtocolReturnData: u32,
ProtocolDataSubValue2: u32,
ProtocolDataSubValue3: u32,
ProtocolDataSubValue4: u32,
ProtocolDataSubValue5: u32,
Reserved: [5]u32,
};
pub const STORAGE_PROTOCOL_DATA_DESCRIPTOR_EXT = extern struct {
Version: u32,
Size: u32,
ProtocolSpecificData: STORAGE_PROTOCOL_SPECIFIC_DATA_EXT,
};
pub const STORAGE_DISK_HEALTH_STATUS = enum(i32) {
Unknown = 0,
Unhealthy = 1,
Warning = 2,
Healthy = 3,
Max = 4,
};
pub const DiskHealthUnknown = STORAGE_DISK_HEALTH_STATUS.Unknown;
pub const DiskHealthUnhealthy = STORAGE_DISK_HEALTH_STATUS.Unhealthy;
pub const DiskHealthWarning = STORAGE_DISK_HEALTH_STATUS.Warning;
pub const DiskHealthHealthy = STORAGE_DISK_HEALTH_STATUS.Healthy;
pub const DiskHealthMax = STORAGE_DISK_HEALTH_STATUS.Max;
pub const STORAGE_DISK_OPERATIONAL_STATUS = enum(i32) {
None = 0,
Unknown = 1,
Ok = 2,
PredictingFailure = 3,
InService = 4,
HardwareError = 5,
NotUsable = 6,
TransientError = 7,
Missing = 8,
};
pub const DiskOpStatusNone = STORAGE_DISK_OPERATIONAL_STATUS.None;
pub const DiskOpStatusUnknown = STORAGE_DISK_OPERATIONAL_STATUS.Unknown;
pub const DiskOpStatusOk = STORAGE_DISK_OPERATIONAL_STATUS.Ok;
pub const DiskOpStatusPredictingFailure = STORAGE_DISK_OPERATIONAL_STATUS.PredictingFailure;
pub const DiskOpStatusInService = STORAGE_DISK_OPERATIONAL_STATUS.InService;
pub const DiskOpStatusHardwareError = STORAGE_DISK_OPERATIONAL_STATUS.HardwareError;
pub const DiskOpStatusNotUsable = STORAGE_DISK_OPERATIONAL_STATUS.NotUsable;
pub const DiskOpStatusTransientError = STORAGE_DISK_OPERATIONAL_STATUS.TransientError;
pub const DiskOpStatusMissing = STORAGE_DISK_OPERATIONAL_STATUS.Missing;
pub const STORAGE_OPERATIONAL_STATUS_REASON = enum(i32) {
Unknown = 0,
ScsiSenseCode = 1,
Media = 2,
Io = 3,
ThresholdExceeded = 4,
LostData = 5,
EnergySource = 6,
Configuration = 7,
DeviceController = 8,
MediaController = 9,
Component = 10,
NVDIMM_N = 11,
BackgroundOperation = 12,
InvalidFirmware = 13,
HealthCheck = 14,
LostDataPersistence = 15,
DisabledByPlatform = 16,
LostWritePersistence = 17,
DataPersistenceLossImminent = 18,
WritePersistenceLossImminent = 19,
Max = 20,
};
pub const DiskOpReasonUnknown = STORAGE_OPERATIONAL_STATUS_REASON.Unknown;
pub const DiskOpReasonScsiSenseCode = STORAGE_OPERATIONAL_STATUS_REASON.ScsiSenseCode;
pub const DiskOpReasonMedia = STORAGE_OPERATIONAL_STATUS_REASON.Media;
pub const DiskOpReasonIo = STORAGE_OPERATIONAL_STATUS_REASON.Io;
pub const DiskOpReasonThresholdExceeded = STORAGE_OPERATIONAL_STATUS_REASON.ThresholdExceeded;
pub const DiskOpReasonLostData = STORAGE_OPERATIONAL_STATUS_REASON.LostData;
pub const DiskOpReasonEnergySource = STORAGE_OPERATIONAL_STATUS_REASON.EnergySource;
pub const DiskOpReasonConfiguration = STORAGE_OPERATIONAL_STATUS_REASON.Configuration;
pub const DiskOpReasonDeviceController = STORAGE_OPERATIONAL_STATUS_REASON.DeviceController;
pub const DiskOpReasonMediaController = STORAGE_OPERATIONAL_STATUS_REASON.MediaController;
pub const DiskOpReasonComponent = STORAGE_OPERATIONAL_STATUS_REASON.Component;
pub const DiskOpReasonNVDIMM_N = STORAGE_OPERATIONAL_STATUS_REASON.NVDIMM_N;
pub const DiskOpReasonBackgroundOperation = STORAGE_OPERATIONAL_STATUS_REASON.BackgroundOperation;
pub const DiskOpReasonInvalidFirmware = STORAGE_OPERATIONAL_STATUS_REASON.InvalidFirmware;
pub const DiskOpReasonHealthCheck = STORAGE_OPERATIONAL_STATUS_REASON.HealthCheck;
pub const DiskOpReasonLostDataPersistence = STORAGE_OPERATIONAL_STATUS_REASON.LostDataPersistence;
pub const DiskOpReasonDisabledByPlatform = STORAGE_OPERATIONAL_STATUS_REASON.DisabledByPlatform;
pub const DiskOpReasonLostWritePersistence = STORAGE_OPERATIONAL_STATUS_REASON.LostWritePersistence;
pub const DiskOpReasonDataPersistenceLossImminent = STORAGE_OPERATIONAL_STATUS_REASON.DataPersistenceLossImminent;
pub const DiskOpReasonWritePersistenceLossImminent = STORAGE_OPERATIONAL_STATUS_REASON.WritePersistenceLossImminent;
pub const DiskOpReasonMax = STORAGE_OPERATIONAL_STATUS_REASON.Max;
pub const STORAGE_OPERATIONAL_REASON = extern struct {
Version: u32,
Size: u32,
Reason: STORAGE_OPERATIONAL_STATUS_REASON,
RawBytes: extern union {
ScsiSenseKey: extern struct {
SenseKey: u8,
ASC: u8,
ASCQ: u8,
Reserved: u8,
},
NVDIMM_N: extern struct {
CriticalHealth: u8,
ModuleHealth: [2]u8,
ErrorThresholdStatus: u8,
},
AsUlong: u32,
},
};
pub const STORAGE_DEVICE_MANAGEMENT_STATUS = extern struct {
Version: u32,
Size: u32,
Health: STORAGE_DISK_HEALTH_STATUS,
NumberOfOperationalStatus: u32,
NumberOfAdditionalReasons: u32,
OperationalStatus: [16]STORAGE_DISK_OPERATIONAL_STATUS,
AdditionalReasons: [1]STORAGE_OPERATIONAL_REASON,
};
pub const STORAGE_ZONED_DEVICE_TYPES = enum(i32) {
Unknown = 0,
HostManaged = 1,
HostAware = 2,
DeviceManaged = 3,
};
pub const ZonedDeviceTypeUnknown = STORAGE_ZONED_DEVICE_TYPES.Unknown;
pub const ZonedDeviceTypeHostManaged = STORAGE_ZONED_DEVICE_TYPES.HostManaged;
pub const ZonedDeviceTypeHostAware = STORAGE_ZONED_DEVICE_TYPES.HostAware;
pub const ZonedDeviceTypeDeviceManaged = STORAGE_ZONED_DEVICE_TYPES.DeviceManaged;
pub const STORAGE_ZONE_TYPES = enum(i32) {
Unknown = 0,
Conventional = 1,
SequentialWriteRequired = 2,
SequentialWritePreferred = 3,
Max = 4,
};
pub const ZoneTypeUnknown = STORAGE_ZONE_TYPES.Unknown;
pub const ZoneTypeConventional = STORAGE_ZONE_TYPES.Conventional;
pub const ZoneTypeSequentialWriteRequired = STORAGE_ZONE_TYPES.SequentialWriteRequired;
pub const ZoneTypeSequentialWritePreferred = STORAGE_ZONE_TYPES.SequentialWritePreferred;
pub const ZoneTypeMax = STORAGE_ZONE_TYPES.Max;
pub const STORAGE_ZONE_GROUP = extern struct {
ZoneCount: u32,
ZoneType: STORAGE_ZONE_TYPES,
ZoneSize: u64,
};
pub const STORAGE_ZONED_DEVICE_DESCRIPTOR = extern struct {
Version: u32,
Size: u32,
DeviceType: STORAGE_ZONED_DEVICE_TYPES,
ZoneCount: u32,
ZoneAttributes: extern union {
SequentialRequiredZone: extern struct {
MaxOpenZoneCount: u32,
UnrestrictedRead: BOOLEAN,
Reserved: [3]u8,
},
SequentialPreferredZone: extern struct {
OptimalOpenZoneCount: u32,
Reserved: u32,
},
},
ZoneGroupCount: u32,
ZoneGroup: [1]STORAGE_ZONE_GROUP,
};
pub const DEVICE_LOCATION = extern struct {
Socket: u32,
Slot: u32,
Adapter: u32,
Port: u32,
Anonymous: extern union {
Anonymous1: extern struct {
Channel: u32,
Device: u32,
},
Anonymous2: extern struct {
Target: u32,
Lun: u32,
},
},
};
pub const STORAGE_DEVICE_LOCATION_DESCRIPTOR = extern struct {
Version: u32,
Size: u32,
Location: DEVICE_LOCATION,
StringOffset: u32,
};
pub const STORAGE_DEVICE_NUMA_PROPERTY = extern struct {
Version: u32,
Size: u32,
NumaNode: u32,
};
pub const STORAGE_DEVICE_UNSAFE_SHUTDOWN_COUNT = extern struct {
Version: u32,
Size: u32,
UnsafeShutdownCount: u32,
};
pub const STORAGE_HW_ENDURANCE_INFO = extern struct {
ValidFields: u32,
GroupId: u32,
Flags: extern struct {
_bitfield: u32,
},
LifePercentage: u32,
BytesReadCount: [16]u8,
ByteWriteCount: [16]u8,
};
pub const STORAGE_HW_ENDURANCE_DATA_DESCRIPTOR = extern struct {
Version: u32,
Size: u32,
EnduranceInfo: STORAGE_HW_ENDURANCE_INFO,
};
pub const DEVICE_DATA_SET_RANGE = extern struct {
StartingOffset: i64,
LengthInBytes: u64,
};
pub const DEVICE_MANAGE_DATA_SET_ATTRIBUTES = extern struct {
Size: u32,
Action: u32,
Flags: u32,
ParameterBlockOffset: u32,
ParameterBlockLength: u32,
DataSetRangesOffset: u32,
DataSetRangesLength: u32,
};
pub const DEVICE_MANAGE_DATA_SET_ATTRIBUTES_OUTPUT = extern struct {
Size: u32,
Action: u32,
Flags: u32,
OperationStatus: u32,
ExtendedError: u32,
TargetDetailedError: u32,
ReservedStatus: u32,
OutputBlockOffset: u32,
OutputBlockLength: u32,
};
pub const DEVICE_DSM_DEFINITION = extern struct {
Action: u32,
SingleRange: BOOLEAN,
ParameterBlockAlignment: u32,
ParameterBlockLength: u32,
HasOutput: BOOLEAN,
OutputBlockAlignment: u32,
OutputBlockLength: u32,
};
pub const DEVICE_DSM_NOTIFICATION_PARAMETERS = extern struct {
Size: u32,
Flags: u32,
NumFileTypeIDs: u32,
FileTypeID: [1]Guid,
};
pub const STORAGE_OFFLOAD_TOKEN = extern struct {
TokenType: [4]u8,
Reserved: [2]u8,
TokenIdLength: [2]u8,
Anonymous: extern union {
StorageOffloadZeroDataToken: extern struct {
Reserved2: [504]u8,
},
Token: [504]u8,
},
};
pub const DEVICE_DSM_OFFLOAD_READ_PARAMETERS = extern struct {
Flags: u32,
TimeToLive: u32,
Reserved: [2]u32,
};
pub const STORAGE_OFFLOAD_READ_OUTPUT = extern struct {
OffloadReadFlags: u32,
Reserved: u32,
LengthProtected: u64,
TokenLength: u32,
Token: STORAGE_OFFLOAD_TOKEN,
};
pub const DEVICE_DSM_OFFLOAD_WRITE_PARAMETERS = extern struct {
Flags: u32,
Reserved: u32,
TokenOffset: u64,
Token: STORAGE_OFFLOAD_TOKEN,
};
pub const STORAGE_OFFLOAD_WRITE_OUTPUT = extern struct {
OffloadWriteFlags: u32,
Reserved: u32,
LengthCopied: u64,
};
pub const DEVICE_DATA_SET_LBP_STATE_PARAMETERS = extern struct {
Version: u32,
Size: u32,
Flags: u32,
OutputVersion: u32,
};
pub const DEVICE_DATA_SET_LB_PROVISIONING_STATE = extern struct {
Size: u32,
Version: u32,
SlabSizeInBytes: u64,
SlabOffsetDeltaInBytes: u32,
SlabAllocationBitMapBitCount: u32,
SlabAllocationBitMapLength: u32,
SlabAllocationBitMap: [1]u32,
};
pub const DEVICE_DATA_SET_LB_PROVISIONING_STATE_V2 = extern struct {
Size: u32,
Version: u32,
SlabSizeInBytes: u64,
SlabOffsetDeltaInBytes: u64,
SlabAllocationBitMapBitCount: u32,
SlabAllocationBitMapLength: u32,
SlabAllocationBitMap: [1]u32,
};
pub const DEVICE_DATA_SET_REPAIR_PARAMETERS = extern struct {
NumberOfRepairCopies: u32,
SourceCopy: u32,
RepairCopies: [1]u32,
};
pub const DEVICE_DATA_SET_REPAIR_OUTPUT = extern struct {
ParityExtent: DEVICE_DATA_SET_RANGE,
};
pub const DEVICE_DATA_SET_SCRUB_OUTPUT = extern struct {
BytesProcessed: u64,
BytesRepaired: u64,
BytesFailed: u64,
};
pub const DEVICE_DATA_SET_SCRUB_EX_OUTPUT = extern struct {
BytesProcessed: u64,
BytesRepaired: u64,
BytesFailed: u64,
ParityExtent: DEVICE_DATA_SET_RANGE,
};
pub const DEVICE_DSM_TIERING_QUERY_INPUT = extern struct {
Version: u32,
Size: u32,
Flags: u32,
NumberOfTierIds: u32,
TierIds: [1]Guid,
};
pub const STORAGE_TIER_REGION = extern struct {
TierId: Guid,
Offset: u64,
Length: u64,
};
pub const DEVICE_DSM_TIERING_QUERY_OUTPUT = extern struct {
Version: u32,
Size: u32,
Flags: u32,
Reserved: u32,
Alignment: u64,
TotalNumberOfRegions: u32,
NumberOfRegionsReturned: u32,
Regions: [1]STORAGE_TIER_REGION,
};
pub const DEVICE_DSM_NVCACHE_CHANGE_PRIORITY_PARAMETERS = extern struct {
Size: u32,
TargetPriority: u8,
Reserved: [3]u8,
};
pub const DEVICE_DATA_SET_TOPOLOGY_ID_QUERY_OUTPUT = extern struct {
TopologyRangeBytes: u64,
TopologyId: [16]u8,
};
pub const DEVICE_STORAGE_ADDRESS_RANGE = extern struct {
StartAddress: i64,
LengthInBytes: u64,
};
pub const DEVICE_DSM_PHYSICAL_ADDRESSES_OUTPUT = extern struct {
Version: u32,
Flags: u32,
TotalNumberOfRanges: u32,
NumberOfRangesReturned: u32,
Ranges: [1]DEVICE_STORAGE_ADDRESS_RANGE,
};
pub const DEVICE_DSM_REPORT_ZONES_PARAMETERS = extern struct {
Size: u32,
ReportOption: u8,
Partial: u8,
Reserved: [2]u8,
};
pub const STORAGE_ZONES_ATTRIBUTES = enum(i32) {
AndLengthMayDifferent = 0,
SameLengthSame = 1,
SameLastZoneLengthDifferent = 2,
MayDifferentLengthSame = 3,
};
pub const ZonesAttributeTypeAndLengthMayDifferent = STORAGE_ZONES_ATTRIBUTES.AndLengthMayDifferent;
pub const ZonesAttributeTypeSameLengthSame = STORAGE_ZONES_ATTRIBUTES.SameLengthSame;
pub const ZonesAttributeTypeSameLastZoneLengthDifferent = STORAGE_ZONES_ATTRIBUTES.SameLastZoneLengthDifferent;
pub const ZonesAttributeTypeMayDifferentLengthSame = STORAGE_ZONES_ATTRIBUTES.MayDifferentLengthSame;
pub const STORAGE_ZONE_CONDITION = enum(i32) {
Conventional = 0,
Empty = 1,
ImplicitlyOpened = 2,
ExplicitlyOpened = 3,
Closed = 4,
ReadOnly = 13,
Full = 14,
Offline = 15,
};
pub const ZoneConditionConventional = STORAGE_ZONE_CONDITION.Conventional;
pub const ZoneConditionEmpty = STORAGE_ZONE_CONDITION.Empty;
pub const ZoneConditionImplicitlyOpened = STORAGE_ZONE_CONDITION.ImplicitlyOpened;
pub const ZoneConditionExplicitlyOpened = STORAGE_ZONE_CONDITION.ExplicitlyOpened;
pub const ZoneConditionClosed = STORAGE_ZONE_CONDITION.Closed;
pub const ZoneConditionReadOnly = STORAGE_ZONE_CONDITION.ReadOnly;
pub const ZoneConditionFull = STORAGE_ZONE_CONDITION.Full;
pub const ZoneConditionOffline = STORAGE_ZONE_CONDITION.Offline;
pub const STORAGE_ZONE_DESCRIPTOR = extern struct {
Size: u32,
ZoneType: STORAGE_ZONE_TYPES,
ZoneCondition: STORAGE_ZONE_CONDITION,
ResetWritePointerRecommend: BOOLEAN,
Reserved0: [3]u8,
ZoneSize: u64,
WritePointerOffset: u64,
};
pub const DEVICE_DSM_REPORT_ZONES_DATA = extern struct {
Size: u32,
ZoneCount: u32,
Attributes: STORAGE_ZONES_ATTRIBUTES,
Reserved0: u32,
ZoneDescriptors: [1]STORAGE_ZONE_DESCRIPTOR,
};
pub const DEVICE_STORAGE_RANGE_ATTRIBUTES = extern struct {
LengthInBytes: u64,
Anonymous: extern union {
AllFlags: u32,
Anonymous: extern struct {
_bitfield: u32,
},
},
Reserved: u32,
};
pub const DEVICE_DSM_RANGE_ERROR_INFO = extern struct {
Version: u32,
Flags: u32,
TotalNumberOfRanges: u32,
NumberOfRangesReturned: u32,
Ranges: [1]DEVICE_STORAGE_RANGE_ATTRIBUTES,
};
pub const DEVICE_DSM_LOST_QUERY_PARAMETERS = extern struct {
Version: u32,
Granularity: u64,
};
pub const DEVICE_DSM_LOST_QUERY_OUTPUT = extern struct {
Version: u32,
Size: u32,
Alignment: u64,
NumberOfBits: u32,
BitMap: [1]u32,
};
pub const DEVICE_DSM_FREE_SPACE_OUTPUT = extern struct {
Version: u32,
FreeSpace: u64,
};
pub const DEVICE_DSM_CONVERSION_OUTPUT = extern struct {
Version: u32,
Source: Guid,
};
pub const STORAGE_GET_BC_PROPERTIES_OUTPUT = extern struct {
MaximumRequestsPerPeriod: u32,
MinimumPeriod: u32,
MaximumRequestSize: u64,
EstimatedTimePerRequest: u32,
NumOutStandingRequests: u32,
RequestSize: u64,
};
pub const STORAGE_ALLOCATE_BC_STREAM_INPUT = extern struct {
Version: u32,
RequestsPerPeriod: u32,
Period: u32,
RetryFailures: BOOLEAN,
Discardable: BOOLEAN,
Reserved1: [2]BOOLEAN,
AccessType: u32,
AccessMode: u32,
};
pub const STORAGE_ALLOCATE_BC_STREAM_OUTPUT = extern struct {
RequestSize: u64,
NumOutStandingRequests: u32,
};
pub const STORAGE_PRIORITY_HINT_SUPPORT = extern struct {
SupportFlags: u32,
};
pub const STORAGE_DIAGNOSTIC_LEVEL = enum(i32) {
Default = 0,
Max = 1,
};
pub const StorageDiagnosticLevelDefault = STORAGE_DIAGNOSTIC_LEVEL.Default;
pub const StorageDiagnosticLevelMax = STORAGE_DIAGNOSTIC_LEVEL.Max;
pub const STORAGE_DIAGNOSTIC_TARGET_TYPE = enum(i32) {
Undefined = 0,
Port = 1,
Miniport = 2,
HbaFirmware = 3,
Max = 4,
};
pub const StorageDiagnosticTargetTypeUndefined = STORAGE_DIAGNOSTIC_TARGET_TYPE.Undefined;
pub const StorageDiagnosticTargetTypePort = STORAGE_DIAGNOSTIC_TARGET_TYPE.Port;
pub const StorageDiagnosticTargetTypeMiniport = STORAGE_DIAGNOSTIC_TARGET_TYPE.Miniport;
pub const StorageDiagnosticTargetTypeHbaFirmware = STORAGE_DIAGNOSTIC_TARGET_TYPE.HbaFirmware;
pub const StorageDiagnosticTargetTypeMax = STORAGE_DIAGNOSTIC_TARGET_TYPE.Max;
pub const STORAGE_DIAGNOSTIC_REQUEST = extern struct {
Version: u32,
Size: u32,
Reserved: u32,
TargetType: STORAGE_DIAGNOSTIC_TARGET_TYPE,
Level: STORAGE_DIAGNOSTIC_LEVEL,
};
pub const STORAGE_DIAGNOSTIC_DATA = extern struct {
Version: u32,
Size: u32,
ProviderId: Guid,
BufferSize: u32,
Reserved: u32,
DiagnosticDataBuffer: [1]u8,
};
pub const PHYSICAL_ELEMENT_STATUS_REQUEST = extern struct {
Version: u32,
Size: u32,
StartingElement: u32,
Filter: u8,
ReportType: u8,
Reserved: [2]u8,
};
pub const PHYSICAL_ELEMENT_STATUS_DESCRIPTOR = extern struct {
Version: u32,
Size: u32,
ElementIdentifier: u32,
PhysicalElementType: u8,
PhysicalElementHealth: u8,
Reserved1: [2]u8,
AssociatedCapacity: u64,
Reserved2: [4]u32,
};
pub const PHYSICAL_ELEMENT_STATUS = extern struct {
Version: u32,
Size: u32,
DescriptorCount: u32,
ReturnedDescriptorCount: u32,
ElementIdentifierBeingDepoped: u32,
Reserved: u32,
Descriptors: [1]PHYSICAL_ELEMENT_STATUS_DESCRIPTOR,
};
pub const REMOVE_ELEMENT_AND_TRUNCATE_REQUEST = extern struct {
Version: u32,
Size: u32,
RequestCapacity: u64,
ElementIdentifier: u32,
Reserved: u32,
};
pub const DEVICE_INTERNAL_STATUS_DATA_REQUEST_TYPE = enum(i32) {
InternalStatusDataRequestTypeUndefined = 0,
CurrentInternalStatusDataHeader = 1,
CurrentInternalStatusData = 2,
};
pub const DeviceInternalStatusDataRequestTypeUndefined = DEVICE_INTERNAL_STATUS_DATA_REQUEST_TYPE.InternalStatusDataRequestTypeUndefined;
pub const DeviceCurrentInternalStatusDataHeader = DEVICE_INTERNAL_STATUS_DATA_REQUEST_TYPE.CurrentInternalStatusDataHeader;
pub const DeviceCurrentInternalStatusData = DEVICE_INTERNAL_STATUS_DATA_REQUEST_TYPE.CurrentInternalStatusData;
pub const DEVICE_INTERNAL_STATUS_DATA_SET = enum(i32) {
Undefined = 0,
@"1" = 1,
@"2" = 2,
@"3" = 3,
@"4" = 4,
Max = 5,
};
pub const DeviceStatusDataSetUndefined = DEVICE_INTERNAL_STATUS_DATA_SET.Undefined;
pub const DeviceStatusDataSet1 = DEVICE_INTERNAL_STATUS_DATA_SET.@"1";
pub const DeviceStatusDataSet2 = DEVICE_INTERNAL_STATUS_DATA_SET.@"2";
pub const DeviceStatusDataSet3 = DEVICE_INTERNAL_STATUS_DATA_SET.@"3";
pub const DeviceStatusDataSet4 = DEVICE_INTERNAL_STATUS_DATA_SET.@"4";
pub const DeviceStatusDataSetMax = DEVICE_INTERNAL_STATUS_DATA_SET.Max;
pub const GET_DEVICE_INTERNAL_STATUS_DATA_REQUEST = extern struct {
Version: u32,
Size: u32,
RequestDataType: DEVICE_INTERNAL_STATUS_DATA_REQUEST_TYPE,
RequestDataSet: DEVICE_INTERNAL_STATUS_DATA_SET,
};
pub const DEVICE_INTERNAL_STATUS_DATA = extern struct {
Version: u32,
Size: u32,
T10VendorId: u64,
DataSet1Length: u32,
DataSet2Length: u32,
DataSet3Length: u32,
DataSet4Length: u32,
StatusDataVersion: u8,
Reserved: [3]u8,
ReasonIdentifier: [128]u8,
StatusDataLength: u32,
StatusData: [1]u8,
};
pub const STORAGE_MEDIA_SERIAL_NUMBER_DATA = extern struct {
Reserved: u16,
SerialNumberLength: u16,
SerialNumber: [1]u8,
};
pub const STORAGE_READ_CAPACITY = extern struct {
Version: u32,
Size: u32,
BlockLength: u32,
NumberOfBlocks: LARGE_INTEGER,
DiskLength: LARGE_INTEGER,
};
pub const PERSISTENT_RESERVE_COMMAND = extern struct {
Version: u32,
Size: u32,
Anonymous: extern union {
PR_IN: extern struct {
_bitfield: u8,
AllocationLength: u16,
},
PR_OUT: extern struct {
_bitfield1: u8,
_bitfield2: u8,
ParameterList: [1]u8,
},
},
};
pub const _DEVICEDUMP_COLLECTION_TYPE = enum(i32) {
BugCheck = 1,
ApplicationRequested = 2,
DeviceRequested = 3,
};
pub const TCCollectionBugCheck = _DEVICEDUMP_COLLECTION_TYPE.BugCheck;
pub const TCCollectionApplicationRequested = _DEVICEDUMP_COLLECTION_TYPE.ApplicationRequested;
pub const TCCollectionDeviceRequested = _DEVICEDUMP_COLLECTION_TYPE.DeviceRequested;
pub const DEVICEDUMP_SUBSECTION_POINTER = packed struct {
dwSize: u32,
dwFlags: u32,
dwOffset: u32,
};
pub const DEVICEDUMP_STRUCTURE_VERSION = packed struct {
dwSignature: u32,
dwVersion: u32,
dwSize: u32,
};
pub const DEVICEDUMP_SECTION_HEADER = packed struct {
guidDeviceDataId: Guid,
sOrganizationID: [16]u8,
dwFirmwareRevision: u32,
sModelNumber: [32]u8,
szDeviceManufacturingID: [32]u8,
dwFlags: u32,
bRestrictedPrivateDataVersion: u32,
dwFirmwareIssueId: u32,
szIssueDescriptionString: [132]u8,
};
pub const GP_LOG_PAGE_DESCRIPTOR = packed struct {
LogAddress: u16,
LogSectors: u16,
};
pub const DEVICEDUMP_PUBLIC_SUBSECTION = packed struct {
dwFlags: u32,
GPLogTable: [16]GP_LOG_PAGE_DESCRIPTOR,
szDescription: [16]CHAR,
bData: [1]u8,
};
pub const DEVICEDUMP_RESTRICTED_SUBSECTION = extern struct {
bData: [1]u8,
};
pub const DEVICEDUMP_PRIVATE_SUBSECTION = packed struct {
dwFlags: u32,
GPLogId: GP_LOG_PAGE_DESCRIPTOR,
bData: [1]u8,
};
pub const DEVICEDUMP_STORAGEDEVICE_DATA = packed struct {
Descriptor: DEVICEDUMP_STRUCTURE_VERSION,
SectionHeader: DEVICEDUMP_SECTION_HEADER,
dwBufferSize: u32,
dwReasonForCollection: u32,
PublicData: DEVICEDUMP_SUBSECTION_POINTER,
RestrictedData: DEVICEDUMP_SUBSECTION_POINTER,
PrivateData: DEVICEDUMP_SUBSECTION_POINTER,
};
pub const DEVICEDUMP_STORAGESTACK_PUBLIC_STATE_RECORD = packed struct {
Cdb: [16]u8,
Command: [16]u8,
StartTime: u64,
EndTime: u64,
OperationStatus: u32,
OperationError: u32,
StackSpecific: extern union {
ExternalStack: packed struct {
dwReserved: u32,
},
AtaPort: packed struct {
dwAtaPortSpecific: u32,
},
StorPort: packed struct {
SrbTag: u32,
},
},
};
pub const DEVICEDUMP_STORAGESTACK_PUBLIC_DUMP = packed struct {
Descriptor: DEVICEDUMP_STRUCTURE_VERSION,
dwReasonForCollection: u32,
cDriverName: [16]u8,
uiNumRecords: u32,
RecordArray: [1]DEVICEDUMP_STORAGESTACK_PUBLIC_STATE_RECORD,
};
pub const STORAGE_IDLE_POWER = extern struct {
Version: u32,
Size: u32,
_bitfield: u32,
D3IdleTimeout: u32,
};
pub const STORAGE_POWERUP_REASON_TYPE = enum(i32) {
Unknown = 0,
IO = 1,
DeviceAttention = 2,
};
pub const StoragePowerupUnknown = STORAGE_POWERUP_REASON_TYPE.Unknown;
pub const StoragePowerupIO = STORAGE_POWERUP_REASON_TYPE.IO;
pub const StoragePowerupDeviceAttention = STORAGE_POWERUP_REASON_TYPE.DeviceAttention;
pub const STORAGE_IDLE_POWERUP_REASON = extern struct {
Version: u32,
Size: u32,
PowerupReason: STORAGE_POWERUP_REASON_TYPE,
};
pub const STORAGE_RPMB_DATA_FRAME = extern struct {
Stuff: [196]u8,
KeyOrMAC: [32]u8,
Data: [256]u8,
Nonce: [16]u8,
WriteCounter: [4]u8,
Address: [2]u8,
BlockCount: [2]u8,
OperationResult: [2]u8,
RequestOrResponseType: [2]u8,
};
pub const STORAGE_RPMB_COMMAND_TYPE = enum(i32) {
ProgramAuthKey = 1,
QueryWriteCounter = 2,
AuthenticatedWrite = 3,
AuthenticatedRead = 4,
ReadResultRequest = 5,
AuthenticatedDeviceConfigWrite = 6,
AuthenticatedDeviceConfigRead = 7,
};
pub const StorRpmbProgramAuthKey = STORAGE_RPMB_COMMAND_TYPE.ProgramAuthKey;
pub const StorRpmbQueryWriteCounter = STORAGE_RPMB_COMMAND_TYPE.QueryWriteCounter;
pub const StorRpmbAuthenticatedWrite = STORAGE_RPMB_COMMAND_TYPE.AuthenticatedWrite;
pub const StorRpmbAuthenticatedRead = STORAGE_RPMB_COMMAND_TYPE.AuthenticatedRead;
pub const StorRpmbReadResultRequest = STORAGE_RPMB_COMMAND_TYPE.ReadResultRequest;
pub const StorRpmbAuthenticatedDeviceConfigWrite = STORAGE_RPMB_COMMAND_TYPE.AuthenticatedDeviceConfigWrite;
pub const StorRpmbAuthenticatedDeviceConfigRead = STORAGE_RPMB_COMMAND_TYPE.AuthenticatedDeviceConfigRead;
pub const STORAGE_EVENT_NOTIFICATION = extern struct {
Version: u32,
Size: u32,
Events: u64,
};
pub const STORAGE_COUNTER_TYPE = enum(i32) {
Unknown = 0,
TemperatureCelsius = 1,
TemperatureCelsiusMax = 2,
ReadErrorsTotal = 3,
ReadErrorsCorrected = 4,
ReadErrorsUncorrected = 5,
WriteErrorsTotal = 6,
WriteErrorsCorrected = 7,
WriteErrorsUncorrected = 8,
ManufactureDate = 9,
StartStopCycleCount = 10,
StartStopCycleCountMax = 11,
LoadUnloadCycleCount = 12,
LoadUnloadCycleCountMax = 13,
WearPercentage = 14,
WearPercentageWarning = 15,
WearPercentageMax = 16,
PowerOnHours = 17,
ReadLatency100NSMax = 18,
WriteLatency100NSMax = 19,
FlushLatency100NSMax = 20,
Max = 21,
};
pub const StorageCounterTypeUnknown = STORAGE_COUNTER_TYPE.Unknown;
pub const StorageCounterTypeTemperatureCelsius = STORAGE_COUNTER_TYPE.TemperatureCelsius;
pub const StorageCounterTypeTemperatureCelsiusMax = STORAGE_COUNTER_TYPE.TemperatureCelsiusMax;
pub const StorageCounterTypeReadErrorsTotal = STORAGE_COUNTER_TYPE.ReadErrorsTotal;
pub const StorageCounterTypeReadErrorsCorrected = STORAGE_COUNTER_TYPE.ReadErrorsCorrected;
pub const StorageCounterTypeReadErrorsUncorrected = STORAGE_COUNTER_TYPE.ReadErrorsUncorrected;
pub const StorageCounterTypeWriteErrorsTotal = STORAGE_COUNTER_TYPE.WriteErrorsTotal;
pub const StorageCounterTypeWriteErrorsCorrected = STORAGE_COUNTER_TYPE.WriteErrorsCorrected;
pub const StorageCounterTypeWriteErrorsUncorrected = STORAGE_COUNTER_TYPE.WriteErrorsUncorrected;
pub const StorageCounterTypeManufactureDate = STORAGE_COUNTER_TYPE.ManufactureDate;
pub const StorageCounterTypeStartStopCycleCount = STORAGE_COUNTER_TYPE.StartStopCycleCount;
pub const StorageCounterTypeStartStopCycleCountMax = STORAGE_COUNTER_TYPE.StartStopCycleCountMax;
pub const StorageCounterTypeLoadUnloadCycleCount = STORAGE_COUNTER_TYPE.LoadUnloadCycleCount;
pub const StorageCounterTypeLoadUnloadCycleCountMax = STORAGE_COUNTER_TYPE.LoadUnloadCycleCountMax;
pub const StorageCounterTypeWearPercentage = STORAGE_COUNTER_TYPE.WearPercentage;
pub const StorageCounterTypeWearPercentageWarning = STORAGE_COUNTER_TYPE.WearPercentageWarning;
pub const StorageCounterTypeWearPercentageMax = STORAGE_COUNTER_TYPE.WearPercentageMax;
pub const StorageCounterTypePowerOnHours = STORAGE_COUNTER_TYPE.PowerOnHours;
pub const StorageCounterTypeReadLatency100NSMax = STORAGE_COUNTER_TYPE.ReadLatency100NSMax;
pub const StorageCounterTypeWriteLatency100NSMax = STORAGE_COUNTER_TYPE.WriteLatency100NSMax;
pub const StorageCounterTypeFlushLatency100NSMax = STORAGE_COUNTER_TYPE.FlushLatency100NSMax;
pub const StorageCounterTypeMax = STORAGE_COUNTER_TYPE.Max;
pub const STORAGE_COUNTER = extern struct {
Type: STORAGE_COUNTER_TYPE,
Value: extern union {
ManufactureDate: extern struct {
Week: u32,
Year: u32,
},
AsUlonglong: u64,
},
};
pub const STORAGE_COUNTERS = extern struct {
Version: u32,
Size: u32,
NumberOfCounters: u32,
Counters: [1]STORAGE_COUNTER,
};
pub const STORAGE_HW_FIRMWARE_INFO_QUERY = extern struct {
Version: u32,
Size: u32,
Flags: u32,
Reserved: u32,
};
pub const STORAGE_HW_FIRMWARE_SLOT_INFO = extern struct {
Version: u32,
Size: u32,
SlotNumber: u8,
_bitfield: u8,
Reserved1: [6]u8,
Revision: [16]u8,
};
pub const STORAGE_HW_FIRMWARE_INFO = extern struct {
Version: u32,
Size: u32,
_bitfield: u8,
SlotCount: u8,
ActiveSlot: u8,
PendingActivateSlot: u8,
FirmwareShared: BOOLEAN,
Reserved: [3]u8,
ImagePayloadAlignment: u32,
ImagePayloadMaxSize: u32,
Slot: [1]STORAGE_HW_FIRMWARE_SLOT_INFO,
};
pub const STORAGE_HW_FIRMWARE_DOWNLOAD_V2 = extern struct {
Version: u32,
Size: u32,
Flags: u32,
Slot: u8,
Reserved: [3]u8,
Offset: u64,
BufferSize: u64,
ImageSize: u32,
Reserved2: u32,
ImageBuffer: [1]u8,
};
pub const STORAGE_ATTRIBUTE_MGMT_ACTION = enum(i32) {
ClearAttribute = 0,
SetAttribute = 1,
ResetAttribute = 2,
};
pub const StorAttributeMgmt_ClearAttribute = STORAGE_ATTRIBUTE_MGMT_ACTION.ClearAttribute;
pub const StorAttributeMgmt_SetAttribute = STORAGE_ATTRIBUTE_MGMT_ACTION.SetAttribute;
pub const StorAttributeMgmt_ResetAttribute = STORAGE_ATTRIBUTE_MGMT_ACTION.ResetAttribute;
pub const STORAGE_ATTRIBUTE_MGMT = extern struct {
Version: u32,
Size: u32,
Action: STORAGE_ATTRIBUTE_MGMT_ACTION,
Attribute: u32,
};
pub const SCM_PD_HEALTH_NOTIFICATION_DATA = extern struct {
DeviceGuid: Guid,
};
pub const SCM_LOGICAL_DEVICE_INSTANCE = extern struct {
Version: u32,
Size: u32,
DeviceGuid: Guid,
SymbolicLink: [256]u16,
};
pub const SCM_LOGICAL_DEVICES = extern struct {
Version: u32,
Size: u32,
DeviceCount: u32,
Devices: [1]SCM_LOGICAL_DEVICE_INSTANCE,
};
pub const SCM_PHYSICAL_DEVICE_INSTANCE = extern struct {
Version: u32,
Size: u32,
NfitHandle: u32,
SymbolicLink: [256]u16,
};
pub const SCM_PHYSICAL_DEVICES = extern struct {
Version: u32,
Size: u32,
DeviceCount: u32,
Devices: [1]SCM_PHYSICAL_DEVICE_INSTANCE,
};
pub const SCM_REGION_FLAG = enum(i32) {
None = 0,
Label = 1,
};
pub const ScmRegionFlagNone = SCM_REGION_FLAG.None;
pub const ScmRegionFlagLabel = SCM_REGION_FLAG.Label;
pub const SCM_REGION = extern struct {
Version: u32,
Size: u32,
Flags: u32,
NfitHandle: u32,
LogicalDeviceGuid: Guid,
AddressRangeType: Guid,
AssociatedId: u32,
Length: u64,
StartingDPA: u64,
BaseSPA: u64,
SPAOffset: u64,
RegionOffset: u64,
};
pub const SCM_REGIONS = extern struct {
Version: u32,
Size: u32,
RegionCount: u32,
Regions: [1]SCM_REGION,
};
pub const SCM_INTERLEAVED_PD_INFO = extern struct {
DeviceHandle: u32,
DeviceGuid: Guid,
};
pub const SCM_LD_INTERLEAVE_SET_INFO = extern struct {
Version: u32,
Size: u32,
InterleaveSetSize: u32,
InterleaveSet: [1]SCM_INTERLEAVED_PD_INFO,
};
pub const SCM_PD_QUERY_TYPE = enum(i32) {
Descriptor = 0,
IsSupported = 1,
Max = 2,
};
pub const ScmPhysicalDeviceQuery_Descriptor = SCM_PD_QUERY_TYPE.Descriptor;
pub const ScmPhysicalDeviceQuery_IsSupported = SCM_PD_QUERY_TYPE.IsSupported;
pub const ScmPhysicalDeviceQuery_Max = SCM_PD_QUERY_TYPE.Max;
pub const SCM_PD_PROPERTY_ID = enum(i32) {
DeviceInfo = 0,
ManagementStatus = 1,
FirmwareInfo = 2,
LocationString = 3,
DeviceSpecificInfo = 4,
DeviceHandle = 5,
Max = 6,
};
pub const ScmPhysicalDeviceProperty_DeviceInfo = SCM_PD_PROPERTY_ID.DeviceInfo;
pub const ScmPhysicalDeviceProperty_ManagementStatus = SCM_PD_PROPERTY_ID.ManagementStatus;
pub const ScmPhysicalDeviceProperty_FirmwareInfo = SCM_PD_PROPERTY_ID.FirmwareInfo;
pub const ScmPhysicalDeviceProperty_LocationString = SCM_PD_PROPERTY_ID.LocationString;
pub const ScmPhysicalDeviceProperty_DeviceSpecificInfo = SCM_PD_PROPERTY_ID.DeviceSpecificInfo;
pub const ScmPhysicalDeviceProperty_DeviceHandle = SCM_PD_PROPERTY_ID.DeviceHandle;
pub const ScmPhysicalDeviceProperty_Max = SCM_PD_PROPERTY_ID.Max;
pub const SCM_PD_PROPERTY_QUERY = extern struct {
Version: u32,
Size: u32,
PropertyId: SCM_PD_PROPERTY_ID,
QueryType: SCM_PD_QUERY_TYPE,
AdditionalParameters: [1]u8,
};
pub const SCM_PD_DESCRIPTOR_HEADER = extern struct {
Version: u32,
Size: u32,
};
pub const SCM_PD_DEVICE_HANDLE = extern struct {
Version: u32,
Size: u32,
DeviceGuid: Guid,
DeviceHandle: u32,
};
pub const SCM_PD_DEVICE_INFO = extern struct {
Version: u32,
Size: u32,
DeviceGuid: Guid,
UnsafeShutdownCount: u32,
PersistentMemorySizeInBytes: u64,
VolatileMemorySizeInBytes: u64,
TotalMemorySizeInBytes: u64,
SlotNumber: u32,
DeviceHandle: u32,
PhysicalId: u16,
NumberOfFormatInterfaceCodes: u8,
FormatInterfaceCodes: [8]u16,
VendorId: u32,
ProductId: u32,
SubsystemDeviceId: u32,
SubsystemVendorId: u32,
ManufacturingLocation: u8,
ManufacturingWeek: u8,
ManufacturingYear: u8,
SerialNumber4Byte: u32,
SerialNumberLengthInChars: u32,
SerialNumber: [1]CHAR,
};
pub const SCM_PD_DEVICE_SPECIFIC_PROPERTY = extern struct {
Name: [128]u16,
Value: i64,
};
pub const SCM_PD_DEVICE_SPECIFIC_INFO = extern struct {
Version: u32,
Size: u32,
NumberOfProperties: u32,
DeviceSpecificProperties: [1]SCM_PD_DEVICE_SPECIFIC_PROPERTY,
};
pub const SCM_PD_FIRMWARE_SLOT_INFO = extern struct {
Version: u32,
Size: u32,
SlotNumber: u8,
_bitfield: u8,
Reserved1: [6]u8,
Revision: [32]u8,
};
pub const SCM_PD_FIRMWARE_INFO = extern struct {
Version: u32,
Size: u32,
ActiveSlot: u8,
NextActiveSlot: u8,
SlotCount: u8,
Slots: [1]SCM_PD_FIRMWARE_SLOT_INFO,
};
pub const SCM_PD_HEALTH_STATUS = enum(i32) {
Unknown = 0,
Unhealthy = 1,
Warning = 2,
Healthy = 3,
Max = 4,
};
pub const ScmPhysicalDeviceHealth_Unknown = SCM_PD_HEALTH_STATUS.Unknown;
pub const ScmPhysicalDeviceHealth_Unhealthy = SCM_PD_HEALTH_STATUS.Unhealthy;
pub const ScmPhysicalDeviceHealth_Warning = SCM_PD_HEALTH_STATUS.Warning;
pub const ScmPhysicalDeviceHealth_Healthy = SCM_PD_HEALTH_STATUS.Healthy;
pub const ScmPhysicalDeviceHealth_Max = SCM_PD_HEALTH_STATUS.Max;
pub const SCM_PD_OPERATIONAL_STATUS = enum(i32) {
Unknown = 0,
Ok = 1,
PredictingFailure = 2,
InService = 3,
HardwareError = 4,
NotUsable = 5,
TransientError = 6,
Missing = 7,
Max = 8,
};
pub const ScmPhysicalDeviceOpStatus_Unknown = SCM_PD_OPERATIONAL_STATUS.Unknown;
pub const ScmPhysicalDeviceOpStatus_Ok = SCM_PD_OPERATIONAL_STATUS.Ok;
pub const ScmPhysicalDeviceOpStatus_PredictingFailure = SCM_PD_OPERATIONAL_STATUS.PredictingFailure;
pub const ScmPhysicalDeviceOpStatus_InService = SCM_PD_OPERATIONAL_STATUS.InService;
pub const ScmPhysicalDeviceOpStatus_HardwareError = SCM_PD_OPERATIONAL_STATUS.HardwareError;
pub const ScmPhysicalDeviceOpStatus_NotUsable = SCM_PD_OPERATIONAL_STATUS.NotUsable;
pub const ScmPhysicalDeviceOpStatus_TransientError = SCM_PD_OPERATIONAL_STATUS.TransientError;
pub const ScmPhysicalDeviceOpStatus_Missing = SCM_PD_OPERATIONAL_STATUS.Missing;
pub const ScmPhysicalDeviceOpStatus_Max = SCM_PD_OPERATIONAL_STATUS.Max;
pub const SCM_PD_OPERATIONAL_STATUS_REASON = enum(i32) {
Unknown = 0,
Media = 1,
ThresholdExceeded = 2,
LostData = 3,
EnergySource = 4,
Configuration = 5,
DeviceController = 6,
MediaController = 7,
Component = 8,
BackgroundOperation = 9,
InvalidFirmware = 10,
HealthCheck = 11,
LostDataPersistence = 12,
DisabledByPlatform = 13,
PermanentError = 14,
LostWritePersistence = 15,
FatalError = 16,
DataPersistenceLossImminent = 17,
WritePersistenceLossImminent = 18,
MediaRemainingSpareBlock = 19,
PerformanceDegradation = 20,
ExcessiveTemperature = 21,
Max = 22,
};
pub const ScmPhysicalDeviceOpReason_Unknown = SCM_PD_OPERATIONAL_STATUS_REASON.Unknown;
pub const ScmPhysicalDeviceOpReason_Media = SCM_PD_OPERATIONAL_STATUS_REASON.Media;
pub const ScmPhysicalDeviceOpReason_ThresholdExceeded = SCM_PD_OPERATIONAL_STATUS_REASON.ThresholdExceeded;
pub const ScmPhysicalDeviceOpReason_LostData = SCM_PD_OPERATIONAL_STATUS_REASON.LostData;
pub const ScmPhysicalDeviceOpReason_EnergySource = SCM_PD_OPERATIONAL_STATUS_REASON.EnergySource;
pub const ScmPhysicalDeviceOpReason_Configuration = SCM_PD_OPERATIONAL_STATUS_REASON.Configuration;
pub const ScmPhysicalDeviceOpReason_DeviceController = SCM_PD_OPERATIONAL_STATUS_REASON.DeviceController;
pub const ScmPhysicalDeviceOpReason_MediaController = SCM_PD_OPERATIONAL_STATUS_REASON.MediaController;
pub const ScmPhysicalDeviceOpReason_Component = SCM_PD_OPERATIONAL_STATUS_REASON.Component;
pub const ScmPhysicalDeviceOpReason_BackgroundOperation = SCM_PD_OPERATIONAL_STATUS_REASON.BackgroundOperation;
pub const ScmPhysicalDeviceOpReason_InvalidFirmware = SCM_PD_OPERATIONAL_STATUS_REASON.InvalidFirmware;
pub const ScmPhysicalDeviceOpReason_HealthCheck = SCM_PD_OPERATIONAL_STATUS_REASON.HealthCheck;
pub const ScmPhysicalDeviceOpReason_LostDataPersistence = SCM_PD_OPERATIONAL_STATUS_REASON.LostDataPersistence;
pub const ScmPhysicalDeviceOpReason_DisabledByPlatform = SCM_PD_OPERATIONAL_STATUS_REASON.DisabledByPlatform;
pub const ScmPhysicalDeviceOpReason_PermanentError = SCM_PD_OPERATIONAL_STATUS_REASON.PermanentError;
pub const ScmPhysicalDeviceOpReason_LostWritePersistence = SCM_PD_OPERATIONAL_STATUS_REASON.LostWritePersistence;
pub const ScmPhysicalDeviceOpReason_FatalError = SCM_PD_OPERATIONAL_STATUS_REASON.FatalError;
pub const ScmPhysicalDeviceOpReason_DataPersistenceLossImminent = SCM_PD_OPERATIONAL_STATUS_REASON.DataPersistenceLossImminent;
pub const ScmPhysicalDeviceOpReason_WritePersistenceLossImminent = SCM_PD_OPERATIONAL_STATUS_REASON.WritePersistenceLossImminent;
pub const ScmPhysicalDeviceOpReason_MediaRemainingSpareBlock = SCM_PD_OPERATIONAL_STATUS_REASON.MediaRemainingSpareBlock;
pub const ScmPhysicalDeviceOpReason_PerformanceDegradation = SCM_PD_OPERATIONAL_STATUS_REASON.PerformanceDegradation;
pub const ScmPhysicalDeviceOpReason_ExcessiveTemperature = SCM_PD_OPERATIONAL_STATUS_REASON.ExcessiveTemperature;
pub const ScmPhysicalDeviceOpReason_Max = SCM_PD_OPERATIONAL_STATUS_REASON.Max;
pub const SCM_PD_MANAGEMENT_STATUS = extern struct {
Version: u32,
Size: u32,
Health: SCM_PD_HEALTH_STATUS,
NumberOfOperationalStatus: u32,
NumberOfAdditionalReasons: u32,
OperationalStatus: [16]SCM_PD_OPERATIONAL_STATUS,
AdditionalReasons: [1]SCM_PD_OPERATIONAL_STATUS_REASON,
};
pub const SCM_PD_LOCATION_STRING = extern struct {
Version: u32,
Size: u32,
Location: [1]u16,
};
pub const SCM_PD_FIRMWARE_DOWNLOAD = extern struct {
Version: u32,
Size: u32,
Flags: u32,
Slot: u8,
Reserved: [3]u8,
Offset: u64,
FirmwareImageSizeInBytes: u32,
FirmwareImage: [1]u8,
};
pub const SCM_PD_FIRMWARE_ACTIVATE = extern struct {
Version: u32,
Size: u32,
Flags: u32,
Slot: u8,
};
pub const SCM_PD_PASSTHROUGH_INPUT = extern struct {
Version: u32,
Size: u32,
ProtocolGuid: Guid,
DataSize: u32,
Data: [1]u8,
};
pub const SCM_PD_PASSTHROUGH_OUTPUT = extern struct {
Version: u32,
Size: u32,
ProtocolGuid: Guid,
DataSize: u32,
Data: [1]u8,
};
pub const SCM_PD_PASSTHROUGH_INVDIMM_INPUT = extern struct {
Opcode: u32,
OpcodeParametersLength: u32,
OpcodeParameters: [1]u8,
};
pub const SCM_PD_PASSTHROUGH_INVDIMM_OUTPUT = extern struct {
GeneralStatus: u16,
ExtendedStatus: u16,
OutputDataLength: u32,
OutputData: [1]u8,
};
pub const SCM_PD_REINITIALIZE_MEDIA_INPUT = extern struct {
Version: u32,
Size: u32,
Options: extern struct {
_bitfield: u32,
},
};
pub const SCM_PD_MEDIA_REINITIALIZATION_STATUS = enum(i32) {
Success = 0,
RebootNeeded = 1,
ColdBootNeeded = 2,
Max = 3,
};
pub const ScmPhysicalDeviceReinit_Success = SCM_PD_MEDIA_REINITIALIZATION_STATUS.Success;
pub const ScmPhysicalDeviceReinit_RebootNeeded = SCM_PD_MEDIA_REINITIALIZATION_STATUS.RebootNeeded;
pub const ScmPhysicalDeviceReinit_ColdBootNeeded = SCM_PD_MEDIA_REINITIALIZATION_STATUS.ColdBootNeeded;
pub const ScmPhysicalDeviceReinit_Max = SCM_PD_MEDIA_REINITIALIZATION_STATUS.Max;
pub const SCM_PD_REINITIALIZE_MEDIA_OUTPUT = extern struct {
Version: u32,
Size: u32,
Status: SCM_PD_MEDIA_REINITIALIZATION_STATUS,
};
pub const SET_PARTITION_INFORMATION_EX = extern struct {
PartitionStyle: PARTITION_STYLE,
Anonymous: extern union {
Mbr: SET_PARTITION_INFORMATION,
Gpt: PARTITION_INFORMATION_GPT,
},
};
pub const DETECTION_TYPE = enum(i32) {
None = 0,
Int13 = 1,
ExInt13 = 2,
};
pub const DetectNone = DETECTION_TYPE.None;
pub const DetectInt13 = DETECTION_TYPE.Int13;
pub const DetectExInt13 = DETECTION_TYPE.ExInt13;
pub const DISK_CONTROLLER_NUMBER = extern struct {
ControllerNumber: u32,
DiskNumber: u32,
};
pub const DISK_CACHE_RETENTION_PRIORITY = enum(i32) {
EqualPriority = 0,
KeepPrefetchedData = 1,
KeepReadData = 2,
};
pub const EqualPriority = DISK_CACHE_RETENTION_PRIORITY.EqualPriority;
pub const KeepPrefetchedData = DISK_CACHE_RETENTION_PRIORITY.KeepPrefetchedData;
pub const KeepReadData = DISK_CACHE_RETENTION_PRIORITY.KeepReadData;
pub const HISTOGRAM_BUCKET = extern struct {
Reads: u32,
Writes: u32,
};
pub const DISK_HISTOGRAM = extern struct {
DiskSize: LARGE_INTEGER,
Start: LARGE_INTEGER,
End: LARGE_INTEGER,
Average: LARGE_INTEGER,
AverageRead: LARGE_INTEGER,
AverageWrite: LARGE_INTEGER,
Granularity: u32,
Size: u32,
ReadCount: u32,
WriteCount: u32,
Histogram: ?*HISTOGRAM_BUCKET,
};
pub const DISK_RECORD = extern struct {
ByteOffset: LARGE_INTEGER,
StartTime: LARGE_INTEGER,
EndTime: LARGE_INTEGER,
VirtualAddress: ?*c_void,
NumberOfBytes: u32,
DeviceNumber: u8,
ReadRequest: BOOLEAN,
};
pub const DISK_LOGGING = extern struct {
Function: u8,
BufferAddress: ?*c_void,
BufferSize: u32,
};
pub const BIN_TYPES = enum(i32) {
Size = 0,
Location = 1,
};
pub const RequestSize = BIN_TYPES.Size;
pub const RequestLocation = BIN_TYPES.Location;
pub const BIN_RANGE = extern struct {
StartValue: LARGE_INTEGER,
Length: LARGE_INTEGER,
};
pub const PERF_BIN = extern struct {
NumberOfBins: u32,
TypeOfBin: u32,
BinsRanges: [1]BIN_RANGE,
};
pub const BIN_COUNT = extern struct {
BinRange: BIN_RANGE,
BinCount: u32,
};
pub const BIN_RESULTS = extern struct {
NumberOfBins: u32,
BinCounts: [1]BIN_COUNT,
};
pub const GETVERSIONINPARAMS = packed struct {
bVersion: u8,
bRevision: u8,
bReserved: u8,
bIDEDeviceMap: u8,
fCapabilities: u32,
dwReserved: [4]u32,
};
pub const IDEREGS = extern struct {
bFeaturesReg: u8,
bSectorCountReg: u8,
bSectorNumberReg: u8,
bCylLowReg: u8,
bCylHighReg: u8,
bDriveHeadReg: u8,
bCommandReg: u8,
bReserved: u8,
};
pub const SENDCMDINPARAMS = packed struct {
cBufferSize: u32,
irDriveRegs: IDEREGS,
bDriveNumber: u8,
bReserved: [3]u8,
dwReserved: [4]u32,
bBuffer: [1]u8,
};
pub const DRIVERSTATUS = packed struct {
bDriverError: u8,
bIDEError: u8,
bReserved: [2]u8,
dwReserved: [2]u32,
};
pub const SENDCMDOUTPARAMS = packed struct {
cBufferSize: u32,
DriverStatus: DRIVERSTATUS,
bBuffer: [1]u8,
};
pub const ELEMENT_TYPE = enum(i32) {
AllElements = 0,
ChangerTransport = 1,
ChangerSlot = 2,
ChangerIEPort = 3,
ChangerDrive = 4,
ChangerDoor = 5,
ChangerKeypad = 6,
ChangerMaxElement = 7,
};
pub const AllElements = ELEMENT_TYPE.AllElements;
pub const ChangerTransport = ELEMENT_TYPE.ChangerTransport;
pub const ChangerSlot = ELEMENT_TYPE.ChangerSlot;
pub const ChangerIEPort = ELEMENT_TYPE.ChangerIEPort;
pub const ChangerDrive = ELEMENT_TYPE.ChangerDrive;
pub const ChangerDoor = ELEMENT_TYPE.ChangerDoor;
pub const ChangerKeypad = ELEMENT_TYPE.ChangerKeypad;
pub const ChangerMaxElement = ELEMENT_TYPE.ChangerMaxElement;
pub const CHANGER_ELEMENT = extern struct {
ElementType: ELEMENT_TYPE,
ElementAddress: u32,
};
pub const CHANGER_ELEMENT_LIST = extern struct {
Element: CHANGER_ELEMENT,
NumberOfElements: u32,
};
pub const GET_CHANGER_PARAMETERS = extern struct {
Size: u32,
NumberTransportElements: u16,
NumberStorageElements: u16,
NumberCleanerSlots: u16,
NumberIEElements: u16,
NumberDataTransferElements: u16,
NumberOfDoors: u16,
FirstSlotNumber: u16,
FirstDriveNumber: u16,
FirstTransportNumber: u16,
FirstIEPortNumber: u16,
FirstCleanerSlotAddress: u16,
MagazineSize: u16,
DriveCleanTimeout: u32,
Features0: CHANGER_FEATURES,
Features1: GET_CHANGER_PARAMETERS_FEATURES1,
MoveFromTransport: u8,
MoveFromSlot: u8,
MoveFromIePort: u8,
MoveFromDrive: u8,
ExchangeFromTransport: u8,
ExchangeFromSlot: u8,
ExchangeFromIePort: u8,
ExchangeFromDrive: u8,
LockUnlockCapabilities: u8,
PositionCapabilities: u8,
Reserved1: [2]u8,
Reserved2: [2]u32,
};
pub const CHANGER_PRODUCT_DATA = extern struct {
VendorId: [8]u8,
ProductId: [16]u8,
Revision: [4]u8,
SerialNumber: [32]u8,
DeviceType: u8,
};
pub const CHANGER_SET_ACCESS = extern struct {
Element: CHANGER_ELEMENT,
Control: u32,
};
pub const CHANGER_READ_ELEMENT_STATUS = extern struct {
ElementList: CHANGER_ELEMENT_LIST,
VolumeTagInfo: BOOLEAN,
};
pub const CHANGER_ELEMENT_STATUS = extern struct {
Element: CHANGER_ELEMENT,
SrcElementAddress: CHANGER_ELEMENT,
Flags: CHANGER_ELEMENT_STATUS_FLAGS,
ExceptionCode: u32,
TargetId: u8,
Lun: u8,
Reserved: u16,
PrimaryVolumeID: [36]u8,
AlternateVolumeID: [36]u8,
};
pub const CHANGER_ELEMENT_STATUS_EX = extern struct {
Element: CHANGER_ELEMENT,
SrcElementAddress: CHANGER_ELEMENT,
Flags: CHANGER_ELEMENT_STATUS_FLAGS,
ExceptionCode: u32,
TargetId: u8,
Lun: u8,
Reserved: u16,
PrimaryVolumeID: [36]u8,
AlternateVolumeID: [36]u8,
VendorIdentification: [8]u8,
ProductIdentification: [16]u8,
SerialNumber: [32]u8,
};
pub const CHANGER_INITIALIZE_ELEMENT_STATUS = extern struct {
ElementList: CHANGER_ELEMENT_LIST,
BarCodeScan: BOOLEAN,
};
pub const CHANGER_SET_POSITION = extern struct {
Transport: CHANGER_ELEMENT,
Destination: CHANGER_ELEMENT,
Flip: BOOLEAN,
};
pub const CHANGER_EXCHANGE_MEDIUM = extern struct {
Transport: CHANGER_ELEMENT,
Source: CHANGER_ELEMENT,
Destination1: CHANGER_ELEMENT,
Destination2: CHANGER_ELEMENT,
Flip1: BOOLEAN,
Flip2: BOOLEAN,
};
pub const CHANGER_MOVE_MEDIUM = extern struct {
Transport: CHANGER_ELEMENT,
Source: CHANGER_ELEMENT,
Destination: CHANGER_ELEMENT,
Flip: BOOLEAN,
};
pub const CHANGER_SEND_VOLUME_TAG_INFORMATION = extern struct {
StartingElement: CHANGER_ELEMENT,
ActionCode: u32,
VolumeIDTemplate: [40]u8,
};
pub const READ_ELEMENT_ADDRESS_INFO = extern struct {
NumberOfElements: u32,
ElementStatus: [1]CHANGER_ELEMENT_STATUS,
};
pub const CHANGER_DEVICE_PROBLEM_TYPE = enum(i32) {
None = 0,
Hardware = 1,
CHMError = 2,
DoorOpen = 3,
CalibrationError = 4,
TargetFailure = 5,
CHMMoveError = 6,
CHMZeroError = 7,
CartridgeInsertError = 8,
PositionError = 9,
SensorError = 10,
CartridgeEjectError = 11,
GripperError = 12,
DriveError = 13,
};
pub const DeviceProblemNone = CHANGER_DEVICE_PROBLEM_TYPE.None;
pub const DeviceProblemHardware = CHANGER_DEVICE_PROBLEM_TYPE.Hardware;
pub const DeviceProblemCHMError = CHANGER_DEVICE_PROBLEM_TYPE.CHMError;
pub const DeviceProblemDoorOpen = CHANGER_DEVICE_PROBLEM_TYPE.DoorOpen;
pub const DeviceProblemCalibrationError = CHANGER_DEVICE_PROBLEM_TYPE.CalibrationError;
pub const DeviceProblemTargetFailure = CHANGER_DEVICE_PROBLEM_TYPE.TargetFailure;
pub const DeviceProblemCHMMoveError = CHANGER_DEVICE_PROBLEM_TYPE.CHMMoveError;
pub const DeviceProblemCHMZeroError = CHANGER_DEVICE_PROBLEM_TYPE.CHMZeroError;
pub const DeviceProblemCartridgeInsertError = CHANGER_DEVICE_PROBLEM_TYPE.CartridgeInsertError;
pub const DeviceProblemPositionError = CHANGER_DEVICE_PROBLEM_TYPE.PositionError;
pub const DeviceProblemSensorError = CHANGER_DEVICE_PROBLEM_TYPE.SensorError;
pub const DeviceProblemCartridgeEjectError = CHANGER_DEVICE_PROBLEM_TYPE.CartridgeEjectError;
pub const DeviceProblemGripperError = CHANGER_DEVICE_PROBLEM_TYPE.GripperError;
pub const DeviceProblemDriveError = CHANGER_DEVICE_PROBLEM_TYPE.DriveError;
pub const PATHNAME_BUFFER = extern struct {
PathNameLength: u32,
Name: [1]u16,
};
pub const FSCTL_QUERY_FAT_BPB_BUFFER = extern struct {
First0x24BytesOfBootSector: [36]u8,
};
pub const REFS_VOLUME_DATA_BUFFER = extern struct {
ByteCount: u32,
MajorVersion: u32,
MinorVersion: u32,
BytesPerPhysicalSector: u32,
VolumeSerialNumber: LARGE_INTEGER,
NumberSectors: LARGE_INTEGER,
TotalClusters: LARGE_INTEGER,
FreeClusters: LARGE_INTEGER,
TotalReserved: LARGE_INTEGER,
BytesPerSector: u32,
BytesPerCluster: u32,
MaximumSizeOfResidentFile: LARGE_INTEGER,
FastTierDataFillRatio: u16,
SlowTierDataFillRatio: u16,
DestagesFastTierToSlowTierRate: u32,
Reserved: [9]LARGE_INTEGER,
};
pub const STARTING_LCN_INPUT_BUFFER_EX = extern struct {
StartingLcn: LARGE_INTEGER,
Flags: u32,
};
pub const RETRIEVAL_POINTERS_AND_REFCOUNT_BUFFER = extern struct {
ExtentCount: u32,
StartingVcn: LARGE_INTEGER,
Extents: [1]extern struct {
NextVcn: LARGE_INTEGER,
Lcn: LARGE_INTEGER,
ReferenceCount: u32,
},
};
pub const RETRIEVAL_POINTER_COUNT = extern struct {
ExtentCount: u32,
};
pub const MOVE_FILE_RECORD_DATA = extern struct {
FileHandle: ?HANDLE,
SourceFileRecord: LARGE_INTEGER,
TargetFileRecord: LARGE_INTEGER,
};
pub const BULK_SECURITY_TEST_DATA = extern struct {
DesiredAccess: u32,
SecurityIds: [1]u32,
};
pub const FILE_PREFETCH = extern struct {
Type: u32,
Count: u32,
Prefetch: [1]u64,
};
pub const FILE_PREFETCH_EX = extern struct {
Type: u32,
Count: u32,
Context: ?*c_void,
Prefetch: [1]u64,
};
pub const FILE_ZERO_DATA_INFORMATION_EX = extern struct {
FileOffset: LARGE_INTEGER,
BeyondFinalZero: LARGE_INTEGER,
Flags: u32,
};
pub const ENCRYPTION_BUFFER = extern struct {
EncryptionOperation: u32,
Private: [1]u8,
};
pub const DECRYPTION_STATUS_BUFFER = extern struct {
NoEncryptedStreams: BOOLEAN,
};
pub const REQUEST_RAW_ENCRYPTED_DATA = extern struct {
FileOffset: i64,
Length: u32,
};
pub const ENCRYPTED_DATA_INFO = extern struct {
StartingFileOffset: u64,
OutputBufferOffset: u32,
BytesWithinFileSize: u32,
BytesWithinValidDataLength: u32,
CompressionFormat: u16,
DataUnitShift: u8,
ChunkShift: u8,
ClusterShift: u8,
EncryptionFormat: u8,
NumberOfDataBlocks: u16,
DataBlockSize: [1]u32,
};
pub const EXTENDED_ENCRYPTED_DATA_INFO = extern struct {
ExtendedCode: u32,
Length: u32,
Flags: u32,
Reserved: u32,
};
pub const SI_COPYFILE = extern struct {
SourceFileNameLength: u32,
DestinationFileNameLength: u32,
Flags: u32,
FileNameBuffer: [1]u16,
};
pub const FILE_INITIATE_REPAIR_OUTPUT_BUFFER = extern struct {
Hint1: u64,
Hint2: u64,
Clsn: u64,
Status: u32,
};
pub const SHRINK_VOLUME_REQUEST_TYPES = enum(i32) {
Prepare = 1,
Commit = 2,
Abort = 3,
};
pub const ShrinkPrepare = SHRINK_VOLUME_REQUEST_TYPES.Prepare;
pub const ShrinkCommit = SHRINK_VOLUME_REQUEST_TYPES.Commit;
pub const ShrinkAbort = SHRINK_VOLUME_REQUEST_TYPES.Abort;
pub const TXFS_ROLLFORWARD_REDO_INFORMATION = extern struct {
LastVirtualClock: LARGE_INTEGER,
LastRedoLsn: u64,
HighestRecoveryLsn: u64,
Flags: u32,
};
pub const TXFS_START_RM_INFORMATION = extern struct {
Flags: u32,
LogContainerSize: u64,
LogContainerCountMin: u32,
LogContainerCountMax: u32,
LogGrowthIncrement: u32,
LogAutoShrinkPercentage: u32,
TmLogPathOffset: u32,
TmLogPathLength: u16,
LoggingMode: u16,
LogPathLength: u16,
Reserved: u16,
LogPath: [1]u16,
};
pub const FILE_FS_PERSISTENT_VOLUME_INFORMATION = extern struct {
VolumeFlags: u32,
FlagMask: u32,
Version: u32,
Reserved: u32,
};
pub const STORAGE_QUERY_DEPENDENT_VOLUME_REQUEST = extern struct {
RequestLevel: u32,
RequestFlags: u32,
};
pub const STORAGE_QUERY_DEPENDENT_VOLUME_LEV1_ENTRY = extern struct {
EntryLength: u32,
DependencyTypeFlags: u32,
ProviderSpecificFlags: u32,
VirtualStorageType: VIRTUAL_STORAGE_TYPE,
};
pub const STORAGE_QUERY_DEPENDENT_VOLUME_LEV2_ENTRY = extern struct {
EntryLength: u32,
DependencyTypeFlags: u32,
ProviderSpecificFlags: u32,
VirtualStorageType: VIRTUAL_STORAGE_TYPE,
AncestorLevel: u32,
HostVolumeNameOffset: u32,
HostVolumeNameSize: u32,
DependentVolumeNameOffset: u32,
DependentVolumeNameSize: u32,
RelativePathOffset: u32,
RelativePathSize: u32,
DependentDeviceNameOffset: u32,
DependentDeviceNameSize: u32,
};
pub const STORAGE_QUERY_DEPENDENT_VOLUME_RESPONSE = extern struct {
ResponseLevel: u32,
NumberEntries: u32,
Anonymous: extern union {
Lev1Depends: [1]STORAGE_QUERY_DEPENDENT_VOLUME_LEV1_ENTRY,
Lev2Depends: [1]STORAGE_QUERY_DEPENDENT_VOLUME_LEV2_ENTRY,
},
};
pub const SD_CHANGE_MACHINE_SID_INPUT = extern struct {
CurrentMachineSIDOffset: u16,
CurrentMachineSIDLength: u16,
NewMachineSIDOffset: u16,
NewMachineSIDLength: u16,
};
pub const SD_CHANGE_MACHINE_SID_OUTPUT = extern struct {
NumSDChangedSuccess: u64,
NumSDChangedFail: u64,
NumSDUnused: u64,
NumSDTotal: u64,
NumMftSDChangedSuccess: u64,
NumMftSDChangedFail: u64,
NumMftSDTotal: u64,
};
pub const SD_QUERY_STATS_INPUT = extern struct {
Reserved: u32,
};
pub const SD_QUERY_STATS_OUTPUT = extern struct {
SdsStreamSize: u64,
SdsAllocationSize: u64,
SiiStreamSize: u64,
SiiAllocationSize: u64,
SdhStreamSize: u64,
SdhAllocationSize: u64,
NumSDTotal: u64,
NumSDUnused: u64,
};
pub const SD_ENUM_SDS_INPUT = extern struct {
StartingOffset: u64,
MaxSDEntriesToReturn: u64,
};
pub const SD_ENUM_SDS_ENTRY = extern struct {
Hash: u32,
SecurityId: u32,
Offset: u64,
Length: u32,
Descriptor: [1]u8,
};
pub const SD_ENUM_SDS_OUTPUT = extern struct {
NextOffset: u64,
NumSDEntriesReturned: u64,
NumSDBytesReturned: u64,
SDEntry: [1]SD_ENUM_SDS_ENTRY,
};
pub const SD_GLOBAL_CHANGE_INPUT = extern struct {
Flags: u32,
ChangeType: u32,
Anonymous: extern union {
SdChange: SD_CHANGE_MACHINE_SID_INPUT,
SdQueryStats: SD_QUERY_STATS_INPUT,
SdEnumSds: SD_ENUM_SDS_INPUT,
},
};
pub const SD_GLOBAL_CHANGE_OUTPUT = extern struct {
Flags: u32,
ChangeType: u32,
Anonymous: extern union {
SdChange: SD_CHANGE_MACHINE_SID_OUTPUT,
SdQueryStats: SD_QUERY_STATS_OUTPUT,
SdEnumSds: SD_ENUM_SDS_OUTPUT,
},
};
pub const FILE_TYPE_NOTIFICATION_INPUT = extern struct {
Flags: u32,
NumFileTypeIDs: u32,
FileTypeID: [1]Guid,
};
pub const CSV_MGMT_LOCK = extern struct {
Flags: u32,
};
pub const CSV_QUERY_FILE_REVISION_FILE_ID_128 = extern struct {
FileId: FILE_ID_128,
FileRevision: [3]i64,
};
pub const CSVFS_DISK_CONNECTIVITY = enum(i32) {
None = 0,
MdsNodeOnly = 1,
SubsetOfNodes = 2,
AllNodes = 3,
};
pub const CsvFsDiskConnectivityNone = CSVFS_DISK_CONNECTIVITY.None;
pub const CsvFsDiskConnectivityMdsNodeOnly = CSVFS_DISK_CONNECTIVITY.MdsNodeOnly;
pub const CsvFsDiskConnectivitySubsetOfNodes = CSVFS_DISK_CONNECTIVITY.SubsetOfNodes;
pub const CsvFsDiskConnectivityAllNodes = CSVFS_DISK_CONNECTIVITY.AllNodes;
pub const CSV_QUERY_VOLUME_REDIRECT_STATE = extern struct {
MdsNodeId: u32,
DsNodeId: u32,
IsDiskConnected: BOOLEAN,
ClusterEnableDirectIo: BOOLEAN,
DiskConnectivity: CSVFS_DISK_CONNECTIVITY,
};
pub const CSV_QUERY_MDS_PATH_V2 = extern struct {
Version: i64,
RequiredSize: u32,
MdsNodeId: u32,
DsNodeId: u32,
Flags: u32,
DiskConnectivity: CSVFS_DISK_CONNECTIVITY,
VolumeId: Guid,
IpAddressOffset: u32,
IpAddressLength: u32,
PathOffset: u32,
PathLength: u32,
};
pub const STORAGE_RESERVE_ID = enum(i32) {
None = 0,
Hard = 1,
Soft = 2,
UpdateScratch = 3,
Max = 4,
};
pub const StorageReserveIdNone = STORAGE_RESERVE_ID.None;
pub const StorageReserveIdHard = STORAGE_RESERVE_ID.Hard;
pub const StorageReserveIdSoft = STORAGE_RESERVE_ID.Soft;
pub const StorageReserveIdUpdateScratch = STORAGE_RESERVE_ID.UpdateScratch;
pub const StorageReserveIdMax = STORAGE_RESERVE_ID.Max;
pub const QUERY_FILE_LAYOUT_FILTER_TYPE = enum(i32) {
FILTER_TYPE_NONE = 0,
FILTER_TYPE_CLUSTERS = 1,
FILTER_TYPE_FILEID = 2,
FILTER_TYPE_STORAGE_RESERVE_ID = 3,
NUM_FILTER_TYPES = 4,
};
pub const QUERY_FILE_LAYOUT_FILTER_TYPE_NONE = QUERY_FILE_LAYOUT_FILTER_TYPE.FILTER_TYPE_NONE;
pub const QUERY_FILE_LAYOUT_FILTER_TYPE_CLUSTERS = QUERY_FILE_LAYOUT_FILTER_TYPE.FILTER_TYPE_CLUSTERS;
pub const QUERY_FILE_LAYOUT_FILTER_TYPE_FILEID = QUERY_FILE_LAYOUT_FILTER_TYPE.FILTER_TYPE_FILEID;
pub const QUERY_FILE_LAYOUT_FILTER_TYPE_STORAGE_RESERVE_ID = QUERY_FILE_LAYOUT_FILTER_TYPE.FILTER_TYPE_STORAGE_RESERVE_ID;
pub const QUERY_FILE_LAYOUT_NUM_FILTER_TYPES = QUERY_FILE_LAYOUT_FILTER_TYPE.NUM_FILTER_TYPES;
pub const CLUSTER_RANGE = extern struct {
StartingCluster: LARGE_INTEGER,
ClusterCount: LARGE_INTEGER,
};
pub const FILE_REFERENCE_RANGE = extern struct {
StartingFileReferenceNumber: u64,
EndingFileReferenceNumber: u64,
};
pub const QUERY_FILE_LAYOUT_INPUT = extern struct {
Anonymous: extern union {
FilterEntryCount: u32,
NumberOfPairs: u32,
},
Flags: u32,
FilterType: QUERY_FILE_LAYOUT_FILTER_TYPE,
Reserved: u32,
Filter: extern union {
ClusterRanges: [1]CLUSTER_RANGE,
FileReferenceRanges: [1]FILE_REFERENCE_RANGE,
StorageReserveIds: [1]STORAGE_RESERVE_ID,
},
};
pub const QUERY_FILE_LAYOUT_OUTPUT = extern struct {
FileEntryCount: u32,
FirstFileOffset: u32,
Flags: u32,
Reserved: u32,
};
pub const FILE_LAYOUT_ENTRY = extern struct {
Version: u32,
NextFileOffset: u32,
Flags: u32,
FileAttributes: u32,
FileReferenceNumber: u64,
FirstNameOffset: u32,
FirstStreamOffset: u32,
ExtraInfoOffset: u32,
ExtraInfoLength: u32,
};
pub const FILE_LAYOUT_NAME_ENTRY = extern struct {
NextNameOffset: u32,
Flags: u32,
ParentFileReferenceNumber: u64,
FileNameLength: u32,
Reserved: u32,
FileName: [1]u16,
};
pub const FILE_LAYOUT_INFO_ENTRY = extern struct {
BasicInformation: extern struct {
CreationTime: LARGE_INTEGER,
LastAccessTime: LARGE_INTEGER,
LastWriteTime: LARGE_INTEGER,
ChangeTime: LARGE_INTEGER,
FileAttributes: u32,
},
OwnerId: u32,
SecurityId: u32,
Usn: i64,
StorageReserveId: STORAGE_RESERVE_ID,
};
pub const STREAM_LAYOUT_ENTRY = extern struct {
Version: u32,
NextStreamOffset: u32,
Flags: u32,
ExtentInformationOffset: u32,
AllocationSize: LARGE_INTEGER,
EndOfFile: LARGE_INTEGER,
StreamInformationOffset: u32,
AttributeTypeCode: u32,
AttributeFlags: u32,
StreamIdentifierLength: u32,
StreamIdentifier: [1]u16,
};
pub const STREAM_EXTENT_ENTRY = extern struct {
Flags: u32,
ExtentInformation: extern union {
RetrievalPointers: RETRIEVAL_POINTERS_BUFFER,
},
};
pub const FSCTL_SET_INTEGRITY_INFORMATION_BUFFER_EX = extern struct {
EnableIntegrity: u8,
KeepIntegrityStateUnchanged: u8,
Reserved: u16,
Flags: u32,
Version: u8,
Reserved2: [7]u8,
};
pub const FSCTL_OFFLOAD_READ_INPUT = extern struct {
Size: u32,
Flags: u32,
TokenTimeToLive: u32,
Reserved: u32,
FileOffset: u64,
CopyLength: u64,
};
pub const FSCTL_OFFLOAD_READ_OUTPUT = extern struct {
Size: u32,
Flags: u32,
TransferLength: u64,
Token: [512]u8,
};
pub const FSCTL_OFFLOAD_WRITE_INPUT = extern struct {
Size: u32,
Flags: u32,
FileOffset: u64,
CopyLength: u64,
TransferOffset: u64,
Token: [512]u8,
};
pub const FSCTL_OFFLOAD_WRITE_OUTPUT = extern struct {
Size: u32,
Flags: u32,
LengthWritten: u64,
};
pub const SET_PURGE_FAILURE_MODE_INPUT = extern struct {
Flags: u32,
};
pub const FILE_REGION_INFO = extern struct {
FileOffset: i64,
Length: i64,
Usage: u32,
Reserved: u32,
};
pub const FILE_REGION_OUTPUT = extern struct {
Flags: u32,
TotalRegionEntryCount: u32,
RegionEntryCount: u32,
Reserved: u32,
Region: [1]FILE_REGION_INFO,
};
pub const FILE_REGION_INPUT = extern struct {
FileOffset: i64,
Length: i64,
DesiredUsage: u32,
};
pub const WRITE_USN_REASON_INPUT = extern struct {
Flags: u32,
UsnReasonToWrite: u32,
};
pub const FILE_STORAGE_TIER_CLASS = enum(i32) {
Unspecified = 0,
Capacity = 1,
Performance = 2,
Max = 3,
};
pub const FileStorageTierClassUnspecified = FILE_STORAGE_TIER_CLASS.Unspecified;
pub const FileStorageTierClassCapacity = FILE_STORAGE_TIER_CLASS.Capacity;
pub const FileStorageTierClassPerformance = FILE_STORAGE_TIER_CLASS.Performance;
pub const FileStorageTierClassMax = FILE_STORAGE_TIER_CLASS.Max;
pub const STREAM_INFORMATION_ENTRY = extern struct {
pub const _StreamInformation = extern union {
pub const _Reparse = extern struct {
Length: u16,
Flags: u16,
ReparseDataSize: u32,
ReparseDataOffset: u32,
};
pub const _DesiredStorageClass = extern struct {
Class: FILE_STORAGE_TIER_CLASS,
Flags: u32,
};
pub const _DataStream = extern struct {
Length: u16,
Flags: u16,
Reserved: u32,
Vdl: u64,
};
pub const _Ea = extern struct {
Length: u16,
Flags: u16,
EaSize: u32,
EaInformationOffset: u32,
};
DesiredStorageClass: _DesiredStorageClass,
DataStream: _DataStream,
Reparse: _Reparse,
Ea: _Ea,
};
Version: u32,
Flags: u32,
StreamInformation: _StreamInformation,
};
pub const FILE_DESIRED_STORAGE_CLASS_INFORMATION = extern struct {
Class: FILE_STORAGE_TIER_CLASS,
Flags: u32,
};
pub const DUPLICATE_EXTENTS_DATA_EX = extern struct {
Size: usize,
FileHandle: ?HANDLE,
SourceFileOffset: LARGE_INTEGER,
TargetFileOffset: LARGE_INTEGER,
ByteCount: LARGE_INTEGER,
Flags: u32,
};
pub const REFS_SMR_VOLUME_GC_STATE = enum(i32) {
Inactive = 0,
Paused = 1,
Active = 2,
ActiveFullSpeed = 3,
};
pub const SmrGcStateInactive = REFS_SMR_VOLUME_GC_STATE.Inactive;
pub const SmrGcStatePaused = REFS_SMR_VOLUME_GC_STATE.Paused;
pub const SmrGcStateActive = REFS_SMR_VOLUME_GC_STATE.Active;
pub const SmrGcStateActiveFullSpeed = REFS_SMR_VOLUME_GC_STATE.ActiveFullSpeed;
pub const REFS_SMR_VOLUME_INFO_OUTPUT = extern struct {
Version: u32,
Flags: u32,
SizeOfRandomlyWritableTier: LARGE_INTEGER,
FreeSpaceInRandomlyWritableTier: LARGE_INTEGER,
SizeofSMRTier: LARGE_INTEGER,
FreeSpaceInSMRTier: LARGE_INTEGER,
UsableFreeSpaceInSMRTier: LARGE_INTEGER,
VolumeGcState: REFS_SMR_VOLUME_GC_STATE,
VolumeGcLastStatus: u32,
Unused: [7]u64,
};
pub const REFS_SMR_VOLUME_GC_ACTION = enum(i32) {
Start = 1,
StartFullSpeed = 2,
Pause = 3,
Stop = 4,
};
pub const SmrGcActionStart = REFS_SMR_VOLUME_GC_ACTION.Start;
pub const SmrGcActionStartFullSpeed = REFS_SMR_VOLUME_GC_ACTION.StartFullSpeed;
pub const SmrGcActionPause = REFS_SMR_VOLUME_GC_ACTION.Pause;
pub const SmrGcActionStop = REFS_SMR_VOLUME_GC_ACTION.Stop;
pub const REFS_SMR_VOLUME_GC_METHOD = enum(i32) {
Compaction = 1,
Compression = 2,
Rotation = 3,
};
pub const SmrGcMethodCompaction = REFS_SMR_VOLUME_GC_METHOD.Compaction;
pub const SmrGcMethodCompression = REFS_SMR_VOLUME_GC_METHOD.Compression;
pub const SmrGcMethodRotation = REFS_SMR_VOLUME_GC_METHOD.Rotation;
pub const REFS_SMR_VOLUME_GC_PARAMETERS = extern struct {
Version: u32,
Flags: u32,
Action: REFS_SMR_VOLUME_GC_ACTION,
Method: REFS_SMR_VOLUME_GC_METHOD,
IoGranularity: u32,
CompressionFormat: u32,
Unused: [8]u64,
};
pub const STREAMS_QUERY_PARAMETERS_OUTPUT_BUFFER = extern struct {
OptimalWriteSize: u32,
StreamGranularitySize: u32,
StreamIdMin: u32,
StreamIdMax: u32,
};
pub const STREAMS_ASSOCIATE_ID_INPUT_BUFFER = extern struct {
Flags: u32,
StreamId: u32,
};
pub const STREAMS_QUERY_ID_OUTPUT_BUFFER = extern struct {
StreamId: u32,
};
pub const QUERY_BAD_RANGES_INPUT_RANGE = extern struct {
StartOffset: u64,
LengthInBytes: u64,
};
pub const QUERY_BAD_RANGES_INPUT = extern struct {
Flags: u32,
NumRanges: u32,
Ranges: [1]QUERY_BAD_RANGES_INPUT_RANGE,
};
pub const QUERY_BAD_RANGES_OUTPUT_RANGE = extern struct {
Flags: u32,
Reserved: u32,
StartOffset: u64,
LengthInBytes: u64,
};
pub const QUERY_BAD_RANGES_OUTPUT = extern struct {
Flags: u32,
NumBadRanges: u32,
NextOffsetToLookUp: u64,
BadRanges: [1]QUERY_BAD_RANGES_OUTPUT_RANGE,
};
pub const SET_DAX_ALLOC_ALIGNMENT_HINT_INPUT = extern struct {
Flags: u32,
AlignmentShift: u32,
FileOffsetToAlign: u64,
FallbackAlignmentShift: u32,
};
pub const VIRTUAL_STORAGE_BEHAVIOR_CODE = enum(i32) {
Undefined = 0,
CacheWriteThrough = 1,
CacheWriteBack = 2,
};
pub const VirtualStorageBehaviorUndefined = VIRTUAL_STORAGE_BEHAVIOR_CODE.Undefined;
pub const VirtualStorageBehaviorCacheWriteThrough = VIRTUAL_STORAGE_BEHAVIOR_CODE.CacheWriteThrough;
pub const VirtualStorageBehaviorCacheWriteBack = VIRTUAL_STORAGE_BEHAVIOR_CODE.CacheWriteBack;
pub const VIRTUAL_STORAGE_SET_BEHAVIOR_INPUT = extern struct {
Size: u32,
BehaviorCode: VIRTUAL_STORAGE_BEHAVIOR_CODE,
};
pub const ENCRYPTION_KEY_CTRL_INPUT = extern struct {
HeaderSize: u32,
StructureSize: u32,
KeyOffset: u16,
KeySize: u16,
DplLock: u32,
DplUserId: u64,
DplCredentialId: u64,
};
pub const WOF_EXTERNAL_INFO = extern struct {
Version: u32,
Provider: u32,
};
pub const WOF_EXTERNAL_FILE_ID = extern struct {
FileId: FILE_ID_128,
};
pub const WOF_VERSION_INFO = extern struct {
WofVersion: u32,
};
pub const WIM_PROVIDER_EXTERNAL_INFO = extern struct {
Version: u32,
Flags: u32,
DataSourceId: LARGE_INTEGER,
ResourceHash: [20]u8,
};
pub const WIM_PROVIDER_ADD_OVERLAY_INPUT = extern struct {
WimType: u32,
WimIndex: u32,
WimFileNameOffset: u32,
WimFileNameLength: u32,
};
pub const WIM_PROVIDER_UPDATE_OVERLAY_INPUT = extern struct {
DataSourceId: LARGE_INTEGER,
WimFileNameOffset: u32,
WimFileNameLength: u32,
};
pub const WIM_PROVIDER_REMOVE_OVERLAY_INPUT = extern struct {
DataSourceId: LARGE_INTEGER,
};
pub const WIM_PROVIDER_SUSPEND_OVERLAY_INPUT = extern struct {
DataSourceId: LARGE_INTEGER,
};
pub const WIM_PROVIDER_OVERLAY_ENTRY = extern struct {
NextEntryOffset: u32,
DataSourceId: LARGE_INTEGER,
WimGuid: Guid,
WimFileNameOffset: u32,
WimType: u32,
WimIndex: u32,
Flags: u32,
};
pub const FILE_PROVIDER_EXTERNAL_INFO_V0 = extern struct {
Version: u32,
Algorithm: u32,
};
pub const FILE_PROVIDER_EXTERNAL_INFO_V1 = extern struct {
Version: u32,
Algorithm: u32,
Flags: u32,
};
pub const CONTAINER_VOLUME_STATE = extern struct {
Flags: u32,
};
pub const CONTAINER_ROOT_INFO_INPUT = extern struct {
Flags: u32,
};
pub const CONTAINER_ROOT_INFO_OUTPUT = extern struct {
ContainerRootIdLength: u16,
ContainerRootId: [1]u8,
};
pub const VIRTUALIZATION_INSTANCE_INFO_INPUT = extern struct {
NumberOfWorkerThreads: u32,
Flags: u32,
};
pub const VIRTUALIZATION_INSTANCE_INFO_INPUT_EX = extern struct {
HeaderSize: u16,
Flags: u32,
NotificationInfoSize: u32,
NotificationInfoOffset: u16,
ProviderMajorVersion: u16,
};
pub const VIRTUALIZATION_INSTANCE_INFO_OUTPUT = extern struct {
VirtualizationInstanceID: Guid,
};
pub const GET_FILTER_FILE_IDENTIFIER_INPUT = extern struct {
AltitudeLength: u16,
Altitude: [1]u16,
};
pub const GET_FILTER_FILE_IDENTIFIER_OUTPUT = extern struct {
FilterFileIdentifierLength: u16,
FilterFileIdentifier: [1]u8,
};
pub const PIO_IRP_EXT_PROCESS_TRACKED_OFFSET_CALLBACK = fn(
SourceContext: ?*IO_IRP_EXT_TRACK_OFFSET_HEADER,
TargetContext: ?*IO_IRP_EXT_TRACK_OFFSET_HEADER,
RelativeOffset: i64,
) callconv(@import("std").os.windows.WINAPI) void;
pub const IO_IRP_EXT_TRACK_OFFSET_HEADER = extern struct {
Validation: u16,
Flags: u16,
TrackedOffsetCallback: ?PIO_IRP_EXT_PROCESS_TRACKED_OFFSET_CALLBACK,
};
pub const DEVICE_EVENT_MOUNT = extern struct {
Version: u32,
Flags: u32,
FileSystemNameLength: u32,
FileSystemNameOffset: u32,
};
pub const DEVICE_EVENT_BECOMING_READY = extern struct {
Version: u32,
Reason: u32,
Estimated100msToReady: u32,
};
pub const DEVICE_EVENT_EXTERNAL_REQUEST = extern struct {
Version: u32,
DeviceClass: u32,
ButtonStatus: u16,
Request: u16,
SystemTime: LARGE_INTEGER,
};
pub const DEVICE_EVENT_GENERIC_DATA = extern struct {
EventNumber: u32,
};
pub const DEVICE_EVENT_RBC_DATA = extern struct {
EventNumber: u32,
SenseQualifier: u8,
SenseCode: u8,
SenseKey: u8,
Reserved: u8,
Information: u32,
};
pub const GUID_IO_DISK_CLONE_ARRIVAL_INFORMATION = extern struct {
DiskNumber: u32,
};
pub const DISK_HEALTH_NOTIFICATION_DATA = extern struct {
DeviceGuid: Guid,
};
pub const DEVPROPKEY = extern struct {
fmtid: Guid,
pid: u32,
};
pub const DEVPROPSTORE = enum(i32) {
SYSTEM = 0,
USER = 1,
};
pub const DEVPROP_STORE_SYSTEM = DEVPROPSTORE.SYSTEM;
pub const DEVPROP_STORE_USER = DEVPROPSTORE.USER;
pub const DEVPROPCOMPKEY = extern struct {
Key: DEVPROPKEY,
Store: DEVPROPSTORE,
LocaleName: ?[*:0]const u16,
};
pub const DEVPROPERTY = extern struct {
CompKey: DEVPROPCOMPKEY,
Type: u32,
BufferSize: u32,
Buffer: ?*c_void,
};
pub const REDBOOK_DIGITAL_AUDIO_EXTRACTION_INFO = extern struct {
Version: u32,
Accurate: u32,
Supported: u32,
AccurateMask0: u32,
};
pub const DEV_BROADCAST_HDR = extern struct {
dbch_size: u32,
dbch_devicetype: DEV_BROADCAST_HDR_DEVICE_TYPE,
dbch_reserved: u32,
};
pub const VolLockBroadcast = extern struct {
vlb_dbh: DEV_BROADCAST_HDR,
vlb_owner: u32,
vlb_perms: u8,
vlb_lockType: u8,
vlb_drive: u8,
vlb_flags: u8,
};
pub const _DEV_BROADCAST_HEADER = extern struct {
dbcd_size: u32,
dbcd_devicetype: u32,
dbcd_reserved: u32,
};
pub const DEV_BROADCAST_OEM = extern struct {
dbco_size: u32,
dbco_devicetype: u32,
dbco_reserved: u32,
dbco_identifier: u32,
dbco_suppfunc: u32,
};
pub const DEV_BROADCAST_DEVNODE = extern struct {
dbcd_size: u32,
dbcd_devicetype: u32,
dbcd_reserved: u32,
dbcd_devnode: u32,
};
pub const DEV_BROADCAST_VOLUME = extern struct {
dbcv_size: u32,
dbcv_devicetype: u32,
dbcv_reserved: u32,
dbcv_unitmask: u32,
dbcv_flags: DEV_BROADCAST_VOLUME_FLAGS,
};
pub const DEV_BROADCAST_PORT_A = extern struct {
dbcp_size: u32,
dbcp_devicetype: u32,
dbcp_reserved: u32,
dbcp_name: [1]CHAR,
};
pub const DEV_BROADCAST_PORT_W = extern struct {
dbcp_size: u32,
dbcp_devicetype: u32,
dbcp_reserved: u32,
dbcp_name: [1]u16,
};
pub const DEV_BROADCAST_NET = extern struct {
dbcn_size: u32,
dbcn_devicetype: u32,
dbcn_reserved: u32,
dbcn_resource: u32,
dbcn_flags: u32,
};
pub const DEV_BROADCAST_DEVICEINTERFACE_A = extern struct {
dbcc_size: u32,
dbcc_devicetype: u32,
dbcc_reserved: u32,
dbcc_classguid: Guid,
dbcc_name: [1]CHAR,
};
pub const DEV_BROADCAST_DEVICEINTERFACE_W = extern struct {
dbcc_size: u32,
dbcc_devicetype: u32,
dbcc_reserved: u32,
dbcc_classguid: Guid,
dbcc_name: [1]u16,
};
pub const DEV_BROADCAST_HANDLE = extern struct {
dbch_size: u32,
dbch_devicetype: u32,
dbch_reserved: u32,
dbch_handle: ?HANDLE,
dbch_hdevnotify: ?*c_void,
dbch_eventguid: Guid,
dbch_nameoffset: i32,
dbch_data: [1]u8,
};
pub const DEV_BROADCAST_HANDLE32 = extern struct {
dbch_size: u32,
dbch_devicetype: u32,
dbch_reserved: u32,
dbch_handle: u32,
dbch_hdevnotify: u32,
dbch_eventguid: Guid,
dbch_nameoffset: i32,
dbch_data: [1]u8,
};
pub const DEV_BROADCAST_HANDLE64 = extern struct {
dbch_size: u32,
dbch_devicetype: u32,
dbch_reserved: u32,
dbch_handle: u64,
dbch_hdevnotify: u64,
dbch_eventguid: Guid,
dbch_nameoffset: i32,
dbch_data: [1]u8,
};
pub const _DEV_BROADCAST_USERDEFINED = extern struct {
dbud_dbh: DEV_BROADCAST_HDR,
dbud_szName: [1]CHAR,
};
pub const XSAVE_FORMAT = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
ControlWord: u16,
StatusWord: u16,
TagWord: u8,
Reserved1: u8,
ErrorOpcode: u16,
ErrorOffset: u32,
ErrorSelector: u16,
Reserved2: u16,
DataOffset: u32,
DataSelector: u16,
Reserved3: u16,
MxCsr: u32,
MxCsr_Mask: u32,
FloatRegisters: [8]M128A,
XmmRegisters: [16]M128A,
Reserved4: [96]u8,
},
.X86 => extern struct {
ControlWord: u16,
StatusWord: u16,
TagWord: u8,
Reserved1: u8,
ErrorOpcode: u16,
ErrorOffset: u32,
ErrorSelector: u16,
Reserved2: u16,
DataOffset: u32,
DataSelector: u16,
Reserved3: u16,
MxCsr: u32,
MxCsr_Mask: u32,
FloatRegisters: [8]M128A,
XmmRegisters: [8]M128A,
Reserved4: [224]u8,
},
};
pub const XSTATE_CONTEXT = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
Mask: u64,
Length: u32,
Reserved1: u32,
Area: ?*XSAVE_AREA,
Buffer: ?*c_void,
},
.X86 => extern struct {
Mask: u64,
Length: u32,
Reserved1: u32,
Area: ?*XSAVE_AREA,
Reserved2: u32,
Buffer: ?*c_void,
Reserved3: u32,
},
};
pub const ARM64_NT_NEON128 = switch(@import("../zig.zig").arch) {
.Arm64 => extern union {
Anonymous: extern struct {
Low: u64,
High: i64,
},
D: [2]f64,
S: [4]f32,
H: [8]u16,
B: [16]u8,
},
else => usize, // NOTE: this should be a @compileError but can't because of https://github.com/ziglang/zig/issues/9682
};
pub const UNWIND_HISTORY_TABLE_ENTRY = switch(@import("../zig.zig").arch) {
.Arm64 => extern struct {
ImageBase: u64,
FunctionEntry: ?*IMAGE_ARM64_RUNTIME_FUNCTION_ENTRY,
},
.X64 => extern struct {
ImageBase: u64,
FunctionEntry: ?*IMAGE_RUNTIME_FUNCTION_ENTRY,
},
else => usize, // NOTE: this should be a @compileError but can't because of https://github.com/ziglang/zig/issues/9682
};
pub const UNWIND_HISTORY_TABLE = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
Count: u32,
LocalHint: u8,
GlobalHint: u8,
Search: u8,
Once: u8,
LowAddress: u64,
HighAddress: u64,
Entry: [12]UNWIND_HISTORY_TABLE_ENTRY,
},
else => usize, // NOTE: this should be a @compileError but can't because of https://github.com/ziglang/zig/issues/9682
};
pub const DISPATCHER_CONTEXT = switch(@import("../zig.zig").arch) {
.Arm64 => extern struct {
ControlPc: usize,
ImageBase: usize,
FunctionEntry: ?*IMAGE_ARM64_RUNTIME_FUNCTION_ENTRY,
EstablisherFrame: usize,
TargetPc: usize,
ContextRecord: ?*CONTEXT,
LanguageHandler: ?EXCEPTION_ROUTINE,
HandlerData: ?*c_void,
HistoryTable: ?*UNWIND_HISTORY_TABLE,
ScopeIndex: u32,
ControlPcIsUnwound: BOOLEAN,
NonVolatileRegisters: ?*u8,
},
.X64 => extern struct {
ControlPc: u64,
ImageBase: u64,
FunctionEntry: ?*IMAGE_RUNTIME_FUNCTION_ENTRY,
EstablisherFrame: u64,
TargetIp: u64,
ContextRecord: ?*CONTEXT,
LanguageHandler: ?EXCEPTION_ROUTINE,
HandlerData: ?*c_void,
HistoryTable: ?*UNWIND_HISTORY_TABLE,
ScopeIndex: u32,
Fill0: u32,
},
else => usize, // NOTE: this should be a @compileError but can't because of https://github.com/ziglang/zig/issues/9682
};
pub const PEXCEPTION_FILTER = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => fn(
ExceptionPointers: ?*EXCEPTION_POINTERS,
EstablisherFrame: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) i32,
else => usize, // NOTE: this should be a @compileError but can't because of https://github.com/ziglang/zig/issues/9682
};
pub const PTERMINATION_HANDLER = switch(@import("../zig.zig").arch) {
.Arm64 => fn(
_abnormal_termination: BOOLEAN,
EstablisherFrame: u64,
) callconv(@import("std").os.windows.WINAPI) void,
.X64 => fn(
_abnormal_termination: BOOLEAN,
EstablisherFrame: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void,
else => usize, // NOTE: this should be a @compileError but can't because of https://github.com/ziglang/zig/issues/9682
};
pub const PGET_RUNTIME_FUNCTION_CALLBACK = switch(@import("../zig.zig").arch) {
.Arm64 => fn(
ControlPc: u64,
Context: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) ?*IMAGE_ARM64_RUNTIME_FUNCTION_ENTRY,
.X64 => fn(
ControlPc: u64,
Context: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) ?*IMAGE_RUNTIME_FUNCTION_ENTRY,
else => usize, // NOTE: this should be a @compileError but can't because of https://github.com/ziglang/zig/issues/9682
};
pub const POUT_OF_PROCESS_FUNCTION_TABLE_CALLBACK = switch(@import("../zig.zig").arch) {
.Arm64 => fn(
Process: ?HANDLE,
TableAddress: ?*c_void,
Entries: ?*u32,
Functions: ?*?*IMAGE_ARM64_RUNTIME_FUNCTION_ENTRY,
) callconv(@import("std").os.windows.WINAPI) u32,
.X64 => fn(
Process: ?HANDLE,
TableAddress: ?*c_void,
Entries: ?*u32,
Functions: ?*?*IMAGE_RUNTIME_FUNCTION_ENTRY,
) callconv(@import("std").os.windows.WINAPI) u32,
else => usize, // NOTE: this should be a @compileError but can't because of https://github.com/ziglang/zig/issues/9682
};
pub const KNONVOLATILE_CONTEXT_POINTERS = switch(@import("../zig.zig").arch) {
.Arm64 => extern struct {
X19: ?*u64,
X20: ?*u64,
X21: ?*u64,
X22: ?*u64,
X23: ?*u64,
X24: ?*u64,
X25: ?*u64,
X26: ?*u64,
X27: ?*u64,
X28: ?*u64,
Fp: ?*u64,
Lr: ?*u64,
D8: ?*u64,
D9: ?*u64,
D10: ?*u64,
D11: ?*u64,
D12: ?*u64,
D13: ?*u64,
D14: ?*u64,
D15: ?*u64,
},
.X64 => extern struct {
Anonymous1: extern union {
FloatingContext: [16]?*M128A,
Anonymous: extern struct {
Xmm0: ?*M128A,
Xmm1: ?*M128A,
Xmm2: ?*M128A,
Xmm3: ?*M128A,
Xmm4: ?*M128A,
Xmm5: ?*M128A,
Xmm6: ?*M128A,
Xmm7: ?*M128A,
Xmm8: ?*M128A,
Xmm9: ?*M128A,
Xmm10: ?*M128A,
Xmm11: ?*M128A,
Xmm12: ?*M128A,
Xmm13: ?*M128A,
Xmm14: ?*M128A,
Xmm15: ?*M128A,
},
},
Anonymous2: extern union {
IntegerContext: [16]?*u64,
Anonymous: extern struct {
Rax: ?*u64,
Rcx: ?*u64,
Rdx: ?*u64,
Rbx: ?*u64,
Rsp: ?*u64,
Rbp: ?*u64,
Rsi: ?*u64,
Rdi: ?*u64,
R8: ?*u64,
R9: ?*u64,
R10: ?*u64,
R11: ?*u64,
R12: ?*u64,
R13: ?*u64,
R14: ?*u64,
R15: ?*u64,
},
},
},
.X86 => extern struct {
Dummy: u32,
},
};
pub const REARRANGE_FILE_DATA32 = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
SourceStartingOffset: u64,
TargetOffset: u64,
SourceFileHandle: u32,
Length: u32,
Flags: u32,
},
else => usize, // NOTE: this should be a @compileError but can't because of https://github.com/ziglang/zig/issues/9682
};
pub const MOVE_FILE_DATA32 = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
FileHandle: u32,
StartingVcn: LARGE_INTEGER,
StartingLcn: LARGE_INTEGER,
ClusterCount: u32,
},
else => usize, // NOTE: this should be a @compileError but can't because of https://github.com/ziglang/zig/issues/9682
};
pub const DUPLICATE_EXTENTS_DATA32 = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
FileHandle: u32,
SourceFileOffset: LARGE_INTEGER,
TargetFileOffset: LARGE_INTEGER,
ByteCount: LARGE_INTEGER,
},
else => usize, // NOTE: this should be a @compileError but can't because of https://github.com/ziglang/zig/issues/9682
};
pub const DUPLICATE_EXTENTS_DATA_EX32 = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
Size: u32,
FileHandle: u32,
SourceFileOffset: LARGE_INTEGER,
TargetFileOffset: LARGE_INTEGER,
ByteCount: LARGE_INTEGER,
Flags: u32,
},
else => usize, // NOTE: this should be a @compileError but can't because of https://github.com/ziglang/zig/issues/9682
};
//--------------------------------------------------------------------------------
// Section: Functions (45)
//--------------------------------------------------------------------------------
pub usingnamespace switch (@import("../zig.zig").arch) {
.X64, .Arm64 => struct {
pub extern "ntdll" fn RtlGetNonVolatileToken(
// TODO: what to do with BytesParamIndex 1?
NvBuffer: ?*c_void,
Size: usize,
NvToken: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) u32;
}, else => struct { } };
pub usingnamespace switch (@import("../zig.zig").arch) {
.X64, .Arm64 => struct {
pub extern "ntdll" fn RtlFreeNonVolatileToken(
NvToken: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) u32;
}, else => struct { } };
pub usingnamespace switch (@import("../zig.zig").arch) {
.X64, .Arm64 => struct {
pub extern "ntdll" fn RtlFlushNonVolatileMemory(
NvToken: ?*c_void,
// TODO: what to do with BytesParamIndex 2?
NvBuffer: ?*c_void,
Size: usize,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
}, else => struct { } };
pub usingnamespace switch (@import("../zig.zig").arch) {
.X64, .Arm64 => struct {
pub extern "ntdll" fn RtlDrainNonVolatileFlush(
NvToken: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) u32;
}, else => struct { } };
pub usingnamespace switch (@import("../zig.zig").arch) {
.X64, .Arm64 => struct {
pub extern "ntdll" fn RtlWriteNonVolatileMemory(
NvToken: ?*c_void,
// TODO: what to do with BytesParamIndex 3?
NvDestination: ?*c_void,
// TODO: what to do with BytesParamIndex 3?
Source: ?*const c_void,
Size: usize,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
}, else => struct { } };
pub usingnamespace switch (@import("../zig.zig").arch) {
.X64, .Arm64 => struct {
pub extern "ntdll" fn RtlFillNonVolatileMemory(
NvToken: ?*c_void,
// TODO: what to do with BytesParamIndex 2?
NvDestination: ?*c_void,
Size: usize,
Value: u8,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
}, else => struct { } };
pub usingnamespace switch (@import("../zig.zig").arch) {
.X64, .Arm64 => struct {
pub extern "ntdll" fn RtlFlushNonVolatileMemoryRanges(
NvToken: ?*c_void,
NvRanges: [*]NV_MEMORY_RANGE,
NumRanges: usize,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
}, else => struct { } };
pub extern "KERNEL32" fn RtlRaiseException(
ExceptionRecord: ?*EXCEPTION_RECORD,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "KERNEL32" fn RtlCompareMemory(
Source1: ?*const c_void,
Source2: ?*const c_void,
Length: usize,
) callconv(@import("std").os.windows.WINAPI) usize;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ntdll" fn RtlInitializeSListHead(
ListHead: ?*SLIST_HEADER,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ntdll" fn RtlFirstEntrySList(
ListHead: ?*const SLIST_HEADER,
) callconv(@import("std").os.windows.WINAPI) ?*SLIST_ENTRY;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ntdll" fn RtlInterlockedPopEntrySList(
ListHead: ?*SLIST_HEADER,
) callconv(@import("std").os.windows.WINAPI) ?*SLIST_ENTRY;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ntdll" fn RtlInterlockedPushEntrySList(
ListHead: ?*SLIST_HEADER,
ListEntry: ?*SLIST_ENTRY,
) callconv(@import("std").os.windows.WINAPI) ?*SLIST_ENTRY;
pub extern "ntdll" fn RtlInterlockedPushListSListEx(
ListHead: ?*SLIST_HEADER,
List: ?*SLIST_ENTRY,
ListEnd: ?*SLIST_ENTRY,
Count: u32,
) callconv(@import("std").os.windows.WINAPI) ?*SLIST_ENTRY;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ntdll" fn RtlInterlockedFlushSList(
ListHead: ?*SLIST_HEADER,
) callconv(@import("std").os.windows.WINAPI) ?*SLIST_ENTRY;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ntdll" fn RtlQueryDepthSList(
ListHead: ?*SLIST_HEADER,
) callconv(@import("std").os.windows.WINAPI) u16;
pub extern "ntdll" fn RtlGetReturnAddressHijackTarget(
) callconv(@import("std").os.windows.WINAPI) usize;
pub extern "ntdll" fn RtlGetProductInfo(
OSMajorVersion: u32,
OSMinorVersion: u32,
SpMajorVersion: u32,
SpMinorVersion: u32,
ReturnedProductType: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOLEAN;
pub extern "ntdll" fn RtlCrc32(
// TODO: what to do with BytesParamIndex 1?
Buffer: ?*const c_void,
Size: usize,
InitialCrc: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "ntdll" fn RtlCrc64(
// TODO: what to do with BytesParamIndex 1?
Buffer: ?*const c_void,
Size: usize,
InitialCrc: u64,
) callconv(@import("std").os.windows.WINAPI) u64;
pub extern "ntdll" fn RtlOsDeploymentState(
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) OS_DEPLOYEMENT_STATE_VALUES;
pub extern "ntdll" fn RtlInitializeCorrelationVector(
CorrelationVector: ?*CORRELATION_VECTOR,
Version: i32,
Guid: ?*const Guid,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "ntdll" fn RtlIncrementCorrelationVector(
CorrelationVector: ?*CORRELATION_VECTOR,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "ntdll" fn RtlExtendCorrelationVector(
CorrelationVector: ?*CORRELATION_VECTOR,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "ntdll" fn RtlValidateCorrelationVector(
Vector: ?*CORRELATION_VECTOR,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "ntdll" fn RtlRaiseCustomSystemEventTrigger(
TriggerConfig: ?*CUSTOM_SYSTEM_EVENT_TRIGGER_CONFIG,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "ntdll" fn RtlIsZeroMemory(
Buffer: ?*c_void,
Length: usize,
) callconv(@import("std").os.windows.WINAPI) BOOLEAN;
pub extern "ntdll" fn RtlNormalizeSecurityDescriptor(
SecurityDescriptor: ?*?*SECURITY_DESCRIPTOR,
SecurityDescriptorLength: u32,
NewSecurityDescriptor: ?*?*SECURITY_DESCRIPTOR,
NewSecurityDescriptorLength: ?*u32,
CheckOnly: BOOLEAN,
) callconv(@import("std").os.windows.WINAPI) BOOLEAN;
pub extern "ntdll" fn RtlGetDeviceFamilyInfoEnum(
pullUAPInfo: ?*u64,
pulDeviceFamily: ?*u32,
pulDeviceForm: ?*u32,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "ntdll" fn RtlConvertDeviceFamilyInfoToString(
pulDeviceFamilyBufferSize: ?*u32,
pulDeviceFormBufferSize: ?*u32,
// TODO: what to do with BytesParamIndex 0?
DeviceFamily: ?PWSTR,
// TODO: what to do with BytesParamIndex 1?
DeviceForm: ?PWSTR,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "ntdll" fn RtlSwitchedVVI(
VersionInfo: ?*OSVERSIONINFOEXW,
TypeMask: u32,
ConditionMask: u64,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "RPCNS4" fn I_RpcNsGetBuffer(
Message: ?*RPC_MESSAGE,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCNS4" fn I_RpcNsSendReceive(
Message: ?*RPC_MESSAGE,
Handle: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCNS4" fn I_RpcNsRaiseException(
Message: ?*RPC_MESSAGE,
Status: RPC_STATUS,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCNS4" fn I_RpcReBindBuffer(
Message: ?*RPC_MESSAGE,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "WINMM" fn timeSetEvent(
uDelay: u32,
uResolution: u32,
fptc: ?LPTIMECALLBACK,
dwUser: usize,
fuEvent: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "WINMM" fn timeKillEvent(
uTimerID: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "GDI32" fn EngQueryEMFInfo(
hdev: ?HDEV,
pEMFInfo: ?*EMFINFO,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn DeviceIoControl(
hDevice: ?HANDLE,
dwIoControlCode: u32,
// TODO: what to do with BytesParamIndex 3?
lpInBuffer: ?*c_void,
nInBufferSize: u32,
// TODO: what to do with BytesParamIndex 5?
lpOutBuffer: ?*c_void,
nOutBufferSize: u32,
lpBytesReturned: ?*u32,
lpOverlapped: ?*OVERLAPPED,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn GetOverlappedResult(
hFile: ?HANDLE,
lpOverlapped: ?*OVERLAPPED,
lpNumberOfBytesTransferred: ?*u32,
bWait: BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows8.0'
pub extern "KERNEL32" fn GetOverlappedResultEx(
hFile: ?HANDLE,
lpOverlapped: ?*OVERLAPPED,
lpNumberOfBytesTransferred: ?*u32,
dwMilliseconds: u32,
bAlertable: BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "USER32" fn RegisterDeviceNotificationA(
hRecipient: ?HANDLE,
NotificationFilter: ?*c_void,
Flags: POWER_SETTING_REGISTER_NOTIFICATION_FLAGS,
) callconv(@import("std").os.windows.WINAPI) ?*c_void;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "USER32" fn RegisterDeviceNotificationW(
hRecipient: ?HANDLE,
NotificationFilter: ?*c_void,
Flags: POWER_SETTING_REGISTER_NOTIFICATION_FLAGS,
) callconv(@import("std").os.windows.WINAPI) ?*c_void;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "USER32" fn UnregisterDeviceNotification(
Handle: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn BindIoCompletionCallback(
FileHandle: ?HANDLE,
Function: ?LPOVERLAPPED_COMPLETION_ROUTINE,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (3)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../zig.zig").unicode_mode) {
.ansi => struct {
pub const DEV_BROADCAST_PORT_ = thismodule.DEV_BROADCAST_PORT_A;
pub const DEV_BROADCAST_DEVICEINTERFACE_ = thismodule.DEV_BROADCAST_DEVICEINTERFACE_A;
pub const RegisterDeviceNotification = thismodule.RegisterDeviceNotificationA;
},
.wide => struct {
pub const DEV_BROADCAST_PORT_ = thismodule.DEV_BROADCAST_PORT_W;
pub const DEV_BROADCAST_DEVICEINTERFACE_ = thismodule.DEV_BROADCAST_DEVICEINTERFACE_W;
pub const RegisterDeviceNotification = thismodule.RegisterDeviceNotificationW;
},
.unspecified => if (@import("builtin").is_test) struct {
pub const DEV_BROADCAST_PORT_ = *opaque{};
pub const DEV_BROADCAST_DEVICEINTERFACE_ = *opaque{};
pub const RegisterDeviceNotification = *opaque{};
} else struct {
pub const DEV_BROADCAST_PORT_ = @compileError("'DEV_BROADCAST_PORT_' requires that UNICODE be set to true or false in the root module");
pub const DEV_BROADCAST_DEVICEINTERFACE_ = @compileError("'DEV_BROADCAST_DEVICEINTERFACE_' requires that UNICODE be set to true or false in the root module");
pub const RegisterDeviceNotification = @compileError("'RegisterDeviceNotification' requires that UNICODE be set to true or false in the root module");
},
};
//--------------------------------------------------------------------------------
// Section: Imports (114)
//--------------------------------------------------------------------------------
const Guid = @import("../zig.zig").Guid;
const ACE_HEADER = @import("../security.zig").ACE_HEADER;
const BLENDOBJ = @import("../ui/display_devices.zig").BLENDOBJ;
const BOOL = @import("../foundation.zig").BOOL;
const BOOLEAN = @import("../foundation.zig").BOOLEAN;
const BRUSHOBJ = @import("../ui/display_devices.zig").BRUSHOBJ;
const BYTE_BLOB = @import("../system/com.zig").BYTE_BLOB;
const CLIPOBJ = @import("../ui/display_devices.zig").CLIPOBJ;
const COLORADJUSTMENT = @import("../graphics/gdi.zig").COLORADJUSTMENT;
const D3DCOLORVALUE = @import("../graphics/direct3d9.zig").D3DCOLORVALUE;
const D3DLIGHTTYPE = @import("../graphics/direct3d9.zig").D3DLIGHTTYPE;
const D3DMATRIX = @import("../graphics/direct3d9.zig").D3DMATRIX;
const D3DRECT = @import("../graphics/direct3d9.zig").D3DRECT;
const D3DRENDERSTATETYPE = @import("../graphics/direct3d9.zig").D3DRENDERSTATETYPE;
const D3DSTATEBLOCKTYPE = @import("../graphics/direct3d9.zig").D3DSTATEBLOCKTYPE;
const D3DTRANSFORMSTATETYPE = @import("../graphics/direct3d9.zig").D3DTRANSFORMSTATETYPE;
const D3DVECTOR = @import("../graphics/direct3d9.zig").D3DVECTOR;
const DD_CALLBACKS = @import("../ui/display_devices.zig").DD_CALLBACKS;
const DD_DIRECTDRAW_GLOBAL = @import("../ui/display_devices.zig").DD_DIRECTDRAW_GLOBAL;
const DD_DIRECTDRAW_LOCAL = @import("../ui/display_devices.zig").DD_DIRECTDRAW_LOCAL;
const DD_HALINFO = @import("../ui/display_devices.zig").DD_HALINFO;
const DD_PALETTECALLBACKS = @import("../ui/display_devices.zig").DD_PALETTECALLBACKS;
const DD_SURFACE_LOCAL = @import("../ui/display_devices.zig").DD_SURFACE_LOCAL;
const DD_SURFACECALLBACKS = @import("../ui/display_devices.zig").DD_SURFACECALLBACKS;
const DDPIXELFORMAT = @import("../graphics/direct_draw.zig").DDPIXELFORMAT;
const DDSURFACEDESC = @import("../graphics/direct_draw.zig").DDSURFACEDESC;
const DESIGNVECTOR = @import("../graphics/gdi.zig").DESIGNVECTOR;
const DEVINFO = @import("../ui/display_devices.zig").DEVINFO;
const DEVMODEW = @import("../ui/display_devices.zig").DEVMODEW;
const DRVENABLEDATA = @import("../ui/display_devices.zig").DRVENABLEDATA;
const DWORD_BLOB = @import("../system/com.zig").DWORD_BLOB;
const ERASE_TAPE_TYPE = @import("../storage/file_system.zig").ERASE_TAPE_TYPE;
const EXCEPTION_RECORD = @import("../system/diagnostics/debug.zig").EXCEPTION_RECORD;
const EXCEPTION_ROUTINE = @import("../system/kernel.zig").EXCEPTION_ROUTINE;
const FILE_ID_128 = @import("../storage/file_system.zig").FILE_ID_128;
const FLAGGED_BYTE_BLOB = @import("../system/com.zig").FLAGGED_BYTE_BLOB;
const FONTOBJ = @import("../ui/display_devices.zig").FONTOBJ;
const GDIINFO = @import("../ui/display_devices.zig").GDIINFO;
const GENERIC_MAPPING = @import("../security.zig").GENERIC_MAPPING;
const GLYPHDATA = @import("../ui/display_devices.zig").GLYPHDATA;
const GROUP_AFFINITY = @import("../system/kernel.zig").GROUP_AFFINITY;
const HANDLE = @import("../foundation.zig").HANDLE;
const HBITMAP = @import("../graphics/gdi.zig").HBITMAP;
const HDC = @import("../graphics/gdi.zig").HDC;
const HINSTANCE = @import("../foundation.zig").HINSTANCE;
const HRESULT = @import("../foundation.zig").HRESULT;
const HWND = @import("../foundation.zig").HWND;
const IFIMETRICS = @import("../ui/display_devices.zig").IFIMETRICS;
const IMAGE_DATA_DIRECTORY = @import("../system/diagnostics/debug.zig").IMAGE_DATA_DIRECTORY;
const IMAGE_FILE_HEADER = @import("../system/diagnostics/debug.zig").IMAGE_FILE_HEADER;
const IUnknown = @import("../system/com.zig").IUnknown;
const JOB_OBJECT_LIMIT = @import("../system/job_objects.zig").JOB_OBJECT_LIMIT;
const JOB_OBJECT_SECURITY = @import("../system/job_objects.zig").JOB_OBJECT_SECURITY;
const JOB_OBJECT_UILIMIT = @import("../system/job_objects.zig").JOB_OBJECT_UILIMIT;
const LINEATTRS = @import("../ui/display_devices.zig").LINEATTRS;
const LIST_ENTRY = @import("../system/kernel.zig").LIST_ENTRY;
const LOGCOLORSPACEW = @import("../ui/color_system.zig").LOGCOLORSPACEW;
const LOGICAL_PROCESSOR_RELATIONSHIP = @import("../system/system_information.zig").LOGICAL_PROCESSOR_RELATIONSHIP;
const LOGPALETTE = @import("../graphics/gdi.zig").LOGPALETTE;
const LPOVERLAPPED_COMPLETION_ROUTINE = @import("../storage/file_system.zig").LPOVERLAPPED_COMPLETION_ROUTINE;
const NTSTATUS = @import("../foundation.zig").NTSTATUS;
const OBJECT_TYPE_LIST = @import("../security.zig").OBJECT_TYPE_LIST;
const OSVERSIONINFOEXW = @import("../system/system_information.zig").OSVERSIONINFOEXW;
const PALOBJ = @import("../ui/display_devices.zig").PALOBJ;
const PARTITION_INFORMATION_GPT = @import("../storage/file_system.zig").PARTITION_INFORMATION_GPT;
const PARTITION_STYLE = @import("../storage/file_system.zig").PARTITION_STYLE;
const PATHOBJ = @import("../ui/display_devices.zig").PATHOBJ;
const PERBANDINFO = @import("../ui/display_devices.zig").PERBANDINFO;
const PIXELFORMATDESCRIPTOR = @import("../graphics/open_gl.zig").PIXELFORMATDESCRIPTOR;
const POINT = @import("../foundation.zig").POINT;
const POINTL = @import("../foundation.zig").POINTL;
const POWER_SETTING_REGISTER_NOTIFICATION_FLAGS = @import("../system/power.zig").POWER_SETTING_REGISTER_NOTIFICATION_FLAGS;
const PREPARE_TAPE_OPERATION = @import("../storage/file_system.zig").PREPARE_TAPE_OPERATION;
const PRIVILEGE_SET = @import("../security.zig").PRIVILEGE_SET;
const PROPERTYKEY = @import("../system/properties_system.zig").PROPERTYKEY;
const PSID = @import("../foundation.zig").PSID;
const PSTR = @import("../foundation.zig").PSTR;
const PTP_POOL = @import("../system/threading.zig").PTP_POOL;
const PWSTR = @import("../foundation.zig").PWSTR;
const RECT = @import("../foundation.zig").RECT;
const RECTL = @import("../foundation.zig").RECTL;
const REPORT_EVENT_TYPE = @import("../system/event_log.zig").REPORT_EVENT_TYPE;
const RETRIEVAL_POINTERS_BUFFER = @import("../storage/file_system.zig").RETRIEVAL_POINTERS_BUFFER;
const RPC_BINDING_VECTOR = @import("../system/rpc.zig").RPC_BINDING_VECTOR;
const RPC_MESSAGE = @import("../system/rpc.zig").RPC_MESSAGE;
const RPC_STATUS = @import("../system/rpc.zig").RPC_STATUS;
const SECURITY_DESCRIPTOR = @import("../security.zig").SECURITY_DESCRIPTOR;
const SECURITY_IMPERSONATION_LEVEL = @import("../security.zig").SECURITY_IMPERSONATION_LEVEL;
const SET_PARTITION_INFORMATION = @import("../storage/file_system.zig").SET_PARTITION_INFORMATION;
const SID = @import("../security.zig").SID;
const SID_AND_ATTRIBUTES = @import("../security.zig").SID_AND_ATTRIBUTES;
const SIZE = @import("../foundation.zig").SIZE;
const SLIST_ENTRY = @import("../system/kernel.zig").SLIST_ENTRY;
const SLIST_HEADER = @import("../system/kernel.zig").SLIST_HEADER;
const STORAGE_PROPERTY_ID = @import("../storage/file_system.zig").STORAGE_PROPERTY_ID;
const STORAGE_PROTOCOL_TYPE = @import("../storage/file_system.zig").STORAGE_PROTOCOL_TYPE;
const STROBJ = @import("../ui/display_devices.zig").STROBJ;
const SURFOBJ = @import("../ui/display_devices.zig").SURFOBJ;
const SYSTEM_POWER_CONDITION = @import("../system/power.zig").SYSTEM_POWER_CONDITION;
const SYSTEM_POWER_STATE = @import("../system/power.zig").SYSTEM_POWER_STATE;
const TAPE_POSITION_METHOD = @import("../storage/file_system.zig").TAPE_POSITION_METHOD;
const TAPE_POSITION_TYPE = @import("../storage/file_system.zig").TAPE_POSITION_TYPE;
const TAPEMARK_TYPE = @import("../storage/file_system.zig").TAPEMARK_TYPE;
const TOKEN_GROUPS = @import("../security.zig").TOKEN_GROUPS;
const TOKEN_PRIVILEGES = @import("../security.zig").TOKEN_PRIVILEGES;
const TOKEN_USER = @import("../security.zig").TOKEN_USER;
const TRIVERTEX = @import("../graphics/gdi.zig").TRIVERTEX;
const TTPOLYGONHEADER = @import("../graphics/gdi.zig").TTPOLYGONHEADER;
const VIDEOMEMORY = @import("../ui/display_devices.zig").VIDEOMEMORY;
const VIRTUAL_STORAGE_TYPE = @import("../storage/vhd.zig").VIRTUAL_STORAGE_TYPE;
const WNDOBJ = @import("../ui/display_devices.zig").WNDOBJ;
const XLATEOBJ = @import("../ui/display_devices.zig").XLATEOBJ;
// 2 arch-specific imports
const CONTEXT = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => @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 EXCEPTION_POINTERS = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => @import("../system/diagnostics/debug.zig").EXCEPTION_POINTERS,
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(), "PUMS_SCHEDULER_ENTRY_POINT")) { _ = PUMS_SCHEDULER_ENTRY_POINT; }
if (@hasDecl(@This(), "PIMAGE_TLS_CALLBACK")) { _ = PIMAGE_TLS_CALLBACK; }
if (@hasDecl(@This(), "PRTL_UMS_SCHEDULER_ENTRY_POINT")) { _ = PRTL_UMS_SCHEDULER_ENTRY_POINT; }
if (@hasDecl(@This(), "PAPCFUNC")) { _ = PAPCFUNC; }
if (@hasDecl(@This(), "WAITORTIMERCALLBACK")) { _ = WAITORTIMERCALLBACK; }
if (@hasDecl(@This(), "WORKERCALLBACKFUNC")) { _ = WORKERCALLBACKFUNC; }
if (@hasDecl(@This(), "APC_CALLBACK_FUNCTION")) { _ = APC_CALLBACK_FUNCTION; }
if (@hasDecl(@This(), "PFLS_CALLBACK_FUNCTION")) { _ = PFLS_CALLBACK_FUNCTION; }
if (@hasDecl(@This(), "PTP_SIMPLE_CALLBACK")) { _ = PTP_SIMPLE_CALLBACK; }
if (@hasDecl(@This(), "PTP_CLEANUP_GROUP_CANCEL_CALLBACK")) { _ = PTP_CLEANUP_GROUP_CANCEL_CALLBACK; }
if (@hasDecl(@This(), "PTP_WORK_CALLBACK")) { _ = PTP_WORK_CALLBACK; }
if (@hasDecl(@This(), "PTP_TIMER_CALLBACK")) { _ = PTP_TIMER_CALLBACK; }
if (@hasDecl(@This(), "PTP_WAIT_CALLBACK")) { _ = PTP_WAIT_CALLBACK; }
if (@hasDecl(@This(), "LPTHREAD_START_ROUTINE")) { _ = LPTHREAD_START_ROUTINE; }
if (@hasDecl(@This(), "LPTIMECALLBACK")) { _ = LPTIMECALLBACK; }
if (@hasDecl(@This(), "LPD3DVALIDATECALLBACK")) { _ = LPD3DVALIDATECALLBACK; }
if (@hasDecl(@This(), "LPD3DENUMTEXTUREFORMATSCALLBACK")) { _ = LPD3DENUMTEXTUREFORMATSCALLBACK; }
if (@hasDecl(@This(), "LPD3DENUMPIXELFORMATSCALLBACK")) { _ = LPD3DENUMPIXELFORMATSCALLBACK; }
if (@hasDecl(@This(), "LPD3DENUMDEVICESCALLBACK")) { _ = LPD3DENUMDEVICESCALLBACK; }
if (@hasDecl(@This(), "LPD3DENUMDEVICESCALLBACK7")) { _ = LPD3DENUMDEVICESCALLBACK7; }
if (@hasDecl(@This(), "LPD3DNTHAL_CONTEXTCREATECB")) { _ = LPD3DNTHAL_CONTEXTCREATECB; }
if (@hasDecl(@This(), "LPD3DNTHAL_CONTEXTDESTROYCB")) { _ = LPD3DNTHAL_CONTEXTDESTROYCB; }
if (@hasDecl(@This(), "LPD3DNTHAL_CONTEXTDESTROYALLCB")) { _ = LPD3DNTHAL_CONTEXTDESTROYALLCB; }
if (@hasDecl(@This(), "LPD3DNTHAL_SCENECAPTURECB")) { _ = LPD3DNTHAL_SCENECAPTURECB; }
if (@hasDecl(@This(), "LPD3DNTHAL_TEXTURECREATECB")) { _ = LPD3DNTHAL_TEXTURECREATECB; }
if (@hasDecl(@This(), "LPD3DNTHAL_TEXTUREDESTROYCB")) { _ = LPD3DNTHAL_TEXTUREDESTROYCB; }
if (@hasDecl(@This(), "LPD3DNTHAL_TEXTURESWAPCB")) { _ = LPD3DNTHAL_TEXTURESWAPCB; }
if (@hasDecl(@This(), "LPD3DNTHAL_TEXTUREGETSURFCB")) { _ = LPD3DNTHAL_TEXTUREGETSURFCB; }
if (@hasDecl(@This(), "LPD3DNTHAL_SETRENDERTARGETCB")) { _ = LPD3DNTHAL_SETRENDERTARGETCB; }
if (@hasDecl(@This(), "LPD3DNTHAL_CLEAR2CB")) { _ = LPD3DNTHAL_CLEAR2CB; }
if (@hasDecl(@This(), "LPD3DNTHAL_VALIDATETEXTURESTAGESTATECB")) { _ = LPD3DNTHAL_VALIDATETEXTURESTAGESTATECB; }
if (@hasDecl(@This(), "LPD3DNTHAL_DRAWPRIMITIVES2CB")) { _ = LPD3DNTHAL_DRAWPRIMITIVES2CB; }
if (@hasDecl(@This(), "PFND3DNTPARSEUNKNOWNCOMMAND")) { _ = PFND3DNTPARSEUNKNOWNCOMMAND; }
if (@hasDecl(@This(), "PFN")) { _ = PFN; }
if (@hasDecl(@This(), "WNDOBJCHANGEPROC")) { _ = WNDOBJCHANGEPROC; }
if (@hasDecl(@This(), "SORTCOMP")) { _ = SORTCOMP; }
if (@hasDecl(@This(), "PFN_DrvEnableDriver")) { _ = PFN_DrvEnableDriver; }
if (@hasDecl(@This(), "PFN_DrvEnablePDEV")) { _ = PFN_DrvEnablePDEV; }
if (@hasDecl(@This(), "PFN_DrvCompletePDEV")) { _ = PFN_DrvCompletePDEV; }
if (@hasDecl(@This(), "PFN_DrvResetDevice")) { _ = PFN_DrvResetDevice; }
if (@hasDecl(@This(), "PFN_DrvDisablePDEV")) { _ = PFN_DrvDisablePDEV; }
if (@hasDecl(@This(), "PFN_DrvSynchronize")) { _ = PFN_DrvSynchronize; }
if (@hasDecl(@This(), "PFN_DrvEnableSurface")) { _ = PFN_DrvEnableSurface; }
if (@hasDecl(@This(), "PFN_DrvDisableDriver")) { _ = PFN_DrvDisableDriver; }
if (@hasDecl(@This(), "PFN_DrvDisableSurface")) { _ = PFN_DrvDisableSurface; }
if (@hasDecl(@This(), "PFN_DrvAssertMode")) { _ = PFN_DrvAssertMode; }
if (@hasDecl(@This(), "PFN_DrvTextOut")) { _ = PFN_DrvTextOut; }
if (@hasDecl(@This(), "PFN_DrvStretchBlt")) { _ = PFN_DrvStretchBlt; }
if (@hasDecl(@This(), "PFN_DrvStretchBltROP")) { _ = PFN_DrvStretchBltROP; }
if (@hasDecl(@This(), "PFN_DrvTransparentBlt")) { _ = PFN_DrvTransparentBlt; }
if (@hasDecl(@This(), "PFN_DrvPlgBlt")) { _ = PFN_DrvPlgBlt; }
if (@hasDecl(@This(), "PFN_DrvBitBlt")) { _ = PFN_DrvBitBlt; }
if (@hasDecl(@This(), "PFN_DrvRealizeBrush")) { _ = PFN_DrvRealizeBrush; }
if (@hasDecl(@This(), "PFN_DrvCopyBits")) { _ = PFN_DrvCopyBits; }
if (@hasDecl(@This(), "PFN_DrvDitherColor")) { _ = PFN_DrvDitherColor; }
if (@hasDecl(@This(), "PFN_DrvCreateDeviceBitmap")) { _ = PFN_DrvCreateDeviceBitmap; }
if (@hasDecl(@This(), "PFN_DrvDeleteDeviceBitmap")) { _ = PFN_DrvDeleteDeviceBitmap; }
if (@hasDecl(@This(), "PFN_DrvSetPalette")) { _ = PFN_DrvSetPalette; }
if (@hasDecl(@This(), "PFN_DrvEscape")) { _ = PFN_DrvEscape; }
if (@hasDecl(@This(), "PFN_DrvDrawEscape")) { _ = PFN_DrvDrawEscape; }
if (@hasDecl(@This(), "PFN_DrvQueryFont")) { _ = PFN_DrvQueryFont; }
if (@hasDecl(@This(), "PFN_DrvQueryFontTree")) { _ = PFN_DrvQueryFontTree; }
if (@hasDecl(@This(), "PFN_DrvQueryFontData")) { _ = PFN_DrvQueryFontData; }
if (@hasDecl(@This(), "PFN_DrvFree")) { _ = PFN_DrvFree; }
if (@hasDecl(@This(), "PFN_DrvDestroyFont")) { _ = PFN_DrvDestroyFont; }
if (@hasDecl(@This(), "PFN_DrvQueryFontCaps")) { _ = PFN_DrvQueryFontCaps; }
if (@hasDecl(@This(), "PFN_DrvLoadFontFile")) { _ = PFN_DrvLoadFontFile; }
if (@hasDecl(@This(), "PFN_DrvUnloadFontFile")) { _ = PFN_DrvUnloadFontFile; }
if (@hasDecl(@This(), "PFN_DrvSetPointerShape")) { _ = PFN_DrvSetPointerShape; }
if (@hasDecl(@This(), "PFN_DrvMovePointer")) { _ = PFN_DrvMovePointer; }
if (@hasDecl(@This(), "PFN_DrvSendPage")) { _ = PFN_DrvSendPage; }
if (@hasDecl(@This(), "PFN_DrvStartPage")) { _ = PFN_DrvStartPage; }
if (@hasDecl(@This(), "PFN_DrvStartDoc")) { _ = PFN_DrvStartDoc; }
if (@hasDecl(@This(), "PFN_DrvEndDoc")) { _ = PFN_DrvEndDoc; }
if (@hasDecl(@This(), "PFN_DrvQuerySpoolType")) { _ = PFN_DrvQuerySpoolType; }
if (@hasDecl(@This(), "PFN_DrvLineTo")) { _ = PFN_DrvLineTo; }
if (@hasDecl(@This(), "PFN_DrvStrokePath")) { _ = PFN_DrvStrokePath; }
if (@hasDecl(@This(), "PFN_DrvFillPath")) { _ = PFN_DrvFillPath; }
if (@hasDecl(@This(), "PFN_DrvStrokeAndFillPath")) { _ = PFN_DrvStrokeAndFillPath; }
if (@hasDecl(@This(), "PFN_DrvPaint")) { _ = PFN_DrvPaint; }
if (@hasDecl(@This(), "PFN_DrvGetGlyphMode")) { _ = PFN_DrvGetGlyphMode; }
if (@hasDecl(@This(), "PFN_DrvResetPDEV")) { _ = PFN_DrvResetPDEV; }
if (@hasDecl(@This(), "PFN_DrvSaveScreenBits")) { _ = PFN_DrvSaveScreenBits; }
if (@hasDecl(@This(), "PFN_DrvGetModes")) { _ = PFN_DrvGetModes; }
if (@hasDecl(@This(), "PFN_DrvQueryTrueTypeTable")) { _ = PFN_DrvQueryTrueTypeTable; }
if (@hasDecl(@This(), "PFN_DrvQueryTrueTypeSection")) { _ = PFN_DrvQueryTrueTypeSection; }
if (@hasDecl(@This(), "PFN_DrvQueryTrueTypeOutline")) { _ = PFN_DrvQueryTrueTypeOutline; }
if (@hasDecl(@This(), "PFN_DrvGetTrueTypeFile")) { _ = PFN_DrvGetTrueTypeFile; }
if (@hasDecl(@This(), "PFN_DrvQueryFontFile")) { _ = PFN_DrvQueryFontFile; }
if (@hasDecl(@This(), "PFN_DrvQueryAdvanceWidths")) { _ = PFN_DrvQueryAdvanceWidths; }
if (@hasDecl(@This(), "PFN_DrvFontManagement")) { _ = PFN_DrvFontManagement; }
if (@hasDecl(@This(), "PFN_DrvSetPixelFormat")) { _ = PFN_DrvSetPixelFormat; }
if (@hasDecl(@This(), "PFN_DrvDescribePixelFormat")) { _ = PFN_DrvDescribePixelFormat; }
if (@hasDecl(@This(), "PFN_DrvSwapBuffers")) { _ = PFN_DrvSwapBuffers; }
if (@hasDecl(@This(), "PFN_DrvStartBanding")) { _ = PFN_DrvStartBanding; }
if (@hasDecl(@This(), "PFN_DrvNextBand")) { _ = PFN_DrvNextBand; }
if (@hasDecl(@This(), "PFN_DrvQueryPerBandInfo")) { _ = PFN_DrvQueryPerBandInfo; }
if (@hasDecl(@This(), "PFN_DrvEnableDirectDraw")) { _ = PFN_DrvEnableDirectDraw; }
if (@hasDecl(@This(), "PFN_DrvDisableDirectDraw")) { _ = PFN_DrvDisableDirectDraw; }
if (@hasDecl(@This(), "PFN_DrvGetDirectDrawInfo")) { _ = PFN_DrvGetDirectDrawInfo; }
if (@hasDecl(@This(), "PFN_DrvIcmCreateColorTransform")) { _ = PFN_DrvIcmCreateColorTransform; }
if (@hasDecl(@This(), "PFN_DrvIcmDeleteColorTransform")) { _ = PFN_DrvIcmDeleteColorTransform; }
if (@hasDecl(@This(), "PFN_DrvIcmCheckBitmapBits")) { _ = PFN_DrvIcmCheckBitmapBits; }
if (@hasDecl(@This(), "PFN_DrvIcmSetDeviceGammaRamp")) { _ = PFN_DrvIcmSetDeviceGammaRamp; }
if (@hasDecl(@This(), "PFN_DrvAlphaBlend")) { _ = PFN_DrvAlphaBlend; }
if (@hasDecl(@This(), "PFN_DrvGradientFill")) { _ = PFN_DrvGradientFill; }
if (@hasDecl(@This(), "PFN_DrvQueryDeviceSupport")) { _ = PFN_DrvQueryDeviceSupport; }
if (@hasDecl(@This(), "PFN_DrvDeriveSurface")) { _ = PFN_DrvDeriveSurface; }
if (@hasDecl(@This(), "PFN_DrvSynchronizeSurface")) { _ = PFN_DrvSynchronizeSurface; }
if (@hasDecl(@This(), "PFN_DrvNotify")) { _ = PFN_DrvNotify; }
if (@hasDecl(@This(), "PFN_DrvRenderHint")) { _ = PFN_DrvRenderHint; }
if (@hasDecl(@This(), "PFN_EngCreateRectRgn")) { _ = PFN_EngCreateRectRgn; }
if (@hasDecl(@This(), "PFN_EngDeleteRgn")) { _ = PFN_EngDeleteRgn; }
if (@hasDecl(@This(), "PFN_EngCombineRgn")) { _ = PFN_EngCombineRgn; }
if (@hasDecl(@This(), "PFN_EngCopyRgn")) { _ = PFN_EngCopyRgn; }
if (@hasDecl(@This(), "PFN_EngIntersectRgn")) { _ = PFN_EngIntersectRgn; }
if (@hasDecl(@This(), "PFN_EngSubtractRgn")) { _ = PFN_EngSubtractRgn; }
if (@hasDecl(@This(), "PFN_EngUnionRgn")) { _ = PFN_EngUnionRgn; }
if (@hasDecl(@This(), "PFN_EngXorRgn")) { _ = PFN_EngXorRgn; }
if (@hasDecl(@This(), "PFN_DrvCreateDeviceBitmapEx")) { _ = PFN_DrvCreateDeviceBitmapEx; }
if (@hasDecl(@This(), "PFN_DrvDeleteDeviceBitmapEx")) { _ = PFN_DrvDeleteDeviceBitmapEx; }
if (@hasDecl(@This(), "PFN_DrvAssociateSharedSurface")) { _ = PFN_DrvAssociateSharedSurface; }
if (@hasDecl(@This(), "PFN_DrvSynchronizeRedirectionBitmaps")) { _ = PFN_DrvSynchronizeRedirectionBitmaps; }
if (@hasDecl(@This(), "PFN_DrvAccumulateD3DDirtyRect")) { _ = PFN_DrvAccumulateD3DDirtyRect; }
if (@hasDecl(@This(), "PFN_DrvStartDxInterop")) { _ = PFN_DrvStartDxInterop; }
if (@hasDecl(@This(), "PFN_DrvEndDxInterop")) { _ = PFN_DrvEndDxInterop; }
if (@hasDecl(@This(), "PFN_DrvLockDisplayArea")) { _ = PFN_DrvLockDisplayArea; }
if (@hasDecl(@This(), "PFN_DrvUnlockDisplayArea")) { _ = PFN_DrvUnlockDisplayArea; }
if (@hasDecl(@This(), "PFN_DrvSurfaceComplete")) { _ = PFN_DrvSurfaceComplete; }
if (@hasDecl(@This(), "PIO_IRP_EXT_PROCESS_TRACKED_OFFSET_CALLBACK")) { _ = PIO_IRP_EXT_PROCESS_TRACKED_OFFSET_CALLBACK; }
if (@hasDecl(@This(), "PEXCEPTION_FILTER")) { _ = PEXCEPTION_FILTER; }
if (@hasDecl(@This(), "PTERMINATION_HANDLER")) { _ = PTERMINATION_HANDLER; }
if (@hasDecl(@This(), "PTERMINATION_HANDLER")) { _ = PTERMINATION_HANDLER; }
if (@hasDecl(@This(), "PGET_RUNTIME_FUNCTION_CALLBACK")) { _ = PGET_RUNTIME_FUNCTION_CALLBACK; }
if (@hasDecl(@This(), "PGET_RUNTIME_FUNCTION_CALLBACK")) { _ = PGET_RUNTIME_FUNCTION_CALLBACK; }
if (@hasDecl(@This(), "POUT_OF_PROCESS_FUNCTION_TABLE_CALLBACK")) { _ = POUT_OF_PROCESS_FUNCTION_TABLE_CALLBACK; }
if (@hasDecl(@This(), "POUT_OF_PROCESS_FUNCTION_TABLE_CALLBACK")) { _ = POUT_OF_PROCESS_FUNCTION_TABLE_CALLBACK; }
@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/system/system_services.zig |
const std = @import("std");
pub const CigarOp = enum(u8) {
match = '=',
mismatch = 'X',
deletion = 'D',
insertion = 'I',
};
pub const Cigar = struct {
const Self = @This();
const Entry = struct {
op: CigarOp,
count: usize = 0,
};
allocator: std.mem.Allocator,
entries: std.ArrayList(Entry),
pub fn init(allocator: std.mem.Allocator) Self {
return Self{
.allocator = allocator,
.entries = std.ArrayList(Entry).init(allocator),
};
}
pub fn clone(self: Self) !Self {
var cloned = Self.init(self.allocator);
try cloned.entries.appendSlice(self.entries.items);
return cloned;
}
pub fn isEmpty(self: Self) bool {
return self.entries.items.len == 0;
}
pub fn clear(self: *Self) void {
self.entries.clearRetainingCapacity();
}
pub fn addWithCount(self: *Self, op: CigarOp, count: usize) !void {
var last_entry = if (self.entries.items.len == 0) null else &self.entries.items[self.entries.items.len - 1];
if (last_entry == null or last_entry.?.op != op) {
try self.entries.append(Entry{ .op = op, .count = count });
} else {
last_entry.?.count += count;
}
}
pub fn add(self: *Self, op: CigarOp) !void {
try self.addWithCount(op, 1);
}
pub fn addFromString(self: *Self, s: []const u8) !void {
var counts = std.mem.tokenize(u8, s, "=XDI");
var ops = std.mem.tokenize(u8, s, "0123456789");
while (counts.next()) |count| {
var op = ops.next();
if (op == null)
break;
try self.addWithCount(@intToEnum(CigarOp, op.?[0]), try std.fmt.parseInt(usize, count, 10));
}
}
pub fn appendOther(self: *Self, other: Self) !void {
for (other.entries.items) |other_entry| {
try self.addWithCount(other_entry.op, other_entry.count);
}
}
pub const Iterator = struct {
cigar: *const Self,
index: usize = 0,
count: usize = 0,
pub fn next(it: *Iterator) ?CigarOp {
if (it.isEmpty())
return null;
var entry = it.cigar.entries.items[it.index];
it.count += 1;
if (it.count >= entry.count) {
// next element
it.count = 0;
it.index += 1;
}
return entry.op;
}
pub fn isEmpty(it: *Iterator) bool {
if (it.cigar.entries.items.len == 0)
return true;
if (it.index >= it.cigar.entries.items.len)
return true;
return false;
}
};
pub fn iterator(self: *const Self) Iterator {
return Iterator{ .cigar = self };
}
pub fn reverse(self: *Self) void {
std.mem.reverse(Entry, self.entries.items);
}
pub fn str(self: Self) []const u8 {
// let's try this nifty local buffer thingy by idtech idStr
const S = struct {
threadlocal var buffer: [10_000]u8 = undefined;
};
var fbs = std.io.fixedBufferStream(&S.buffer);
var buf: [128]u8 = undefined;
for (self.entries.items) |entry| {
const xyz = std.fmt.bufPrint(&buf, "{}{c}", .{ entry.count, @enumToInt(entry.op) }) catch &[_]u8{};
_ = fbs.write(xyz) catch 0;
}
return fbs.getWritten();
}
pub fn identity(self: Self) f32 {
var letters: usize = 0;
var matches: usize = 0;
for (self.entries.items) |entry, index| {
const is_gap = (entry.op == .insertion or entry.op == .deletion);
// Don't count terminal gaps towards identity calculation
if (index == 0 and is_gap)
continue;
if (index == self.entries.items.len - 1 and is_gap)
continue;
letters += entry.count;
matches += if (entry.op == .match) entry.count else 0;
}
if (letters == 0)
return 0.0;
return @intToFloat(f32, matches) / @intToFloat(f32, letters);
}
pub fn deinit(self: *Self) void {
self.entries.deinit();
}
};
test "basic add" {
const allocator = std.testing.allocator;
var cigar = Cigar.init(allocator);
defer cigar.deinit();
try cigar.add(.match);
try cigar.add(.match);
try cigar.add(.mismatch);
try cigar.add(.deletion);
try cigar.addWithCount(.deletion, 2);
try cigar.add(.insertion);
try cigar.add(.insertion);
try cigar.add(.match);
try std.testing.expectEqualStrings("2=1X3D2I1=", cigar.str());
}
test "pop op" {
const allocator = std.testing.allocator;
var cigar = Cigar.init(allocator);
defer cigar.deinit();
try cigar.add(.match);
try cigar.add(.mismatch);
try cigar.addWithCount(.insertion, 2);
try cigar.add(.match);
var it = cigar.iterator();
try std.testing.expectEqual(CigarOp.match, it.next().?);
try std.testing.expectEqual(CigarOp.mismatch, it.next().?);
try std.testing.expectEqual(CigarOp.insertion, it.next().?);
try std.testing.expectEqual(CigarOp.insertion, it.next().?);
try std.testing.expectEqual(CigarOp.match, it.next().?);
try std.testing.expect(it.next() == null);
}
test "append other cigar" {
const allocator = std.testing.allocator;
var cigar = Cigar.init(allocator);
defer cigar.deinit();
var other_cigar = Cigar.init(allocator);
defer other_cigar.deinit();
// tail does not match, simple append
{
cigar.clear();
try cigar.add(.match);
try cigar.add(.match);
try cigar.add(.mismatch);
other_cigar.clear();
try other_cigar.add(.match);
try other_cigar.add(.deletion);
try cigar.appendOther(other_cigar);
try std.testing.expectEqualStrings("2=1X1=1D", cigar.str());
}
// tail matches, expand
{
cigar.clear();
try cigar.add(.match);
try cigar.add(.match);
try cigar.add(.mismatch);
other_cigar.clear();
try other_cigar.add(.mismatch);
try other_cigar.add(.mismatch);
try other_cigar.add(.deletion);
try cigar.appendOther(other_cigar);
try std.testing.expectEqualStrings("2=3X1D", cigar.str());
}
}
test "addFromString" {
const allocator = std.testing.allocator;
var cigar = Cigar.init(allocator);
defer cigar.deinit();
try cigar.addFromString("5=2I3X25=3D");
try std.testing.expectEqualStrings("5=2I3X25=3D", cigar.str());
} | src/cigar.zig |
const Self = @This();
const std = @import("std");
const hash_map = std.hash_map;
const Allocator = std.mem.Allocator;
const Waypoint = @import("Waypoint.zig");
const Departure = @import("Departure.zig");
const Destination = @import("Destination.zig");
const Route = @import("Route.zig");
/// Allocator associated with this FlightPlan. This allocator must be
/// used for all the memory owned by this structure for deinit to work.
alloc: Allocator,
// The type of flight rules, assumes IFR.
rules: Rules = .ifr,
/// The AIRAC cycle used to create this flight plan, i.e. 2201.
/// See: https://en.wikipedia.org/wiki/Aeronautical_Information_Publication
/// This is expected to be heap-allocated and will be freed on deinit.
airac: ?[:0]const u8 = null,
/// The timestamp when this flight plan was created. This is expected to
/// be heap-allocated and will be freed on deinit.
/// TODO: some well known format
created: ?[:0]const u8 = null,
/// Departure information
departure: ?Departure = null,
/// Destination information
destination: ?Destination = null,
/// Waypoints that are part of the route. These are unordered, they are
/// just the full list of possible waypoints that the route may contain.
waypoints: hash_map.StringHashMapUnmanaged(Waypoint) = .{},
/// The flight plan route. This route may only contain waypoints in the
/// waypoints map.
route: Route = .{},
/// Flight rules types
pub const Rules = enum {
vfr,
ifr,
};
/// Clean up resources associated with the flight plan. This should
/// always be called for any created flight plan when it is no longer in use.
pub fn deinit(self: *Self) void {
if (self.airac) |v| self.alloc.free(v);
if (self.created) |v| self.alloc.free(v);
if (self.departure) |*dep| dep.deinit(self.alloc);
if (self.destination) |*des| des.deinit(self.alloc);
self.route.deinit(self.alloc);
var it = self.waypoints.iterator();
while (it.next()) |kv| {
kv.value_ptr.deinit(self.alloc);
}
self.waypoints.deinit(self.alloc);
self.* = undefined;
}
test {
_ = Waypoint;
_ = @import("binding.zig");
} | src/FlightPlan.zig |
const std = @import("std");
const Compiler = @import("Compiler.zig");
const Context = @import("Context.zig");
const GraphemeIterator = @import("ziglyph").GraphemeIterator;
const Node = @import("Node.zig");
const Scope = @import("Scope.zig");
const ScopeStack = @import("ScopeStack.zig");
const Token = @import("Token.zig");
const value = @import("value.zig");
const Value = value.Value;
const isBuiltinMethod = @import("Parser.zig").isBuiltinMethod;
const runtimePrint = @import("fmt.zig").runtimePrint;
const p2z = @import("pcre2zig");
const ziglyph = @import("ziglyph");
const ObjectTag = std.meta.Tag(Value.Object);
allocator: std.mem.Allocator,
ctx: Context,
last_popped: Value = value.val_nil,
output: *std.ArrayList(u8),
bytecode: []const u8 = undefined,
ip: *u16 = undefined,
scope_stack: *ScopeStack,
frame_stack: std.ArrayList(Frame),
value_stack: std.ArrayList(Value),
const Vm = @This();
pub fn init(
allocator: std.mem.Allocator,
bytecode: []const u8,
scope_stack: *ScopeStack,
ctx: Context,
output: *std.ArrayList(u8),
) !Vm {
var self = Vm{
.allocator = allocator,
.ctx = ctx,
.output = output,
.frame_stack = std.ArrayList(Frame).init(allocator),
.scope_stack = scope_stack,
.value_stack = std.ArrayList(Value).init(allocator),
};
try self.pushFrame(bytecode);
return self;
}
pub fn run(self: *Vm) !void {
while (self.ip.* < self.bytecode.len) {
const opcode = @intToEnum(Compiler.Opcode, self.bytecode[self.ip.*]);
switch (opcode) {
// Stack operations
.pop => try self.execPop(),
.jump => self.execJump(),
.jump_false => self.execJumpFalse(),
.jump_true => self.execJumpTrue(),
// Scope
.scope_in => try self.execScopeIn(),
.scope_out => try self.execScopeOut(),
// Predefined constant values
.bool_false => try self.execBoolFalse(),
.bool_true => try self.execBoolTrue(),
.nil => try self.execNil(),
// Numbers
.float => try self.execFloat(),
.int => try self.execInt(),
.uint => try self.execUint(),
// Strings
.format => try self.execFormat(),
.plain, .raw_str => try self.execPlain(),
.string => try self.execString(),
// functions
.builtin => try self.execBuiltin(),
.call => try self.execCall(),
.func => try self.execFunc(),
.func_return => {
if (self.frame_stack.items.len == 1) {
// Top-level return
self.last_popped = self.value_stack.pop();
self.ip.* += 1;
break; // VM exit
}
try self.execReturn();
},
// Variables
.define => try self.execDefine(),
.load => try self.execLoad(),
.store => try self.execStore(),
.global => try self.execGlobal(),
.gstore => try self.execGlobalStore(),
// Infix
.add => try self.execAdd(),
.sub => try self.execSub(),
.mul => try self.execMul(),
.div => try self.execDiv(),
.mod => try self.execMod(),
.concat => try self.execConcat(),
.repeat => try self.execRepeat(),
// Comparison
.lt,
.lte,
.gt,
.gte,
=> try self.execComparison(opcode),
.eq, .neq => try self.execEqNeq(opcode),
// Prefix
.neg => try self.execNeg(),
.not => try self.execNot(),
// Data structures
.list => try self.execList(),
.map => try self.execMap(),
.range => try self.execRange(),
.subscript => try self.execSubscript(),
.set => try self.execSet(),
// Record Ranges
.rec_range => try self.execRecRange(),
// Output redirection
.redir => try self.execRedir(),
// Printing
.sprint => try self.execSprint(),
// Regex
.match, .nomatch => try self.execMatch(opcode),
.matcher => try self.execMatcher(),
}
}
}
// Exec functions
fn execPop(self: *Vm) !void {
self.last_popped = self.value_stack.pop();
self.ip.* += 1;
}
fn execBoolFalse(self: *Vm) !void {
self.ip.* += 1;
try self.value_stack.append(value.val_false);
self.ip.* += 2;
}
fn execBoolTrue(self: *Vm) !void {
self.ip.* += 1;
try self.value_stack.append(value.val_true);
self.ip.* += 2;
}
fn execNil(self: *Vm) !void {
self.ip.* += 1;
try self.value_stack.append(value.val_nil);
self.ip.* += 2;
}
fn execFloat(self: *Vm) !void {
self.ip.* += 1;
const f = self.getNumber(f64, self.ip.*, 8);
self.ip.* += 8;
try self.value_stack.append(value.floatToValue(f));
}
fn execInt(self: *Vm) !void {
self.ip.* += 1;
const i = self.getNumber(i32, self.ip.*, 4);
self.ip.* += 4;
try self.value_stack.append(value.intToValue(i));
}
fn execUint(self: *Vm) !void {
self.ip.* += 1;
const u = self.getNumber(u32, self.ip.*, 4);
self.ip.* += 4;
try self.value_stack.append(value.uintToValue(u));
}
fn execFormat(self: *Vm) !void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const spec = std.mem.sliceTo(self.bytecode[self.ip.*..], 0);
self.ip.* += @intCast(u16, spec.len) + 1;
const v = self.value_stack.pop();
var buf = std.ArrayList(u8).init(self.allocator);
var writer = buf.writer();
runtimePrint(
self.allocator,
spec,
v,
writer,
) catch |err| return self.ctx.err(
"Error in string interpolation #{s}#.",
.{spec},
err,
offset,
);
if (buf.items.len < 7) {
try self.value_stack.append(value.strToValue(buf.items));
} else {
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .string = buf.items };
const obj_addr = @ptrToInt(obj_ptr);
try self.value_stack.append(value.addrToValue(obj_addr));
}
}
fn execPlain(self: *Vm) !void {
self.ip.* += 1;
const str = std.mem.sliceTo(self.bytecode[self.ip.*..], 0);
self.ip.* += @intCast(u16, str.len) + 1;
if (str.len < 7) {
try self.value_stack.append(value.strToValue(str));
} else {
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .string = str };
const obj_addr = @ptrToInt(obj_ptr);
try self.value_stack.append(value.addrToValue(obj_addr));
}
}
fn execString(self: *Vm) !void {
self.ip.* += 1;
const len = self.getU16(self.ip.*);
self.ip.* += 2;
var buf = std.ArrayList(u8).init(self.allocator);
var writer = buf.writer();
var i: usize = 0;
while (i < len) : (i += 1) try value.print(self.value_stack.pop(), writer);
if (buf.items.len < 7) {
try self.value_stack.append(value.strToValue(buf.items));
} else {
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .string = buf.items };
const obj_addr = @ptrToInt(obj_ptr);
try self.value_stack.append(value.addrToValue(obj_addr));
}
}
fn execFunc(self: *Vm) !void {
self.ip.* += 1;
// Bytes to skip if cached function.
const skip_bytes = self.getU16(self.ip.*);
self.ip.* += 2;
// Func string
const func_str = try self.scope_stack.allocator.dupe(u8, std.mem.sliceTo(self.bytecode[self.ip.*..], 0));
self.ip.* += @intCast(u16, func_str.len) + 1;
// Check for cached function.
if (self.scope_stack.value_cache.get(func_str)) |v| {
try self.value_stack.append(v);
self.ip.* += skip_bytes;
return;
}
// Function name
var func_name: ?[]const u8 = null;
if (self.bytecode[self.ip.*] != 0) {
func_name = try self.scope_stack.allocator.dupe(u8, std.mem.sliceTo(self.bytecode[self.ip.*..], 0));
self.ip.* += @intCast(u16, func_name.?.len) + 1;
} else {
self.ip.* += 1;
}
// function params
const params_len = self.getU16(self.ip.*);
self.ip.* += 2;
var params: ?[]const u16 = null;
if (params_len != 0) {
var params_slice = try self.scope_stack.allocator.alloc(u16, params_len);
for (params_slice) |_, i| {
const param = std.mem.sliceTo(self.bytecode[self.ip.*..], 0);
params_slice[i] = self.ip.*;
self.ip.* += @intCast(u16, param.len) + 1;
}
params = params_slice;
}
// Function bytecode
const bytecode_len = self.getU16(self.ip.*);
self.ip.* += 2;
const func_bytecode: ?[]const u8 = if (bytecode_len == 0) null else self.bytecode[self.ip.* .. self.ip.* + bytecode_len];
self.ip.* += bytecode_len;
const func = value.Function{
.str = func_str,
.name = func_name,
.params = params,
.bytecode = func_bytecode,
};
const obj_ptr = try self.scope_stack.allocator.create(value.Object);
obj_ptr.* = .{ .func = func };
const obj_addr = @ptrToInt(obj_ptr);
const obj_val = value.addrToValue(obj_addr);
// Cache for further re-use.
const func_str_copy = try self.scope_stack.allocator.dupe(u8, func_str);
try self.scope_stack.value_cache.put(func_str_copy, obj_val);
try self.value_stack.append(obj_val);
}
fn execBuiltin(self: *Vm) anyerror!void {
self.ip.* += 2;
const offset = self.getOffset();
self.ip.* -= 1;
const builtin = @intToEnum(Token.Tag, self.bytecode[self.ip.*]);
if (isBuiltinMethod(builtin) and value.val_nil == self.value_stack.items[self.value_stack.items.len - 1]) return self.ctx.err(
"Calling a method on nil.",
.{},
error.NilMethodCall,
offset,
);
return switch (builtin) {
.pd_assert => self.execAssert(),
.pd_atan2 => self.execAtan2(),
.pd_capture => self.execCapture(),
.pd_chars => self.execChars(),
.pd_col => self.execCol(),
.pd_contains => self.execContains(),
.pd_cos => self.execOneArgMath(builtin),
.pd_each => self.execEach(),
.pd_endsWith => self.execStrEndStart(false),
.pd_exp => self.execOneArgMath(builtin),
.pd_filter => self.execFilter(),
.pd_join => self.execListJoin(),
.pd_indexOf => self.execIndexOf(),
.pd_int => self.execOneArgMath(builtin),
.pd_keys => self.execMapKeys(),
.pd_keysByValueAsc => self.execMapKeysByValue(true),
.pd_keysByValueDesc => self.execMapKeysByValue(false),
.pd_lastIndexOf => self.execLastIndexOf(),
.pd_len => self.execLen(),
.pd_log => self.execOneArgMath(builtin),
.pd_map => self.execMapMethod(),
.pd_max => self.execListMax(),
.pd_mean => self.execListMean(),
.pd_median => self.execListMedian(),
.pd_memo => self.execMemo(),
.pd_min => self.execListMin(),
.pd_mode => self.execListMode(),
.pd_next => self.execNext(),
.pd_print => self.execPrint(),
.pd_pop => self.execListPop(),
.pd_push => self.execListPush(),
.pd_rand => self.execRand(),
.pd_reduce => self.execReduce(),
.pd_replace => self.execReplace(),
.pd_reset => self.execReset(),
.pd_reverse => self.execListReverse(),
.pd_sin => self.execOneArgMath(builtin),
.pd_sortAsc => self.execListSort(true),
.pd_sortDesc => self.execListSort(false),
.pd_split => self.execStrSplit(),
.pd_sqrt => self.execOneArgMath(builtin),
.pd_startsWith => self.execStrEndStart(true),
.pd_stdev => self.execListStdev(),
.pd_toLower => self.execStrCase(true),
.pd_toUpper => self.execStrCase(false),
.pd_unique => self.execUnique(),
.pd_values => self.execMapValues(),
else => unreachable,
};
}
fn execCall(self: *Vm) anyerror!void {
// Get the offset.
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
// Get the function.
const callee = self.value_stack.pop();
const func_obj_ptr = (value.asFunc(callee)) orelse return self.ctx.err(
"{s} is not callable.",
.{value.typeOf(callee)},
error.InvalidCall,
offset,
);
// Empty func?
if (func_obj_ptr.func.bytecode == null) {
try self.value_stack.append(value.val_nil);
self.ip.* += 1;
return;
}
// Memoized function?
if (func_obj_ptr.func.memo) return self.execCallMemo(func_obj_ptr);
// Prepare the child scope.
var func_scope = Scope.init(self.allocator, .function);
// Self-references
if (func_obj_ptr.func.name) |name| try func_scope.map.put(name, callee);
// Process args
const num_args = self.bytecode[self.ip.*];
self.ip.* += 1;
var i: usize = 0;
while (i < num_args) : (i += 1) {
const arg = self.value_stack.pop();
if (i == 0) try func_scope.map.put("it", arg); // it
var buf: [4]u8 = undefined;
const auto_arg_name = try std.fmt.bufPrint(&buf, "@{}", .{i});
try func_scope.map.put(try self.allocator.dupe(u8, auto_arg_name), arg); // @0, @1, ...
if (func_obj_ptr.func.params) |params| {
if (i < params.len) try func_scope.map.put(std.mem.sliceTo(self.bytecode[params[i]..], 0), arg);
}
}
// Push the function's frame.
try self.pushScope(func_scope);
try self.pushFrame(func_obj_ptr.func.bytecode.?);
}
fn execCallMemo(self: *Vm, func_obj_ptr: *value.Object) !void {
// Process args
const num_args = self.bytecode[self.ip.*];
self.ip.* += 1;
// Hash and check for memoized result.
var wh = std.hash.Wyhash.init(Context.seed);
wh.update(func_obj_ptr.func.str);
var args_buf: [256]Value = undefined;
var i: usize = 0;
while (i < num_args) : (i += 1) args_buf[i] = self.value_stack.pop();
const args = args_buf[0..i];
wh.update(std.mem.sliceAsBytes(args));
const memo_hash = wh.final();
if (self.scope_stack.func_memo.get(memo_hash)) |v| {
try self.value_stack.append(v);
return;
}
// Prepare the child scope.
var func_scope = Scope.init(self.allocator, .function);
// Signal need to memo.
try func_scope.map.put("@memo", memo_hash);
// Self-references
if (func_obj_ptr.func.name) |name| {
const addr = @ptrToInt(func_obj_ptr);
try func_scope.map.put(name, value.addrToValue(addr));
}
for (args) |arg, j| {
if (j == 0) try func_scope.map.put("it", arg); // it
var buf: [4]u8 = undefined;
const auto_arg_name = try std.fmt.bufPrint(&buf, "@{}", .{j});
try func_scope.map.put(try self.allocator.dupe(u8, auto_arg_name), arg); // @0, @1, ...
if (func_obj_ptr.func.params) |params| {
if (j < params.len) try func_scope.map.put(std.mem.sliceTo(self.bytecode[params[j]..], 0), arg);
}
}
// Push the function's frame.
try self.pushScope(func_scope);
try self.pushFrame(func_obj_ptr.func.bytecode.?);
}
fn execReturn(self: *Vm) !void {
self.popFrame();
// Unwind scopes up to the function's scope.
while (true) {
var popped_scope = self.popScope();
// Signal to memoize?
if (popped_scope.map.get("@memo")) |hash| {
try self.scope_stack.func_memo.put(hash, self.value_stack.items[self.value_stack.items.len - 1]);
}
popped_scope.map.deinit();
if (popped_scope.ty == .function) break;
}
}
fn execDefine(self: *Vm) !void {
// Offset
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
// Name
const name = std.mem.sliceTo(self.bytecode[self.ip.*..], 0);
self.ip.* += @intCast(u16, name.len) + 1;
// Is it already defined?
if (self.scope_stack.isDefined(name)) return self.ctx.err(
"{s} is already defined.",
.{name},
error.NameAlreadyDefined,
offset,
);
// Value
const rvalue = self.value_stack.pop();
// Define
try self.scope_stack.store(name, rvalue);
try self.value_stack.append(rvalue);
}
fn execLoad(self: *Vm) !void {
// Offset
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
// Name
const name = std.mem.sliceTo(self.bytecode[self.ip.*..], 0);
self.ip.* += @intCast(u16, name.len) + 1;
// Is the name defined?
if (!self.scope_stack.isDefined(name)) return self.ctx.err(
"{s} is not defined.",
.{name},
error.NameUndefined,
offset,
);
// Load
try self.value_stack.append((self.scope_stack.load(name)).?);
}
fn execStore(self: *Vm) !void {
// Offset
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
// Combo assign
const combo = @intToEnum(Node.Combo, self.bytecode[self.ip.*]);
self.ip.* += 1;
// Name
const name = std.mem.sliceTo(self.bytecode[self.ip.*..], 0);
self.ip.* += @intCast(u16, name.len) + 1;
// Is the name defined?
if (!self.scope_stack.isDefined(name)) return self.ctx.err(
"{s} is not defined.",
.{name},
error.NameUndefined,
offset,
);
// Value
const rvalue = self.value_stack.pop();
// Store
if (combo == .none) {
try self.scope_stack.update(name, rvalue);
try self.value_stack.append(rvalue);
} else {
const old_value = (self.scope_stack.load(name)).?;
const new_value = switch (combo) {
.none => unreachable,
.add => try value.add(old_value, rvalue),
.sub => try value.sub(old_value, rvalue),
.mul => try value.mul(old_value, rvalue),
.div => try value.div(old_value, rvalue),
.mod => try value.mod(old_value, rvalue),
};
try self.scope_stack.update(name, new_value);
try self.value_stack.append(new_value);
}
}
fn execGlobal(self: *Vm) !void {
self.ip.* += 1;
const global = @intToEnum(Token.Tag, self.bytecode[self.ip.*]);
self.ip.* += 1;
const result = switch (global) {
.at_cols => self.scope_stack.columns,
.at_file => self.scope_stack.file,
.at_frnum => value.uintToValue(@intCast(u32, self.scope_stack.frnum)),
.at_head => hd: {
if (self.scope_stack.header_row) |hr| {
break :hd value.uintToValue(@intCast(u32, hr));
} else {
break :hd value.val_nil;
}
},
.at_headers => hdrs: {
if (self.scope_stack.header_row == null) break :hdrs value.val_nil;
var keys_list = std.ArrayList(Value).init(self.allocator);
for (self.scope_stack.headers.keys()) |key| {
if (key.len < 7) {
try keys_list.append(value.strToValue(key));
} else {
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .string = key };
const obj_addr = @ptrToInt(obj_ptr);
try keys_list.append(value.addrToValue(obj_addr));
}
}
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .list = keys_list };
const addr = @ptrToInt(obj_ptr);
break :hdrs value.addrToValue(addr);
},
.at_ics => self.scope_stack.ics,
.at_irs => self.scope_stack.irs,
.at_ocs => self.scope_stack.ocs,
.at_ors => self.scope_stack.ors,
.at_rec => self.scope_stack.record,
.at_rnum => value.uintToValue(@intCast(u32, self.scope_stack.rnum)),
else => unreachable,
};
try self.value_stack.append(result);
}
fn execGlobalStore(self: *Vm) !void {
// Get the offset.
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
// Get the global type.
const global = @intToEnum(Token.Tag, self.bytecode[self.ip.*]);
self.ip.* += 1;
// Get the value to assign.
const rvalue = self.value_stack.pop();
switch (global) {
.at_ics => {
if (!value.isAnyStr(rvalue)) return self.ctx.err(
"@ics must be a string, got: {s}",
.{value.typeOf(rvalue)},
error.InvalidIcs,
offset,
);
self.scope_stack.ics = rvalue;
},
.at_irs => {
if (!value.isAnyStr(rvalue)) return self.ctx.err(
"@irs must be a string, got: {s}",
.{value.typeOf(rvalue)},
error.InvalidIrs,
offset,
);
self.scope_stack.irs = rvalue;
},
.at_ocs => {
if (!value.isAnyStr(rvalue)) return self.ctx.err(
"@ocs must be a string, got: {s}",
.{value.typeOf(rvalue)},
error.InvalidOcs,
offset,
);
self.scope_stack.ocs = rvalue;
},
.at_ors => {
if (!value.isAnyStr(rvalue)) return self.ctx.err(
"@ors must be a string. got: {s}",
.{value.typeOf(rvalue)},
error.InvalidOrs,
offset,
);
self.scope_stack.ors = rvalue;
},
.at_rec => {
if (!value.isAnyStr(rvalue)) return self.ctx.err(
"@rec must be a string, got {s}",
.{value.typeOf(rvalue)},
error.InvalidRec,
offset,
);
self.scope_stack.record = rvalue;
},
.at_cols => {
if (value.asList(rvalue) == null) return self.ctx.err(
"@cols must be a list, got: {s}",
.{value.typeOf(rvalue)},
error.InvalidCols,
offset,
);
self.scope_stack.columns = rvalue;
},
.at_head => {
if (value.asUint(rvalue)) |u| {
self.scope_stack.header_row = u;
} else return self.ctx.err(
"@head must be an unsigned integer, got: {s}",
.{value.typeOf(rvalue)},
error.InvalidHead,
offset,
);
},
.at_headers => {
const hlist = value.asList(rvalue) orelse return self.ctx.err(
"@headers must be a list, got: {s}",
.{value.typeOf(rvalue)},
error.InvalidHeaders,
offset,
);
self.scope_stack.headers.clearRetainingCapacity();
for (hlist.list.items) |v, i| {
const h_str = if (value.unboxStr(v)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(v).?.string;
const h_copy = try self.scope_stack.allocator.dupe(u8, h_str);
try self.scope_stack.headers.put(h_copy, i);
}
},
else => unreachable,
}
try self.value_stack.append(rvalue);
}
// Arithmetic
fn execAdd(self: *Vm) anyerror!void {
const right = self.value_stack.pop();
const left = self.value_stack.pop();
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
if (value.add(left, right)) |sum| {
try self.value_stack.append(sum);
} else |err| return self.ctx.err(
"Invalid addition.",
.{},
err,
offset,
);
}
fn execSub(self: *Vm) anyerror!void {
const right = self.value_stack.pop();
const left = self.value_stack.pop();
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
if (value.sub(left, right)) |diff| {
try self.value_stack.append(diff);
} else |err| return self.ctx.err(
"Invalid subtraction.",
.{},
err,
offset,
);
}
fn execMul(self: *Vm) anyerror!void {
const right = self.value_stack.pop();
const left = self.value_stack.pop();
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
if (value.mul(left, right)) |product| {
try self.value_stack.append(product);
} else |err| return self.ctx.err(
"Invalid multiplication.",
.{},
err,
offset,
);
}
fn execDiv(self: *Vm) anyerror!void {
const right = self.value_stack.pop();
const left = self.value_stack.pop();
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
if (value.div(left, right)) |quotient| {
try self.value_stack.append(quotient);
} else |err| return self.ctx.err(
"Invalid division.",
.{},
err,
offset,
);
}
fn execMod(self: *Vm) anyerror!void {
const right = self.value_stack.pop();
const left = self.value_stack.pop();
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
if (value.mod(left, right)) |remainder| {
try self.value_stack.append(remainder);
} else |err| return self.ctx.err(
"Invalid modulo.",
.{},
err,
offset,
);
}
fn execComparison(self: *Vm, opcode: Compiler.Opcode) !void {
const right = self.value_stack.pop();
const left = self.value_stack.pop();
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const comparison = value.cmp(left, right) catch |err| return self.ctx.err(
"Invalie comparison.",
.{},
err,
offset,
);
const result = switch (opcode) {
.lt => value.boolToValue(comparison == .lt),
.lte => value.boolToValue(comparison == .lt or comparison == .eq),
.gt => value.boolToValue(comparison == .gt),
.gte => value.boolToValue(comparison == .gt or comparison == .eq),
else => unreachable,
};
try self.value_stack.append(result);
}
fn execEqNeq(self: *Vm, opcode: Compiler.Opcode) !void {
const right = self.value_stack.pop();
const left = self.value_stack.pop();
self.ip.* += 3;
var comparison = value.eql(left, right);
if (opcode == .neq) comparison = !comparison;
try self.value_stack.append(value.boolToValue(comparison));
}
fn execConcat(self: *Vm) anyerror!void {
const right = self.value_stack.pop();
const left = self.value_stack.pop();
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
if (!value.isAnyStr(left) or !value.isAnyStr(right)) return self.ctx.err(
"Invlid concatenation.",
.{},
error.InvalidConcat,
offset,
);
const str_left = if (value.unboxStr(left)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(left).?.string;
const str_right = if (value.unboxStr(right)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(right).?.string;
var buf = try self.allocator.alloc(u8, str_left.len + str_right.len);
std.mem.copy(u8, buf, str_left);
std.mem.copy(u8, buf[str_left.len..], str_right);
if (buf.len < 7) {
try self.value_stack.append(value.strToValue(buf));
} else {
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .string = buf };
const obj_addr = @ptrToInt(obj_ptr);
try self.value_stack.append(value.addrToValue(obj_addr));
}
}
fn execRepeat(self: *Vm) anyerror!void {
const right = self.value_stack.pop();
const left = self.value_stack.pop();
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
if (!value.isAnyStr(left) or !value.isUint(right)) return self.ctx.err(
"Invalid string repeat.",
.{},
error.InvalidRepeat,
offset,
);
const str_left = if (value.unboxStr(left)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(left).?.string;
const n = value.asUint(right) orelse return self.ctx.err(
"`repeat` arg must be an unsigned integer, got: {s}",
.{value.typeOf(right)},
error.InvalidRepeat,
offset,
);
var buf = try self.allocator.alloc(u8, str_left.len * n);
var i: usize = 0;
while (i < n) : (i += 1) std.mem.copy(u8, buf[str_left.len * i ..], str_left);
if (buf.len < 7) {
try self.value_stack.append(value.strToValue(buf));
} else {
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .string = buf };
const obj_addr = @ptrToInt(obj_ptr);
try self.value_stack.append(value.addrToValue(obj_addr));
}
}
fn execNot(self: *Vm) !void {
const v = self.value_stack.pop();
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
if (!value.isBool(v)) return self.ctx.err(
"Logical not only works on booleans, got: {s}",
.{value.typeOf(v)},
error.InvalidNot,
offset,
);
try self.value_stack.append(value.boolToValue(!value.asBool(v).?));
}
fn execNeg(self: *Vm) !void {
const v = self.value_stack.pop();
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
if (value.asFloat(v)) |f| return self.value_stack.append(value.floatToValue(-f));
if (value.asInt(v)) |i| return self.value_stack.append(value.intToValue(-i));
if (value.asUint(v)) |u| return self.value_stack.append(value.floatToValue(-@intToFloat(f64, u)));
return self.ctx.err(
"Negation of non-number, got: {s}",
.{value.typeOf(v)},
error.InvalidNeg,
offset,
);
}
fn execList(self: *Vm) !void {
self.ip.* += 1;
const len = self.getU16(self.ip.*);
self.ip.* += 2;
var list = try std.ArrayList(Value).initCapacity(self.allocator, len);
if (len == 0) {
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .list = list };
const obj_addr = @ptrToInt(obj_ptr);
try self.value_stack.append(value.addrToValue(obj_addr));
return;
}
var i: usize = 0;
while (i < len) : (i += 1) list.appendAssumeCapacity(self.value_stack.pop());
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .list = list };
const obj_addr = @ptrToInt(obj_ptr);
try self.value_stack.append(value.addrToValue(obj_addr));
}
fn execMap(self: *Vm) !void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const len = self.getU16(self.ip.*);
self.ip.* += 2;
var map = std.StringHashMap(Value).init(self.allocator);
if (len == 0) {
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .map = map };
const obj_addr = @ptrToInt(obj_ptr);
try self.value_stack.append(value.addrToValue(obj_addr));
return;
}
try map.ensureTotalCapacity(len);
var i: usize = 0;
while (i < len) : (i += 1) {
const v = self.value_stack.pop();
const key = self.value_stack.pop();
if (!value.isAnyStr(key)) return self.ctx.err(
"Map keys must be strings, got: {s}",
.{value.typeOf(key)},
error.InvalidMapKey,
offset,
);
const key_str = if (value.unboxStr(key)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(key).?.string;
const key_copy = try map.allocator.dupe(u8, key_str);
map.putAssumeCapacity(key_copy, v);
}
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .map = map };
const obj_addr = @ptrToInt(obj_ptr);
try self.value_stack.append(value.addrToValue(obj_addr));
}
fn execSubscript(self: *Vm) !void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const container = self.value_stack.pop();
if (value.asList(container) == null and value.asMap(container) == null) return self.ctx.err(
"Subscript on non-container, got: {s}",
.{value.typeOf(container)},
error.InvalidSubscript,
offset,
);
return if (value.asList(container) != null)
try self.execSubscriptList(container, offset)
else
try self.execSubscriptMap(container, offset);
}
fn execSubscriptList(self: *Vm, list: Value, offset: u16) !void {
const index = self.value_stack.pop();
if (!value.isUint(index) and value.asRange(index) == null) return self.ctx.err(
"Invalid subscript index, got: {s}",
.{value.typeOf(index)},
error.InvalidSubscript,
offset,
);
const list_obj_ptr = value.asList(list).?;
if (value.asUint(index)) |index_u| {
if (index_u >= list_obj_ptr.list.items.len) return self.ctx.err(
"Index out of bounds.",
.{},
error.InvalidSubscript,
offset,
);
try self.value_stack.append(list_obj_ptr.list.items[index_u]);
} else {
const range_obj_ptr = value.asRange(index).?;
if (range_obj_ptr.range[1] > list_obj_ptr.list.items.len) return self.ctx.err(
"Range end out of bounds.",
.{},
error.InvalidSubscript,
offset,
);
var new_list = try std.ArrayList(Value).initCapacity(self.allocator, range_obj_ptr.range[1] - range_obj_ptr.range[0]);
for (list_obj_ptr.list.items[range_obj_ptr.range[0]..range_obj_ptr.range[1]]) |item|
new_list.appendAssumeCapacity(item);
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .list = new_list };
const obj_addr = @ptrToInt(obj_ptr);
try self.value_stack.append(value.addrToValue(obj_addr));
}
}
fn execSubscriptMap(self: *Vm, map: Value, offset: u16) !void {
const key = self.value_stack.pop();
if (!value.isAnyStr(key)) return self.ctx.err(
"Map keys must be strings, got: {s}",
.{value.typeOf(key)},
error.InvalidSubscript,
offset,
);
const key_str = if (value.unboxStr(key)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(key).?.string;
const map_obj_ptr = value.asMap(map).?;
const v = if (map_obj_ptr.map.get(key_str)) |vv| vv else value.val_nil;
try self.value_stack.append(v);
}
fn execSet(self: *Vm) !void {
const container = self.value_stack.pop();
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
// Combo assign
const combo = @intToEnum(Node.Combo, self.bytecode[self.ip.*]);
self.ip.* += 1;
if (value.asList(container) == null and value.asMap(container) == null) return self.ctx.err(
"Subscript assign on non-container, got: {s}",
.{value.typeOf(container)},
error.InvalidSubscript,
offset,
);
return if (value.asList(container) != null)
try self.execSetList(container, offset, combo)
else
try self.execSetMap(container, offset, combo);
}
fn execSetList(self: *Vm, list: Value, offset: u16, combo: Node.Combo) !void {
const index = self.value_stack.pop();
const index_u = value.asUint(index) orelse return self.ctx.err(
"List subscript must be unsigned integer, got: {s}",
.{value.typeOf(index)},
error.InvalidSubscript,
offset,
);
const list_obj_ptr = value.asList(list).?;
if (index_u >= list_obj_ptr.list.items.len) return self.ctx.err(
"Index out of bounds.",
.{},
error.InvalidSubscript,
offset,
);
const rvalue = self.value_stack.pop();
// Store
if (combo == .none) {
list_obj_ptr.list.items[index_u] = rvalue;
try self.value_stack.append(rvalue);
} else {
const old_value = list_obj_ptr.list.items[index_u];
const new_value = switch (combo) {
.none => unreachable,
.add => try value.add(old_value, rvalue),
.sub => try value.sub(old_value, rvalue),
.mul => try value.mul(old_value, rvalue),
.div => try value.div(old_value, rvalue),
.mod => try value.mod(old_value, rvalue),
};
list_obj_ptr.list.items[index_u] = new_value;
try self.value_stack.append(new_value);
}
}
fn execSetMap(self: *Vm, map: Value, offset: u16, combo: Node.Combo) !void {
const key = self.value_stack.pop();
if (!value.isAnyStr(key)) return self.ctx.err(
"Map keys must be strings, got: {s}",
.{value.typeOf(key)},
error.InvalidSubscript,
offset,
);
const rvalue = self.value_stack.pop();
const key_str = if (value.unboxStr(key)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(key).?.string;
const map_obj_ptr = value.asMap(map).?;
const key_copy = try map_obj_ptr.map.allocator.dupe(u8, key_str);
// Store
if (combo == .none) {
try map_obj_ptr.map.put(key_copy, try value.copy(rvalue, map_obj_ptr.map.allocator));
try self.value_stack.append(rvalue);
} else {
const old_value = map_obj_ptr.map.get(key_str) orelse value.uintToValue(0);
const new_value = switch (combo) {
.none => unreachable,
.add => try value.add(old_value, rvalue),
.sub => try value.sub(old_value, rvalue),
.mul => try value.mul(old_value, rvalue),
.div => try value.div(old_value, rvalue),
.mod => try value.mod(old_value, rvalue),
};
try map_obj_ptr.map.put(key_copy, try value.copy(new_value, map_obj_ptr.map.allocator));
try self.value_stack.append(new_value);
}
}
fn execJump(self: *Vm) void {
self.ip.* += 1;
const index = self.getU16(self.ip.*);
self.ip.* = index;
}
fn execJumpFalse(self: *Vm) void {
const condition = self.value_stack.pop();
if (!isTruthy(condition)) self.execJump() else self.ip.* += 3;
}
fn execJumpTrue(self: *Vm) void {
const condition = self.value_stack.pop();
if (isTruthy(condition)) self.execJump() else self.ip.* += 3;
}
fn execRange(self: *Vm) anyerror!void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const inclusive = self.bytecode[self.ip.*] == 1;
self.ip.* += 1;
const to = self.value_stack.pop();
const from = self.value_stack.pop();
if (!value.isUint(from) or !value.isUint(to)) return self.ctx.err(
"Invalid range.",
.{},
error.InvalidRange,
offset,
);
const from_uint = value.asUint(from).?;
var to_uint = value.asUint(to).?;
if (inclusive) to_uint += 1;
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .range = [2]u32{ from_uint, to_uint } };
const obj_addr = @ptrToInt(obj_ptr);
try self.value_stack.append(value.addrToValue(obj_addr));
}
fn execRecRange(self: *Vm) anyerror!void {
self.ip.* += 1;
const range_id = self.bytecode[self.ip.*];
self.ip.* += 1;
const exclusive = self.bytecode[self.ip.*] == 1;
self.ip.* += 1;
const len = self.getU16(self.ip.*);
self.ip.* += 2;
const action_bytecode = if (len != 0) self.bytecode[self.ip.* .. self.ip.* + len] else "";
self.ip.* += len;
const has_from = self.bytecode[self.ip.*] == 1;
self.ip.* += 1;
const has_to = self.bytecode[self.ip.*] == 1;
self.ip.* += 1;
const from = if (has_from) self.value_stack.pop() else value.val_nil;
const to = if (has_to) self.value_stack.pop() else value.val_nil;
var result = value.val_nil;
var exec_action = false;
if (self.scope_stack.rec_ranges.contains(range_id)) {
// In range
exec_action = true;
if (isTruthy(to)) {
// Range end.
_ = self.scope_stack.rec_ranges.remove(range_id);
if (exclusive) exec_action = false;
}
} else {
// Not in range
var start_range = false;
if (from != value.val_nil) {
// We have from
start_range = isTruthy(from);
} else {
// No from; start only at row == 1.
const rnum = value.asUint(self.scope_stack.rnum).?;
start_range = rnum == 1;
}
if (start_range) {
// We start a new range.
try self.scope_stack.rec_ranges.put(range_id, {});
exec_action = true;
}
}
if (exec_action) {
if (len != 0) {
var vm = try init(
self.allocator,
action_bytecode,
self.scope_stack,
self.ctx,
self.output,
);
try vm.run();
result = vm.last_popped;
} else {
// Default action
var writer = self.output.writer();
try value.print(self.scope_stack.record, writer);
}
}
try self.value_stack.append(result);
}
fn execMatch(self: *Vm, opcode: Compiler.Opcode) !void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const right = self.value_stack.pop();
if (!value.isAnyStr(right)) return self.ctx.err(
"Match op right hand side must be a regex pattern string; got {s}",
.{value.typeOf(right)},
error.InvalidMatch,
offset,
);
const pattern = if (value.unboxStr(right)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(right).?.string;
const pattern_copy = try self.scope_stack.allocator.dupe(u8, pattern);
// Check if code isn't cached.
const code_gop = try self.scope_stack.regex_cache.getOrPut(pattern_copy);
if (!code_gop.found_existing) {
// Compile it
code_gop.value_ptr.* = p2z.compile(pattern_copy, .{}) catch |err| return self.ctx.err(
"Could not compile regex pattern: {s}",
.{pattern},
err,
offset,
);
_ = code_gop.value_ptr.jitCompile(0);
}
const left = self.value_stack.pop();
if (!value.isAnyStr(left)) return self.ctx.err(
"Match op left hand side must be a string; got {s}",
.{value.typeOf(left)},
error.InvalidMatch,
offset,
);
const subject = if (value.unboxStr(left)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(left).?.string;
var data = try p2z.MatchData.init(code_gop.value_ptr.*);
defer data.deinit();
var matches = try p2z.match(
code_gop.value_ptr.*,
subject,
0,
&data,
.{},
);
if (opcode == .nomatch) matches = !matches;
try self.value_stack.append(value.boolToValue(matches));
}
fn execMatcher(self: *Vm) !void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const right = self.value_stack.pop();
if (!value.isAnyStr(right)) return self.ctx.err(
"Matcher op right hand side must be a regex pattern string; got {s}",
.{value.typeOf(right)},
error.InvalidMatcher,
offset,
);
const pattern = if (value.unboxStr(right)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(right).?.string;
const left = self.value_stack.pop();
if (!value.isAnyStr(left)) return self.ctx.err(
"Matcher op left hand side must be a string; got {s}",
.{value.typeOf(left)},
error.InvalidMatcher,
offset,
);
const subject = if (value.unboxStr(left)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(left).?.string;
// Check for cached result.
const subpat = try self.allocator.alloc(u8, pattern.len + subject.len);
std.mem.copy(u8, subpat, subject);
std.mem.copy(u8, subpat[subject.len..], pattern);
if (self.scope_stack.value_cache.get(subpat)) |v| {
try self.value_stack.append(v);
return;
}
// Check if code isn't cached.
const code_gop = try self.scope_stack.regex_cache.getOrPut(pattern);
if (!code_gop.found_existing) {
// Compile and cache it.
code_gop.value_ptr.* = p2z.compile(pattern, .{}) catch |err| return self.ctx.err(
"Could not compile regex pattern: {s}",
.{pattern},
err,
offset,
);
_ = code_gop.value_ptr.jitCompile(0);
}
var data = try p2z.MatchData.init(code_gop.value_ptr.*);
errdefer data.deinit();
var matches = try p2z.match(
code_gop.value_ptr.*,
subject,
0,
&data,
.{},
);
if (matches) {
const obj_ptr = try self.scope_stack.allocator.create(value.Object);
obj_ptr.* = .{ .matcher = p2z.MatchIterator.init(
code_gop.value_ptr.*,
data,
try self.scope_stack.allocator.dupe(u8, subject),
) };
const v = value.addrToValue(@ptrToInt(obj_ptr));
// Cache the result.
const subpat_copy = try self.scope_stack.allocator.dupe(u8, subpat);
try self.scope_stack.value_cache.put(subpat_copy, v);
// Put it on the stack too.
try self.value_stack.append(v);
} else {
// This is false instead of nil so that record ranges without a from clause can still work.
try self.value_stack.append(value.val_false);
}
}
fn execCapture(self: *Vm) !void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 3;
const m = self.value_stack.pop();
const matcher_obj_ptr = value.asMatcher(m) orelse return self.ctx.err(
"`capture` only works on regex matchers; got {s}",
.{value.typeOf(m)},
error.InvalidCapture,
offset,
);
const arg = self.value_stack.pop();
if (value.isAnyStr(arg)) {
// Named capture
const name = if (value.unboxStr(arg)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(arg).?.string;
if (p2z.namedCapture(
matcher_obj_ptr.matcher.code,
matcher_obj_ptr.matcher.data,
matcher_obj_ptr.matcher.subject,
name,
)) |substring| {
if (substring.len < 7) {
try self.value_stack.append(value.strToValue(substring));
} else {
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .string = substring };
const obj_addr = @ptrToInt(obj_ptr);
try self.value_stack.append(value.addrToValue(obj_addr));
}
} else {
// No capture with that nae found.
try self.value_stack.append(value.val_nil);
}
} else if (value.asUint(arg)) |u| {
// Numbered captue
if (p2z.numberedCapture(
matcher_obj_ptr.matcher.data,
matcher_obj_ptr.matcher.subject,
@intCast(u16, u),
)) |substring| {
if (substring.len < 7) {
try self.value_stack.append(value.strToValue(substring));
} else {
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .string = substring };
const obj_addr = @ptrToInt(obj_ptr);
try self.value_stack.append(value.addrToValue(obj_addr));
}
} else {
// No capture with that number found.
try self.value_stack.append(value.val_nil);
}
} else return self.ctx.err(
"`capture` arg must be a string or unsigned integer; got {s}",
.{value.typeOf(arg)},
error.InvalidCapture,
offset,
);
}
fn execNext(self: *Vm) !void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 3;
const m = self.value_stack.pop();
const matcher_obj_ptr = value.asMatcher(m) orelse return self.ctx.err(
"`next` only works on regex matchers; got {s}",
.{value.typeOf(m)},
error.InvalidNext,
offset,
);
try self.value_stack.append(value.boolToValue(try matcher_obj_ptr.matcher.next()));
}
fn execReset(self: *Vm) !void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 3;
const m = self.value_stack.pop();
const matcher_obj_ptr = value.asMatcher(m) orelse return self.ctx.err(
"`reset` only works on regex matchers; got {s}",
.{value.typeOf(m)},
error.InvalidNext,
offset,
);
matcher_obj_ptr.matcher.reset();
try self.value_stack.append(m);
}
fn execEachMatcher(self: *Vm, match_obj_ptr: *value.Object, offset: u16) !void {
const f = self.value_stack.pop();
const func_obj_ptr = value.asFunc(f) orelse return self.ctx.err(
"`each` arg must be a function, got: {s}",
.{value.typeOf(f)},
error.InvalidEach,
offset,
);
// No-ops
const matcher_val = value.addrToValue(@ptrToInt(match_obj_ptr));
if (func_obj_ptr.func.bytecode == null) {
try self.value_stack.append(matcher_val);
self.ip.* += 1;
return;
}
var i: u32 = 0;
while (try match_obj_ptr.matcher.next()) : (i += 1) _ = try self.execMatchPredicate(func_obj_ptr, matcher_val, value.uintToValue(i));
// Reset to the first match.
match_obj_ptr.matcher.reset();
try self.value_stack.append(value.addrToValue(matcher_val));
self.ip.* += 1;
}
// Stack Frame
const Frame = struct {
bytecode: []const u8,
ip: u16 = 0,
};
fn pushFrame(self: *Vm, bytecode: []const u8) !void {
try self.frame_stack.append(.{ .bytecode = bytecode });
self.bytecode = bytecode;
self.ip = &self.frame_stack.items[self.frame_stack.items.len - 1].ip;
}
fn popFrame(self: *Vm) void {
_ = self.frame_stack.pop();
self.bytecode = self.frame_stack.items[self.frame_stack.items.len - 1].bytecode;
self.ip = &self.frame_stack.items[self.frame_stack.items.len - 1].ip;
}
// Scopes
fn execScopeIn(self: *Vm) anyerror!void {
const child_scope_type = @intToEnum(Scope.Type, self.bytecode[self.ip.* + 1]);
try self.pushScope(Scope.init(self.allocator, child_scope_type));
self.ip.* += 2;
}
fn execScopeOut(self: *Vm) anyerror!void {
const scope_type = @intToEnum(Scope.Type, self.bytecode[self.ip.* + 1]);
if (scope_type == .loop) {
while (true) {
var popped_scope = self.popScope();
popped_scope.map.deinit();
if (popped_scope.ty == .loop) break;
}
} else {
var popped_scope = self.popScope();
popped_scope.map.deinit();
}
self.ip.* += 2;
}
// Builtins
fn execAssert(self: *Vm) anyerror!void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
// Get args count.
const num_args = self.bytecode[self.ip.*];
self.ip.* += 1;
if (num_args != 1) return self.ctx.err(
"`assert` requires 1 arguments.",
.{},
error.InvalidAssert,
offset,
);
const b = self.value_stack.pop();
if (!value.isBool(b)) return self.ctx.err(
"assert arg not a boolean expression; got {s}",
.{value.typeOf(b)},
error.InvalidAssert,
offset,
);
if (b == value.val_false) return self.ctx.err(
"assertion failed",
.{},
error.AssertFailed,
offset,
);
try self.value_stack.append(value.val_true);
}
fn execAtan2(self: *Vm) anyerror!void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
// Get args count.
const num_args = self.bytecode[self.ip.*];
self.ip.* += 1;
if (num_args != 2) return self.ctx.err(
"atan2 requires 2 arguments.",
.{},
error.InvalidAtan2,
offset,
);
const y_val = self.value_stack.pop();
const y = value.toFloat(y_val) orelse return self.ctx.err(
"atan2 y not convertible to float, got: {s}",
.{value.typeOf(y_val)},
error.InvalidAtan2,
offset,
);
const x_val = self.value_stack.pop();
const x = value.toFloat(x_val) orelse return self.ctx.err(
"atan2 x not convertible to float, got {s}",
.{value.typeOf(x_val)},
error.InvalidAtan2,
offset,
);
const result = value.floatToValue(std.math.atan2(f64, y, x));
try self.value_stack.append(result);
}
fn execChars(self: *Vm) anyerror!void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const str = self.value_stack.pop();
if (!value.isAnyStr(str)) return self.ctx.err(
"`chars` method only works on strings, got: {s}",
.{value.typeOf(str)},
error.InvalidCharsCall,
offset,
);
const str_str = if (value.unboxStr(str)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(str).?.string;
var list = std.ArrayList(Value).init(self.allocator);
var giter = GraphemeIterator.init(str_str) catch |err| return self.ctx.err(
"Unicode error.",
.{},
err,
offset,
);
while (giter.next()) |grapheme| {
if (grapheme.bytes.len < 7) {
try list.append(value.strToValue(grapheme.bytes));
} else {
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .string = grapheme.bytes };
const obj_addr = @ptrToInt(obj_ptr);
try list.append(value.addrToValue(obj_addr));
}
}
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .list = list };
const obj_addr = @ptrToInt(obj_ptr);
try self.value_stack.append(value.addrToValue(obj_addr));
self.ip.* += 1;
}
fn execPrint(self: *Vm) anyerror!void {
self.ip.* += 3; // Func calls get offset.
// Get args count.
const num_args = self.bytecode[self.ip.*];
self.ip.* += 1;
var writer = self.output.writer();
var i: usize = 0;
while (i < num_args) : (i += 1) {
if (i != 0) try value.print(self.scope_stack.ocs, writer);
try value.print(self.value_stack.pop(), writer);
}
try self.value_stack.append(value.val_nil);
}
fn execSprint(self: *Vm) anyerror!void {
self.ip.* += 3;
// Get args count.
const num_args = self.bytecode[self.ip.*];
self.ip.* += 1;
var buf = std.ArrayList(u8).init(self.allocator);
var writer = buf.writer();
var i: usize = 0;
while (i < num_args) : (i += 1) {
if (i != 0) try value.print(self.scope_stack.ocs, writer);
try value.print(self.value_stack.pop(), writer);
}
if (buf.items.len < 7) {
try self.value_stack.append(value.strToValue(buf.items));
} else {
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .string = buf.items };
const obj_addr = @ptrToInt(obj_ptr);
try self.value_stack.append(value.addrToValue(obj_addr));
}
}
fn execOneArgMath(self: *Vm, builtin: Token.Tag) anyerror!void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
// Get args count.
const num_args = self.bytecode[self.ip.*];
self.ip.* += 1;
if (num_args != 1) return self.ctx.err(
"Math builtin call requires one argument.",
.{},
error.InvalidMathBuiltin,
offset,
);
const x_val = self.value_stack.pop();
const x = value.toFloat(x_val) orelse return self.ctx.err(
"Arg not convertible to float, got: {s}",
.{value.typeOf(x_val)},
error.InvalidArg,
offset,
);
const result = switch (builtin) {
.pd_cos => value.floatToValue(@cos(x)),
.pd_exp => value.floatToValue(std.math.exp(x)),
.pd_int => value.intToValue(@floatToInt(i32, @trunc(x))),
.pd_log => value.floatToValue(@log(x)),
.pd_rand => value.uintToValue(std.rand.DefaultPrng.init(@intCast(usize, std.time.timestamp())).random().uintAtMost(u32, @floatToInt(u32, x))),
.pd_sin => value.floatToValue(@sin(x)),
.pd_sqrt => value.floatToValue(@sqrt(x)),
else => unreachable,
};
try self.value_stack.append(result);
}
fn execContains(self: *Vm) anyerror!void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const haystack = self.value_stack.pop();
if (!value.isAnyStr(haystack) and value.asList(haystack) == null) return self.ctx.err(
"`contains` only works on strings and lists, got: {s}.",
.{value.typeOf(haystack)},
error.InvalidContains,
offset,
);
const needle = self.value_stack.pop();
var result = false;
if (value.asList(haystack)) |list_obj_ptr| {
for (list_obj_ptr.list.items) |item| {
if (value.eql(item, needle)) result = true;
}
} else {
if (!value.isAnyStr(needle)) return self.ctx.err(
"`contains` arg on string must be a string, got {s}",
.{value.typeOf(needle)},
error.InvalidContains,
offset,
);
const hay_str = if (value.unboxStr(haystack)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(haystack).?.string;
const needle_str = if (value.unboxStr(needle)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(needle).?.string;
result = std.mem.containsAtLeast(u8, hay_str, 1, needle_str);
}
try self.value_stack.append(value.boolToValue(result));
self.ip.* += 1;
}
fn execIndexOf(self: *Vm) anyerror!void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const haystack = self.value_stack.pop();
if (!value.isAnyStr(haystack) and value.asList(haystack) == null) return self.ctx.err(
"`indexOf` only works on strings and lists, got: {s}.",
.{value.typeOf(haystack)},
error.InvalidIndexOf,
offset,
);
const needle = self.value_stack.pop();
var result: ?usize = null;
if (value.asList(haystack)) |list_obj_ptr| {
for (list_obj_ptr.list.items) |item, i| {
if (value.eql(item, needle)) {
result = i;
break;
}
}
} else {
if (!value.isAnyStr(needle)) return self.ctx.err(
"`indexOf` arg on string must be a string, got: {s}",
.{value.typeOf(needle)},
error.InvalidContains,
offset,
);
const hay_str = if (value.unboxStr(haystack)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(haystack).?.string;
const needle_str = if (value.unboxStr(needle)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(needle).?.string;
var giter = try GraphemeIterator.init(hay_str);
var i: usize = 0;
while (giter.next()) |grapheme| : (i += 1) {
if (std.mem.eql(u8, grapheme.bytes, needle_str)) {
result = i;
break;
}
}
}
try self.value_stack.append(if (result) |idx| value.uintToValue(@intCast(u32, idx)) else value.val_nil);
self.ip.* += 1;
}
fn execLastIndexOf(self: *Vm) anyerror!void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const haystack = self.value_stack.pop();
if (!value.isAnyStr(haystack) and value.asList(haystack) == null) return self.ctx.err(
"`lastIndexOf` only works on strings and lists, got {s}",
.{value.typeOf(haystack)},
error.InvalidLastIndexOf,
offset,
);
const needle = self.value_stack.pop();
var result: ?usize = null;
if (value.asList(haystack)) |list_obj_ptr| {
const len = list_obj_ptr.list.items.len;
var i: usize = 1;
while (i <= list_obj_ptr.list.items.len) : (i += 1) {
if (value.eql(list_obj_ptr.list.items[len - i], (needle))) {
result = i;
break;
}
}
} else {
if (!value.isAnyStr(needle)) return self.ctx.err(
"`lastIndexOf` arg on string must be a string, got: {s}",
.{value.typeOf(needle)},
error.InvalidLastIndexOf,
offset,
);
const hay_str = if (value.unboxStr(haystack)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(haystack).?.string;
const needle_str = if (value.unboxStr(needle)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(needle).?.string;
var giter = try GraphemeIterator.init(hay_str);
var i: usize = 0;
while (giter.next()) |grapheme| : (i += 1) {
if (std.mem.eql(u8, grapheme.bytes, needle_str)) result = i;
}
}
try self.value_stack.append(if (result) |idx| value.uintToValue(@intCast(u32, idx)) else value.val_nil);
self.ip.* += 1;
}
fn execLen(self: *Vm) anyerror!void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const v = self.value_stack.pop();
if (value.asList(v) == null and value.asMap(v) == null and !value.isAnyStr(v)) return self.ctx.err(
"`len` only works on strings, lists, and maps, got {s}",
.{value.typeOf(v)},
error.InvalidLen,
offset,
);
var len: usize = 0;
if (value.asList(v)) |list_obj_ptr| {
len = list_obj_ptr.list.items.len;
} else if (value.asMap(v)) |map_obj_ptr| {
len = map_obj_ptr.map.count();
} else {
const str = if (value.unboxStr(v)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(v).?.string;
len = str.len;
}
try self.value_stack.append(value.uintToValue(@intCast(u32, len)));
self.ip.* += 1;
}
fn execMapKeys(self: *Vm) anyerror!void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const m = self.value_stack.pop();
const map_obj_ptr = value.asMap(m) orelse return self.ctx.err(
"`keys` only works on maps, got {s}",
.{value.typeOf(m)},
error.InvalidKeys,
offset,
);
const map_count = map_obj_ptr.map.count();
if (map_count == 0) {
var list = std.ArrayList(Value).init(self.allocator);
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .list = list };
const obj_addr = @ptrToInt(obj_ptr);
try self.value_stack.append(value.addrToValue(obj_addr));
self.ip.* += 1;
return;
}
var list = try std.ArrayList(Value).initCapacity(self.allocator, map_count);
var key_iter = map_obj_ptr.map.keyIterator();
while (key_iter.next()) |key| {
if (key.len < 7) {
try list.append(value.strToValue(key.*));
} else {
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .string = key.* };
const obj_addr = @ptrToInt(obj_ptr);
try list.append(value.addrToValue(obj_addr));
}
}
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .list = list };
const obj_addr = @ptrToInt(obj_ptr);
try self.value_stack.append(value.addrToValue(obj_addr));
self.ip.* += 1;
}
fn entryAsc(_: void, a: std.StringHashMap(Value).Entry, b: std.StringHashMap(Value).Entry) bool {
return value.cmp(a.value_ptr.*, b.value_ptr.*) catch unreachable == .lt;
}
fn entryDesc(_: void, a: std.StringHashMap(Value).Entry, b: std.StringHashMap(Value).Entry) bool {
return value.cmp(a.value_ptr.*, b.value_ptr.*) catch unreachable == .gt;
}
fn execMapKeysByValue(self: *Vm, asc: bool) anyerror!void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const m = self.value_stack.pop();
const map_obj_ptr = value.asMap(m) orelse return self.ctx.err(
"`keysByValueAsc` only works on maps, got: {s}",
.{value.typeOf(m)},
error.InvalidKeysByValueAsc,
offset,
);
const map_count = map_obj_ptr.map.count();
if (map_count == 0) {
var list = std.ArrayList(Value).init(self.allocator);
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .list = list };
const obj_addr = @ptrToInt(obj_ptr);
try self.value_stack.append(value.addrToValue(obj_addr));
self.ip.* += 1;
return;
}
var list = try std.ArrayList(Value).initCapacity(self.allocator, map_count);
var entries = try std.ArrayList(std.StringHashMap(Value).Entry).initCapacity(self.allocator, map_count);
defer entries.deinit();
var iter = map_obj_ptr.map.iterator();
while (iter.next()) |entry| entries.appendAssumeCapacity(entry);
if (asc) {
std.sort.sort(std.StringHashMap(Value).Entry, entries.items, {}, entryAsc);
} else {
std.sort.sort(std.StringHashMap(Value).Entry, entries.items, {}, entryDesc);
}
for (entries.items) |entry| {
if (entry.key_ptr.len < 7) {
list.appendAssumeCapacity(value.strToValue(entry.key_ptr.*));
} else {
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .string = entry.key_ptr.* };
const obj_addr = @ptrToInt(obj_ptr);
list.appendAssumeCapacity(value.addrToValue(obj_addr));
}
}
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .list = list };
const obj_addr = @ptrToInt(obj_ptr);
try self.value_stack.append(value.addrToValue(obj_addr));
self.ip.* += 1; // num_args
}
fn execMapValues(self: *Vm) anyerror!void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const m = self.value_stack.pop();
const map_obj_ptr = value.asMap(m) orelse return self.ctx.err(
"`values` only works on maps, got {s}",
.{value.typeOf(m)},
error.InvalidValues,
offset,
);
const map_count = map_obj_ptr.map.count();
if (map_count == 0) {
var list = std.ArrayList(Value).init(self.allocator);
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .list = list };
const obj_addr = @ptrToInt(obj_ptr);
try self.value_stack.append(value.addrToValue(obj_addr));
self.ip.* += 1;
return;
}
var list = try std.ArrayList(Value).initCapacity(self.allocator, map_count);
var value_iter = map_obj_ptr.map.valueIterator();
while (value_iter.next()) |ev| list.appendAssumeCapacity(ev.*);
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .list = list };
const obj_addr = @ptrToInt(obj_ptr);
try self.value_stack.append(value.addrToValue(obj_addr));
self.ip.* += 1;
}
fn listMeanHelper(list: std.ArrayList(Value)) f64 {
var sum: f64 = 0;
var count: f64 = 0;
for (list.items) |item| {
if (value.toFloat(item)) |f| {
sum += f;
count += 1;
}
}
return sum / count;
}
fn execListMean(self: *Vm) anyerror!void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const l = self.value_stack.pop();
const list_obj_ptr = value.asList(l) orelse return self.ctx.err(
"`mean` only works on lists, got: {s}",
.{value.typeOf(l)},
error.InvalidMean,
offset,
);
if (list_obj_ptr.list.items.len == 0) {
try self.value_stack.append(value.floatToValue(0));
self.ip.* += 1;
return;
}
try self.value_stack.append(value.floatToValue(listMeanHelper(list_obj_ptr.list)));
self.ip.* += 1;
}
fn execListMedian(self: *Vm) anyerror!void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const l = self.value_stack.pop();
const list_obj_ptr = value.asList(l) orelse return self.ctx.err(
"`median` only works on lists, got: {s}",
.{value.typeOf(l)},
error.InvalidMedian,
offset,
);
if (list_obj_ptr.list.items.len == 0) {
try self.value_stack.append(value.floatToValue(0));
self.ip.* += 1;
return;
}
var list_copy = try std.ArrayList(f64).initCapacity(self.allocator, list_obj_ptr.list.items.len);
for (list_obj_ptr.list.items) |item| {
if (value.toFloat(item)) |f| list_copy.appendAssumeCapacity(f);
}
std.sort.sort(f64, list_copy.items, {}, comptime std.sort.asc(f64));
var median: f64 = @intToFloat(f64, list_copy.items.len) + 1 / 2 - 1;
if (list_copy.items.len % 2 == 0) {
const mid = list_copy.items.len / 2 - 1;
median = (list_copy.items[mid] + list_copy.items[mid + 1]) / 2;
}
try self.value_stack.append(value.floatToValue(median));
self.ip.* += 1;
}
fn execListMode(self: *Vm) anyerror!void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const l = self.value_stack.pop();
const list_obj_ptr = value.asList(l) orelse return self.ctx.err(
"`mode` only works on lists, got: {s}",
.{value.typeOf(l)},
error.InvalidMode,
offset,
);
if (list_obj_ptr.list.items.len == 0) {
try self.value_stack.append(value.val_nil);
self.ip.* += 1;
return;
}
//TODO: Use arena to save memory.
var counts = std.StringHashMap(usize).init(self.allocator);
var key_buf: [4096]u8 = undefined;
for (list_obj_ptr.list.items) |item| {
if (value.toFloat(item)) |f| {
const key_str = try std.fmt.bufPrint(&key_buf, "{}", .{f});
var entry = try counts.getOrPut(try self.allocator.dupe(u8, key_str));
if (entry.found_existing) entry.value_ptr.* += 1 else entry.value_ptr.* = 1;
}
}
var iter = counts.iterator();
var highest: usize = 0;
while (iter.next()) |entry| {
if (entry.value_ptr.* > highest) highest = entry.value_ptr.*;
}
iter = counts.iterator();
var list = std.ArrayList(Value).init(self.allocator);
while (iter.next()) |entry| {
if (entry.value_ptr.* == highest) try list.append(value.floatToValue(std.fmt.parseFloat(f64, entry.key_ptr.*) catch unreachable));
}
std.sort.sort(Value, list.items, {}, value.asc);
const result = if (list.items.len == counts.count()) value.val_nil else blk: {
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .list = list };
const obj_addr = @ptrToInt(obj_ptr);
break :blk value.addrToValue(obj_addr);
};
try self.value_stack.append(result);
self.ip.* += 1;
}
fn execListStdev(self: *Vm) anyerror!void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const l = self.value_stack.pop();
const list_obj_ptr = value.asList(l) orelse return self.ctx.err(
"`stdev` only works on lists, got: {s}",
.{value.typeOf(l)},
error.InvalidStdev,
offset,
);
if (list_obj_ptr.list.items.len == 0) {
try self.value_stack.append(value.floatToValue(0));
self.ip.* += 1;
return;
}
const mean = listMeanHelper(list_obj_ptr.list);
var sum_of_squares: f64 = 0;
var count: f64 = 0;
for (list_obj_ptr.list.items) |item| {
if (value.toFloat(item)) |f| {
const diff = f - mean;
const square = diff * diff;
sum_of_squares += square;
count += 1;
}
}
const sos_by_count = sum_of_squares / count;
try self.value_stack.append(value.floatToValue(@sqrt(sos_by_count)));
self.ip.* += 1;
}
fn execListMin(self: *Vm) anyerror!void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const l = self.value_stack.pop();
const list_obj_ptr = value.asList(l) orelse return self.ctx.err(
"min only works on lists, got: {s}",
.{value.typeOf(l)},
error.InvalidMin,
offset,
);
if (list_obj_ptr.list.items.len == 0) {
try self.value_stack.append(value.val_nil);
self.ip.* += 1;
return;
}
var min = list_obj_ptr.list.items[0];
for (list_obj_ptr.list.items) |item| {
const comparison = try value.cmp(min, item);
if (comparison == .gt) min = item;
}
try self.value_stack.append(min);
self.ip.* += 1;
}
fn execListMax(self: *Vm) anyerror!void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const l = self.value_stack.pop();
const list_obj_ptr = value.asList(l) orelse return self.ctx.err(
"`max` only works on lists, got: {s}",
.{value.typeOf(l)},
error.InvalidMax,
offset,
);
if (list_obj_ptr.list.items.len == 0) {
try self.value_stack.append(value.val_nil);
self.ip.* += 1;
return;
}
var max = list_obj_ptr.list.items[0];
for (list_obj_ptr.list.items) |item| {
const comparison = try value.cmp(max, item);
if (comparison == .lt) max = item;
}
try self.value_stack.append(max);
self.ip.* += 1;
}
fn execListSort(self: *Vm, asc: bool) anyerror!void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const l = self.value_stack.pop();
const list_obj_ptr = value.asList(l) orelse return self.ctx.err(
"`listSortAsc` only works on lists, got: {s}",
.{value.typeOf(l)},
error.InvalidSortAsc,
offset,
);
if (list_obj_ptr.list.items.len == 0) {
try self.value_stack.append(l);
self.ip.* += 1;
return;
}
if (asc) {
std.sort.sort(Value, list_obj_ptr.list.items, {}, value.asc);
} else {
std.sort.sort(Value, list_obj_ptr.list.items, {}, value.desc);
}
try self.value_stack.append(l);
self.ip.* += 1;
}
fn execListReverse(self: *Vm) anyerror!void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const l = self.value_stack.pop();
const list_obj_ptr = value.asList(l) orelse return self.ctx.err(
"`reverse` only works on lists, got: {s}",
.{value.typeOf(l)},
error.InvalidReverse,
offset,
);
if (list_obj_ptr.list.items.len == 0) {
try self.value_stack.append(l);
self.ip.* += 1;
return;
}
std.mem.reverse(Value, list_obj_ptr.list.items);
try self.value_stack.append(l);
self.ip.* += 1;
}
fn execStrSplit(self: *Vm) anyerror!void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const str = self.value_stack.pop();
if (!value.isAnyStr(str)) return self.ctx.err(
"`split` only works on strings, got: {s}",
.{value.typeOf(str)},
error.InvalidSplit,
offset,
);
const delim = self.value_stack.pop();
if (!value.isAnyStr(delim)) return self.ctx.err(
"`split` delimiter must be a string, got: {s}",
.{value.typeOf(delim)},
error.InvalidSplit,
offset,
);
const str_str = if (value.unboxStr(str)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(str).?.string;
const delim_str = if (value.unboxStr(delim)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(delim).?.string;
var list = std.ArrayList(Value).init(self.allocator);
var iter = std.mem.split(u8, str_str, delim_str);
while (iter.next()) |sub| {
if (sub.len < 7) {
try list.append(value.strToValue(sub));
} else {
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .string = sub };
const obj_addr = @ptrToInt(obj_ptr);
try list.append(value.addrToValue(obj_addr));
}
}
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .list = list };
const obj_addr = @ptrToInt(obj_ptr);
try self.value_stack.append(value.addrToValue(obj_addr));
self.ip.* += 1;
}
fn execListJoin(self: *Vm) anyerror!void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const l = self.value_stack.pop();
const list_obj_ptr = value.asList(l) orelse return self.ctx.err(
"`join` only works on lists, got: {s}",
.{value.typeOf(l)},
error.InvalidJoin,
offset,
);
const delim = self.value_stack.pop();
if (!value.isAnyStr(delim)) return self.ctx.err(
"`join` delimiter must be a string, got: {s}",
.{value.typeOf(delim)},
error.InvalidJoin,
offset,
);
const str_delim = if (value.unboxStr(delim)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(delim).?.string;
var buf = std.ArrayList(u8).init(self.allocator);
var writer = buf.writer();
for (list_obj_ptr.list.items) |item, i| {
if (i != 0 and str_delim.len > 0) try buf.appendSlice(str_delim);
try value.print(item, writer);
}
if (buf.items.len < 7) {
try self.value_stack.append(value.strToValue(buf.items));
} else {
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .string = buf.items };
const obj_addr = @ptrToInt(obj_ptr);
try self.value_stack.append(value.addrToValue(obj_addr));
}
self.ip.* += 1;
}
fn execStrEndStart(self: *Vm, start: bool) anyerror!void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const str = self.value_stack.pop();
if (!value.isAnyStr(str)) return self.ctx.err(
"This method only works on strings, got: {s}",
.{value.typeOf(str)},
error.InvalidStrEnStart,
offset,
);
const needle = self.value_stack.pop();
if (!value.isAnyStr(needle)) return self.ctx.err(
"Arg must be a string, got: {s}",
.{value.typeOf(needle)},
error.InvalidXWith,
offset,
);
const str_str = if (value.unboxStr(str)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(str).?.string;
const str_needle = if (value.unboxStr(needle)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(needle).?.string;
var result: Value = undefined;
if (start) {
result = value.boolToValue(std.mem.startsWith(u8, str_str, str_needle));
} else {
result = value.boolToValue(std.mem.endsWith(u8, str_str, str_needle));
}
try self.value_stack.append(result);
self.ip.* += 1;
}
fn execMapMethod(self: *Vm) anyerror!void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const container = self.value_stack.pop();
if (value.asList(container)) |list_obj_ptr| {
return self.execMapList(list_obj_ptr, offset);
} else if (value.asRange(container)) |range_obj_ptr| {
return self.execMapRange(range_obj_ptr, offset);
} else return self.ctx.err(
"`map` only works on lists and ranges, got: {s}",
.{value.typeOf(container)},
error.InvalidMap,
offset,
);
}
fn execMapList(self: *Vm, list_obj_ptr: *value.Object, offset: u16) anyerror!void {
const f = self.value_stack.pop();
const func_obj_ptr = value.asFunc(f) orelse return self.ctx.err(
"`map` requres function argument, got: {s}",
.{value.typeOf(f)},
error.InvalidMap,
offset,
);
// No-ops
if (func_obj_ptr.func.bytecode == null or list_obj_ptr.list.items.len == 0) {
try self.value_stack.append(value.addrToValue(@ptrToInt(list_obj_ptr)));
self.ip.* += 1;
return;
}
var list = try std.ArrayList(Value).initCapacity(self.allocator, list_obj_ptr.list.items.len);
for (list_obj_ptr.list.items) |item, i| {
const v = try self.execListPredicate(func_obj_ptr, item, i);
list.appendAssumeCapacity(v);
}
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .list = list };
const obj_addr = @ptrToInt(obj_ptr);
try self.value_stack.append(value.addrToValue(obj_addr));
self.ip.* += 1;
}
fn execMapRange(self: *Vm, range_obj_ptr: *const value.Object, offset: u16) anyerror!void {
const f = self.value_stack.pop();
const func_obj_ptr = value.asFunc(f) orelse return self.ctx.err(
"`map` requres function argument, got {s}",
.{value.typeOf(f)},
error.InvalidMap,
offset,
);
// No-ops
if (func_obj_ptr.func.bytecode == null or range_obj_ptr.range[1] - range_obj_ptr.range[0] == 0) {
try self.value_stack.append(value.addrToValue(@ptrToInt(range_obj_ptr)));
self.ip.* += 1;
return;
}
var list = try std.ArrayList(Value).initCapacity(self.allocator, range_obj_ptr.range[1] - range_obj_ptr.range[0]);
var n = range_obj_ptr.range[0];
var i: u32 = 0;
while (n < range_obj_ptr.range[1]) : ({
n += 1;
i += 1;
}) {
const v = try self.execRangePredicate(func_obj_ptr, n, i);
list.appendAssumeCapacity(v);
}
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .list = list };
const obj_addr = @ptrToInt(obj_ptr);
try self.value_stack.append(value.addrToValue(obj_addr));
self.ip.* += 1;
}
fn execFilter(self: *Vm) anyerror!void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const container = self.value_stack.pop();
if (value.asList(container)) |list_obj_ptr| {
return self.execFilterList(list_obj_ptr, offset);
} else if (value.asRange(container)) |range_obj_ptr| {
return self.execFilterRange(range_obj_ptr, offset);
} else return self.ctx.err(
"`filter` only works on lists and ranges, got: {s}",
.{value.typeOf(container)},
error.InvalidFilter,
offset,
);
}
fn execFilterList(self: *Vm, list_obj_ptr: *const value.Object, offset: u16) !void {
const f = self.value_stack.pop();
const func_obj_ptr = value.asFunc(f) orelse return self.ctx.err(
"`filter` arg must be a function, got: {s}",
.{value.typeOf(f)},
error.InvalidFilter,
offset,
);
// No-ops
if (func_obj_ptr.func.bytecode == null or list_obj_ptr.list.items.len == 0) {
try self.value_stack.append(value.addrToValue(@ptrToInt(list_obj_ptr)));
self.ip.* += 1;
return;
}
var list = std.ArrayList(Value).init(self.allocator);
for (list_obj_ptr.list.items) |item, i| {
const v = try self.execListPredicate(func_obj_ptr, item, i);
if (isTruthy(v)) try list.append(item);
}
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .list = list };
const obj_addr = @ptrToInt(obj_ptr);
try self.value_stack.append(value.addrToValue(obj_addr));
self.ip.* += 1;
}
fn execFilterRange(self: *Vm, range_obj_ptr: *const value.Object, offset: u16) !void {
const f = self.value_stack.pop();
const func_obj_ptr = value.asFunc(f) orelse return self.ctx.err(
"`filter` arg must be a function, got: {s}",
.{value.typeOf(f)},
error.InvalidFilter,
offset,
);
var list = std.ArrayList(Value).init(self.allocator);
// No-ops
if (func_obj_ptr.func.bytecode == null or range_obj_ptr.range[1] - range_obj_ptr.range[0] == 0) {
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .list = list };
const obj_addr = @ptrToInt(obj_ptr);
try self.value_stack.append(value.addrToValue(obj_addr));
self.ip.* += 1;
return;
}
var n = range_obj_ptr.range[0];
var i: u32 = 0;
while (n < range_obj_ptr.range[1]) : ({
n += 1;
i += 1;
}) {
const v = try self.execRangePredicate(func_obj_ptr, n, i);
if (isTruthy(v)) try list.append(value.uintToValue(n));
}
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .list = list };
const obj_addr = @ptrToInt(obj_ptr);
try self.value_stack.append(value.addrToValue(obj_addr));
self.ip.* += 1;
}
fn execEach(self: *Vm) anyerror!void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const container = self.value_stack.pop();
if (value.asList(container)) |list_obj_ptr| {
return self.execEachList(list_obj_ptr, offset);
} else if (value.asMap(container)) |map_obj_ptr| {
return self.execEachMap(map_obj_ptr, offset);
} else if (value.asMatcher(container)) |matcher_obj_ptr| {
return self.execEachMatcher(matcher_obj_ptr, offset);
} else if (value.asRange(container)) |range_obj_ptr| {
return self.execEachRange(range_obj_ptr, offset);
} else return self.ctx.err(
"`each` only works on lists, maps, ranges, and regex matches, got {s}",
.{value.typeOf(container)},
error.InvalidEach,
offset,
);
}
fn execEachList(self: *Vm, list_obj_ptr: *value.Object, offset: u16) !void {
const f = self.value_stack.pop();
const func_obj_ptr = value.asFunc(f) orelse return self.ctx.err(
"`each` arg must be a function, got: {s}",
.{value.typeOf(f)},
error.InvalidEach,
offset,
);
// No-ops
const obj_addr = @ptrToInt(list_obj_ptr);
if (func_obj_ptr.func.bytecode == null or list_obj_ptr.list.items.len == 0) {
try self.value_stack.append(value.addrToValue(obj_addr));
self.ip.* += 1;
return;
}
for (list_obj_ptr.list.items) |item, i| _ = try self.execListPredicate(func_obj_ptr, item, i);
try self.value_stack.append(value.addrToValue(obj_addr));
self.ip.* += 1;
}
fn execEachMap(self: *Vm, map_obj_ptr: *value.Object, offset: u16) !void {
const f = self.value_stack.pop();
const func_obj_ptr = value.asFunc(f) orelse return self.ctx.err(
"`each` arg must be a function, got: {s}",
.{value.typeOf(f)},
error.InvalidEach,
offset,
);
// No-ops
const obj_addr = @ptrToInt(map_obj_ptr);
if (func_obj_ptr.func.bytecode == null or map_obj_ptr.map.count() == 0) {
try self.value_stack.append(value.addrToValue(obj_addr));
self.ip.* += 1;
return;
}
var iter = map_obj_ptr.map.iterator();
var i: usize = 0;
while (iter.next()) |entry| : (i += 1) _ = try self.execMapPredicate(func_obj_ptr, entry.key_ptr.*, entry.value_ptr.*, i);
try self.value_stack.append(value.addrToValue(obj_addr));
self.ip.* += 1;
}
fn execEachRange(self: *Vm, range_obj_ptr: *const value.Object, offset: u16) !void {
const f = self.value_stack.pop();
const func_obj_ptr = value.asFunc(f) orelse return self.ctx.err(
"`each` arg must be a function, got: {s}",
.{value.typeOf(f)},
error.InvalidEach,
offset,
);
// No-ops
const obj_addr = @ptrToInt(range_obj_ptr);
if (func_obj_ptr.func.bytecode == null or range_obj_ptr.range[1] - range_obj_ptr.range[0] == 0) {
try self.value_stack.append(value.addrToValue(obj_addr));
self.ip.* += 1;
return;
}
var n = range_obj_ptr.range[0];
var i: u32 = 0;
while (n < range_obj_ptr.range[1]) : ({
n += 1;
i += 1;
}) _ = try self.execRangePredicate(func_obj_ptr, n, i);
try self.value_stack.append(value.addrToValue(obj_addr));
self.ip.* += 1;
}
fn execReduce(self: *Vm) anyerror!void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const container = self.value_stack.pop();
if (value.asList(container)) |list_obj_ptr| {
return self.execReduceList(list_obj_ptr, offset);
} else if (value.asRange(container)) |range_obj_ptr| {
return self.execReduceRange(range_obj_ptr, offset);
} else return self.ctx.err(
"`reduce` only works on lists and ranges, got {s}",
.{value.typeOf(container)},
error.InvalidEach,
offset,
);
}
fn execReduceList(self: *Vm, list_obj_ptr: *value.Object, offset: u16) anyerror!void {
var acc = self.value_stack.pop();
const f = self.value_stack.pop();
const func_obj_ptr = value.asFunc(f) orelse return self.ctx.err(
"`reduce` last arg must be a function, got: {s}",
.{value.typeOf(f)},
error.InvalidReduce,
offset,
);
// No-ops
if (func_obj_ptr.func.bytecode == null or list_obj_ptr.list.items.len == 0) {
try self.value_stack.append(value.val_nil);
self.ip.* += 1;
return;
}
for (list_obj_ptr.list.items) |item, i| {
// Set up function scope.
var func_scope = Scope.init(self.allocator, .function);
defer func_scope.map.deinit();
// Assign args as locals in function scope.
try func_scope.map.put("acc", acc);
try func_scope.map.put("it", item);
try func_scope.map.put("@0", item);
try func_scope.map.put("index", value.uintToValue(@intCast(u32, i)));
if (func_obj_ptr.func.params) |params| {
if (params.len > 0) try func_scope.map.put(std.mem.sliceTo(self.bytecode[params[0]..], 0), acc);
if (params.len > 1) try func_scope.map.put(std.mem.sliceTo(self.bytecode[params[1]..], 0), item);
}
try self.pushScope(func_scope);
acc = try self.execPredicate(func_obj_ptr.func.bytecode.?);
_ = self.popScope();
}
try self.value_stack.append(acc);
self.ip.* += 1;
}
fn execReduceRange(self: *Vm, range_obj_ptr: *const value.Object, offset: u16) anyerror!void {
var acc = self.value_stack.pop();
const f = self.value_stack.pop();
const func_obj_ptr = value.asFunc(f) orelse return self.ctx.err(
"`reduce` last arg must be a function, got: {s}",
.{value.typeOf(f)},
error.InvalidReduce,
offset,
);
// No-ops
if (func_obj_ptr.func.bytecode == null or range_obj_ptr.range[1] - range_obj_ptr.range[0] == 0) {
try self.value_stack.append(value.val_nil);
self.ip.* += 1;
return;
}
var n = range_obj_ptr.range[0];
var i: u32 = 0;
while (n < range_obj_ptr.range[1]) : ({
n += 1;
i += 1;
}) {
// Set up function scope.
var func_scope = Scope.init(self.allocator, .function);
defer func_scope.map.deinit();
const n_val = value.uintToValue(n);
const i_val = value.uintToValue(i);
// Assign args as locals in function scope.
try func_scope.map.put("acc", acc);
try func_scope.map.put("it", n_val);
try func_scope.map.put("@0", n_val);
try func_scope.map.put("index", i_val);
if (func_obj_ptr.func.params) |params| {
if (params.len > 0) try func_scope.map.put(std.mem.sliceTo(self.bytecode[params[0]..], 0), acc);
if (params.len > 1) try func_scope.map.put(std.mem.sliceTo(self.bytecode[params[1]..], 0), n_val);
if (params.len > 2) try func_scope.map.put(std.mem.sliceTo(self.bytecode[params[2]..], 0), i_val);
}
try self.pushScope(func_scope);
acc = try self.execPredicate(func_obj_ptr.func.bytecode.?);
_ = self.popScope();
}
try self.value_stack.append(acc);
self.ip.* += 1;
}
fn execRand(self: *Vm) anyerror!void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
// Get args count.
const num_args = self.bytecode[self.ip.*];
self.ip.* += 1;
if (num_args != 1) return self.ctx.err(
"`rand` requires a single argument.",
.{},
error.InvalidRand,
offset,
);
const x_val = self.value_stack.pop();
const x = value.asUint(x_val) orelse return self.ctx.err(
"rand argument must be unsigned integer, got: {s}",
.{value.typeOf(x_val)},
error.InvalidRand,
offset,
);
const result = value.uintToValue(std.rand.DefaultPrng.init(@intCast(usize, std.time.timestamp())).random().uintAtMost(u32, x));
try self.value_stack.append(result);
}
fn execListPush(self: *Vm) anyerror!void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const l = self.value_stack.pop();
const list_obj_ptr = value.asList(l) orelse return self.ctx.err(
"`push` only works on lists, got {s}",
.{value.typeOf(l)},
error.InvalidPush,
offset,
);
var item = self.value_stack.pop();
try list_obj_ptr.list.append(try value.copy(item, list_obj_ptr.list.allocator));
try self.value_stack.append(l);
self.ip.* += 1;
}
fn execListPop(self: *Vm) anyerror!void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const l = self.value_stack.pop();
const list_obj_ptr = value.asList(l) orelse return self.ctx.err(
"`pop` only works on lists, got {s}",
.{value.typeOf(l)},
error.InvalidPop,
offset,
);
try self.value_stack.append(list_obj_ptr.list.pop());
self.ip.* += 1;
}
fn execMatchPredicate(
self: *Vm,
func_obj_ptr: *value.Object,
matcher_val: value.Value,
match_index_val: value.Value,
) anyerror!Value {
// Assign args as locals in function scope.
var func_scope = Scope.init(self.allocator, .function); //TODO: Can we use other allocator here?
defer func_scope.map.deinit();
try func_scope.map.put("it", matcher_val);
try func_scope.map.put("@0", matcher_val);
try func_scope.map.put("index", match_index_val);
if (func_obj_ptr.func.params) |params| {
if (params.len > 0) try func_scope.map.put(std.mem.sliceTo(self.bytecode[params[0]..], 0), matcher_val);
if (params.len > 1) try func_scope.map.put(std.mem.sliceTo(self.bytecode[params[1]..], 0), match_index_val);
}
try self.pushScope(func_scope);
const result = self.execPredicate(func_obj_ptr.func.bytecode.?);
_ = self.popScope();
return result;
}
fn execListPredicate(self: *Vm, func_obj_ptr: *value.Object, item: Value, index: usize) anyerror!Value {
// Assign args as locals in function scope.
var func_scope = Scope.init(self.allocator, .function); //TODO: Can we use other allocator here?
defer func_scope.map.deinit();
const index_val = value.uintToValue(@intCast(u32, index));
try func_scope.map.put("it", item);
try func_scope.map.put("@0", item);
try func_scope.map.put("index", index_val);
if (func_obj_ptr.func.params) |params| {
if (params.len > 0) try func_scope.map.put(std.mem.sliceTo(self.bytecode[params[0]..], 0), item);
if (params.len > 1) try func_scope.map.put(std.mem.sliceTo(self.bytecode[params[1]..], 0), index_val);
}
try self.pushScope(func_scope);
const result = self.execPredicate(func_obj_ptr.func.bytecode.?);
_ = self.popScope();
return result;
}
fn execMapPredicate(self: *Vm, func_obj_ptr: *value.Object, key: []const u8, item: Value, index: usize) anyerror!Value {
// Assign args as locals in function scope.
var func_scope = Scope.init(self.allocator, .function);
defer func_scope.map.deinit();
var key_val: Value = undefined;
if (key.len < 7) {
key_val = value.strToValue(key);
} else {
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .string = key };
const obj_addr = @ptrToInt(obj_ptr);
key_val = value.addrToValue(obj_addr);
}
const index_val = value.uintToValue(@intCast(u32, index));
try func_scope.map.put("key", key_val);
try func_scope.map.put("value", item);
try func_scope.map.put("index", index_val);
if (func_obj_ptr.func.params) |params| {
if (params.len > 0) try func_scope.map.put(std.mem.sliceTo(self.bytecode[params[0]..], 0), key_val);
if (params.len > 1) try func_scope.map.put(std.mem.sliceTo(self.bytecode[params[1]..], 0), item);
if (params.len > 2) try func_scope.map.put(std.mem.sliceTo(self.bytecode[params[2]..], 0), index_val);
}
try self.pushScope(func_scope);
const result = self.execPredicate(func_obj_ptr.func.bytecode.?);
_ = self.popScope();
return result;
}
fn execRangePredicate(self: *Vm, func_obj_ptr: *value.Object, n: u32, i: u32) anyerror!Value {
// Assign args as locals in function scope.
var func_scope = Scope.init(self.allocator, .function); //TODO: Can we use other allocator here?
defer func_scope.map.deinit();
const n_val = value.uintToValue(n);
const i_val = value.uintToValue(i);
try func_scope.map.put("it", n_val);
try func_scope.map.put("@0", n_val);
try func_scope.map.put("index", i_val);
if (func_obj_ptr.func.params) |params| {
if (params.len > 0) try func_scope.map.put(std.mem.sliceTo(self.bytecode[params[0]..], 0), n_val);
if (params.len > 1) try func_scope.map.put(std.mem.sliceTo(self.bytecode[params[1]..], 0), i_val);
}
try self.pushScope(func_scope);
const result = self.execPredicate(func_obj_ptr.func.bytecode.?);
_ = self.popScope();
return result;
}
fn execPredicate(self: *Vm, bytecode: []const u8) anyerror!Value {
// Set up Sub-VM arena.
var vm_arena = std.heap.ArenaAllocator.init(self.allocator);
defer vm_arena.deinit();
const vm_allocator = vm_arena.allocator();
var vm = try init(
vm_allocator,
bytecode,
self.scope_stack,
self.ctx,
self.output,
);
try vm.run();
return try value.copy(vm.last_popped, self.allocator);
}
fn execRedir(self: *Vm) !void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const clobber = self.bytecode[self.ip.*] == 1;
self.ip.* += 1;
// Get filename
const filename = self.value_stack.pop();
if (!value.isAnyStr(filename)) return self.ctx.err(
"Redirection filename must be a string, got: {s}",
.{value.typeOf(filename)},
error.InvalidRedirect,
offset,
);
const str_filename = if (value.unboxStr(filename)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(filename).?.string;
// Open file
var create_flags: std.fs.File.CreateFlags = .{};
if (!clobber) create_flags.truncate = false;
var file = try std.fs.cwd().createFile(str_filename, create_flags);
defer file.close();
if (!clobber) try file.seekFromEnd(0);
// Buffering
var file_buf = std.io.bufferedWriter(file.writer());
var writer = file_buf.writer();
// Write
const v = self.value_stack.pop();
try value.print(v, writer);
try file_buf.flush();
try self.value_stack.append(v);
}
fn execStrCase(self: *Vm, lower: bool) !void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const s = self.value_stack.pop();
if (!value.isAnyStr(s)) return self.ctx.err(
"Case conversion only works on strings, got: {s}",
.{value.typeOf(s)},
error.InvalidToCase,
offset,
);
const str_str = if (value.unboxStr(s)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(s).?.string;
if (str_str.len == 0) {
try self.value_stack.append(s);
self.ip.* += 1;
return;
}
var new_str: []const u8 = undefined;
if (lower) {
new_str = try ziglyph.toLowerStr(self.allocator, str_str);
} else {
new_str = try ziglyph.toUpperStr(self.allocator, str_str);
}
if (new_str.len < 7) {
try self.value_stack.append(value.strToValue(new_str));
} else {
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .string = new_str };
const obj_addr = @ptrToInt(obj_ptr);
try self.value_stack.append(value.addrToValue(obj_addr));
}
self.ip.* += 1; // num_args
}
fn execUnique(self: *Vm) !void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const l = self.value_stack.pop();
const list_obj_ptr = value.asList(l) orelse return self.ctx.err(
"`unique` only works on lists, got: {s}",
.{value.typeOf(l)},
error.InvalidUnique,
offset,
);
var new_list = std.ArrayList(Value).init(self.allocator);
// No-op
if (list_obj_ptr.list.items.len == 0) {
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .list = new_list };
try self.value_stack.append(value.addrToValue(@ptrToInt(obj_ptr)));
self.ip.* += 1;
return;
}
var item_set = std.AutoArrayHashMap(Value, void).init(self.allocator);
defer item_set.deinit();
try item_set.ensureTotalCapacity(@intCast(u32, list_obj_ptr.list.items.len));
for (list_obj_ptr.list.items) |item| item_set.putAssumeCapacity(item, {});
for (item_set.keys()) |item| try new_list.append(item);
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .list = new_list };
try self.value_stack.append(value.addrToValue(@ptrToInt(obj_ptr)));
self.ip.* += 1; // num_args
}
fn execReplace(self: *Vm) !void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const num_args = self.bytecode[self.ip.*];
self.ip.* += 1;
if (num_args != 3) return self.ctx.err(
"`replace` requires two args",
.{},
error.InvalidReplace,
offset,
);
const str = self.value_stack.pop();
if (!value.isAnyStr(str)) return self.ctx.err(
"`replace` only works on strings, got: {s}",
.{value.typeOf(str)},
error.InvalidReplace,
offset,
);
const subject = if (value.unboxStr(str)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(str).?.string;
// No-op
if (subject.len == 0) {
try self.value_stack.append(str);
return;
}
const needle = self.value_stack.pop();
if (!value.isAnyStr(needle)) return self.ctx.err(
"`replace` needle must be a string, got: {s}",
.{value.typeOf(needle)},
error.InvalidReplace,
offset,
);
const needle_str = if (value.unboxStr(needle)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(needle).?.string;
// Check if code isn't cached.
const code_gop = try self.scope_stack.regex_cache.getOrPut(needle_str);
if (!code_gop.found_existing) {
// Compile it
const needle_copy = try self.allocator.dupe(u8, needle_str);
code_gop.value_ptr.* = p2z.compile(needle_copy, .{}) catch |err| return self.ctx.err(
"Could not compile regex pattern: {s}",
.{needle_str},
err,
offset,
);
_ = code_gop.value_ptr.jitCompile(0);
}
const rep = self.value_stack.pop();
if (!value.isAnyStr(rep)) return self.ctx.err(
"`replace` replacement must be a string, got: {s}",
.{value.typeOf(rep)},
error.InvalidReplace,
offset,
);
const rep_str = if (value.unboxStr(rep)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(rep).?.string;
var buf = try self.allocator.alloc(u8, subject.len * 2); //TODO: Better way to estimate this?
const new_str = try p2z.replace(
code_gop.value_ptr.*,
subject,
0,
rep_str,
buf,
.{ .bits = p2z.pcre2.PCRE2_SUBSTITUTE_GLOBAL },
);
if (new_str.len < 7) {
try self.value_stack.append(value.strToValue(new_str));
} else {
const obj_ptr = try self.allocator.create(value.Object);
obj_ptr.* = .{ .string = new_str };
const obj_addr = @ptrToInt(obj_ptr);
try self.value_stack.append(value.addrToValue(obj_addr));
}
}
fn execMemo(self: *Vm) anyerror!void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const f = self.value_stack.pop();
const func_obj_ptr = value.asFunc(f) orelse return self.ctx.err(
"`memo` only works on functions, got: {s}",
.{value.typeOf(f)},
error.InvalidMemo,
offset,
);
func_obj_ptr.func.memo = true;
try self.value_stack.append(f);
self.ip.* += 1;
}
fn execCol(self: *Vm) anyerror!void {
self.ip.* += 1;
const offset = self.getOffset();
self.ip.* += 2;
const idx = self.value_stack.pop();
if (value.asUint(idx)) |ui| {
return self.execColUint(ui, offset);
} else if (value.isAnyStr(idx)) {
return self.execColStr(idx, offset);
} else return self.ctx.err(
"`col` arg must be a sting or unsigned integer, got: {s}",
.{value.typeOf(idx)},
error.InvalidCol,
offset,
);
}
fn execColUint(self: *Vm, index: u32, offset: u16) !void {
const cols_ptr = value.asList(self.scope_stack.columns).?;
if (index >= cols_ptr.list.items.len) return self.ctx.err(
"Column index out of bounds.",
.{},
error.OutOfBounds,
offset,
);
try self.value_stack.append(cols_ptr.list.items[index]);
self.ip.* += 1;
}
fn execColStr(self: *Vm, index_val: Value, offset: u16) !void {
const header_str = if (value.asList(index_val)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(index_val).?.string;
const index = self.scope_stack.headers.get(header_str) orelse return self.ctx.err(
"Column '{s}' not found.",
.{header_str},
error.InvalidColumnName,
offset,
);
const cols_ptr = value.asList(self.scope_stack.columns).?;
if (index >= cols_ptr.list.items.len) return self.ctx.err(
"Column index out of bounds.",
.{},
error.OutOfBounds,
offset,
);
try self.value_stack.append(cols_ptr.list.items[index]);
self.ip.* += 1;
}
// Scopes
fn pushScope(self: *Vm, scope: Scope) !void {
try self.scope_stack.push(scope);
}
fn popScope(self: *Vm) Scope {
return self.scope_stack.pop();
}
// Helpers
fn isTruthy(v: Value) bool {
if (value.isBool(v)) return v == value.val_true;
if (value.asFloat(v)) |f| return f != 0;
if (value.asFunc(v)) |_| return true;
if (value.asInt(v)) |i| return i != 0;
if (value.asUint(v)) |u| return u != 0;
if (value.asList(v)) |l| return l.list.items.len != 0;
if (value.asMap(v)) |m| return m.map.count() != 0;
if (value.asRange(v)) |r| return r.range[1] - r.range[0] != 0;
if (value.asString(v)) |s| return s.string.len != 0;
if (value.unboxStr(v)) |u| return u != 0;
return v != value.val_nil;
}
fn getNumber(self: Vm, comptime T: type, start: usize, n: usize) T {
return std.mem.bytesAsSlice(T, self.bytecode[start .. start + n])[0];
}
fn getOffset(self: Vm) u16 {
return self.getU16(self.ip.*);
}
fn getU16(self: Vm, start: usize) u16 {
return self.getNumber(u16, start, 2);
}
// Tests
fn testVmValue(allocator: std.mem.Allocator, input: []const u8) !Value {
const Lexer = @import("Lexer.zig");
const Parser = @import("Parser.zig");
const ctx = Context{ .filename = "inline", .src = input };
var lexer = Lexer{ .allocator = allocator, .ctx = ctx };
var tokens = try lexer.lex();
var parser = Parser{
.allocator = allocator,
.ctx = ctx,
.tokens = tokens,
};
const program = try parser.parse();
var compiler = try Compiler.init(allocator, ctx);
for (program.rules) |n| try compiler.compile(n);
var scope_stack = ScopeStack.init(allocator);
var output = std.ArrayList(u8).init(allocator);
var vm = try init(
allocator,
compiler.bytecode.items,
&scope_stack,
ctx,
&output,
);
try vm.run();
try std.testing.expectEqual(@as(usize, 0), vm.value_stack.items.len);
return vm.last_popped;
}
test "Vm assert" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
var got = try testVmValue(allocator, "assert(1 == 1)");
try std.testing.expectEqual(value.val_true, got);
//try std.testing.expectError(error.AssertFailed, testVmValue(allocator, "assert(1 == 2)"));
}
test "Vm basic values and types" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
var got = try testVmValue(allocator, "true");
try std.testing.expectEqual(value.val_true, got);
got = try testVmValue(allocator, "false");
try std.testing.expectEqual(value.val_false, got);
got = try testVmValue(allocator, "nil");
try std.testing.expectEqual(value.val_nil, got);
got = try testVmValue(allocator, "3.1415");
try std.testing.expectEqual(@as(f64, 3.1415), value.asFloat(got).?);
got = try testVmValue(allocator, "3.1415 3.1415");
try std.testing.expectEqual(@as(f64, 3.1415), value.asFloat(got).?);
got = try testVmValue(allocator, "-3");
try std.testing.expectEqual(@as(i32, -3), value.asInt(got).?);
got = try testVmValue(allocator, "-3 -3");
try std.testing.expectEqual(@as(i32, -3), value.asInt(got).?);
got = try testVmValue(allocator, "9");
try std.testing.expectEqual(@as(u32, 9), value.asUint(got).?);
got = try testVmValue(allocator, "9 9");
try std.testing.expectEqual(@as(u32, 9), value.asUint(got).?);
}
test "Vm strings" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
var got = try testVmValue(allocator, "\"foo\"");
var got_str = if (value.unboxStr(got)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(got).?.string;
try std.testing.expectEqualStrings("foo", got_str);
got = try testVmValue(allocator, "\"foobar\" \"foobarbaz\"");
got_str = if (value.unboxStr(got)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(got).?.string;
try std.testing.expectEqualStrings("foobarbaz", got_str);
got = try testVmValue(allocator,
\\"foo {#d:0>3# 2} bar"
);
got_str = if (value.unboxStr(got)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(got).?.string;
try std.testing.expectEqualStrings("foo 002 bar", got_str);
}
test "Vm function literal" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
var got = try testVmValue(allocator,
\\{ foo, bar => 1 }
);
const got_func = value.asFunc(got).?.func;
try std.testing.expectEqual(@as(usize, 2), got_func.params.?.len);
try std.testing.expectEqual(@as(usize, 6), got_func.bytecode.?.len);
try std.testing.expectEqual(Compiler.Opcode.uint, @intToEnum(Compiler.Opcode, got_func.bytecode.?[0]));
}
test "Vm function call / define, store, load" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
var got = try testVmValue(allocator,
\\f := { a := it; return a }
\\r := f(42)
\\r
);
const got_uint = value.asUint(got).?;
try std.testing.expectEqual(@as(u32, 42), got_uint);
}
test "Vm combo assign" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
var got = try testVmValue(allocator,
\\f := 1
\\f += 2
\\f
);
const got_uint = value.asUint(got).?;
try std.testing.expectEqual(@as(u32, 3), got_uint);
}
test "Vm infix" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
var got = try testVmValue(allocator, "1 + 2 * 3 / 2 % 2");
const got_uint = value.asUint(got).?;
try std.testing.expectEqual(@as(u32, 2), got_uint);
got = try testVmValue(allocator, "1 + 2 * 3 / 2 % 2 == 2");
try std.testing.expectEqual(value.val_true, got);
got = try testVmValue(allocator, "(1 + 2) * 3 / 2 % 2 > 2");
try std.testing.expectEqual(value.val_false, got);
got = try testVmValue(allocator,
\\"foo" ++ "bar"
);
var got_str = if (value.unboxStr(got)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(got).?.string;
try std.testing.expectEqualStrings("foobar", got_str);
got = try testVmValue(allocator,
\\"-" ** 3
);
got_str = if (value.unboxStr(got)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(got).?.string;
try std.testing.expectEqualStrings("---", got_str);
got = try testVmValue(allocator, "true and false");
try std.testing.expectEqual(value.val_false, got);
got = try testVmValue(allocator, "false or true");
try std.testing.expectEqual(value.val_true, got);
}
test "Vm prefix" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
var got = try testVmValue(allocator, "foo := 42; -foo");
const got_int = value.asFloat(got).?;
try std.testing.expectEqual(@as(f64, -42), got_int);
got = try testVmValue(allocator, "!true");
try std.testing.expectEqual(value.val_false, got);
}
test "Vm list literal" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
var got = try testVmValue(allocator, "[1, 2, 3]");
const got_list = value.asList(got).?.list;
try std.testing.expectEqual(@as(usize, 3), got_list.items.len);
try std.testing.expectEqual(@as(u32, 1), value.asUint(got_list.items[0]).?);
}
test "Vm map literal" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
var got = try testVmValue(allocator,
\\["a": 1, "b": 2]
);
const got_map = value.asMap(got).?.map;
try std.testing.expectEqual(@as(usize, 2), got_map.count());
try std.testing.expectEqual(@as(u32, 1), value.asUint(got_map.get("a").?).?);
}
test "Vm subscripts" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
var got = try testVmValue(allocator,
\\["a": 1, "b": 2]["b"] + [1, 2, 3][1]
);
try std.testing.expectEqual(@as(u32, 4), value.asUint(got).?);
}
test "Vm subscript assign" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
var got = try testVmValue(allocator,
\\m := ["a": 1, "b": 2]
\\m["b"] += 2
\\m["c"] += m["b"]
\\l := [1, 2, 3]
\\l[1] = 3
\\m["c"] + l[1]
);
try std.testing.expectEqual(@as(u32, 7), value.asUint(got).?);
}
test "Vm conditionals" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
var got = try testVmValue(allocator,
\\a := if (false) 1 else 0
\\a ?= 1
\\b := a ?: 3
\\c := b ? 4 : 5
\\a + b + c
);
try std.testing.expectEqual(@as(u32, 6), value.asUint(got).?);
}
test "Vm while loop" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
var got = try testVmValue(allocator,
\\i := 0
\\while (i < 9) {
\\ i += 1
\\}
\\i
);
try std.testing.expectEqual(@as(u32, 9), value.asUint(got).?);
}
test "Vm do while loop" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
var got = try testVmValue(allocator,
\\i := 10
\\do {
\\ i += 1
\\} while (i < 10)
\\i
);
try std.testing.expectEqual(@as(u32, 11), value.asUint(got).?);
}
test "Vm loop break" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
var got = try testVmValue(allocator,
\\i := 0
\\while (i < 9) {
\\ i += 1
\\ if (i == 4) break
\\}
\\i
);
try std.testing.expectEqual(@as(u32, 4), value.asUint(got).?);
}
test "Vm loop continue" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
var got = try testVmValue(allocator,
\\i := 0
\\total := 0
\\while (i < 4) {
\\ i += 1
\\ if (i == 2) continue
\\ total += i
\\}
\\total
);
try std.testing.expectEqual(@as(u32, 8), value.asUint(got).?);
}
test "Vm fibonacci" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
var got = try testVmValue(allocator,
\\fib := {
\\ a := 0
\\ b := 1
\\ i := 0
\\
\\ while (i < it) {
\\ tmp := a
\\ a = b
\\ b = tmp + a
\\ i += 1
\\ }
\\
\\ return a
\\}
\\fib(7)
);
try std.testing.expectEqual(@as(u32, 13), value.asUint(got).?);
}
test "Vm recursive fibonacci" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
var got = try testVmValue(allocator,
\\fib := {
\\ if (it < 2) return it
\\ return fib(it - 1) + fib(it - 2)
\\}
\\fib(7)
);
try std.testing.expectEqual(@as(u32, 13), value.asUint(got).?);
}
test "Vm list range subscript" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
var got = try testVmValue(allocator,
\\[1, 2, 3, 4, 5][2..<5][1]
);
try std.testing.expectEqual(@as(u32, 4), value.asUint(got).?);
}
test "Vm math builtins" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
var got = try testVmValue(allocator, "atan2(0, -1)");
try std.testing.expectEqual(@as(f64, 3.141592653589793e+00), value.asFloat(got).?);
got = try testVmValue(allocator, "cos(-1)");
try std.testing.expectEqual(@as(f64, 5.403023058681398e-01), value.asFloat(got).?);
got = try testVmValue(allocator, "exp(5)");
try std.testing.expectEqual(@as(f64, 1.484131591025766e+02), value.asFloat(got).?);
got = try testVmValue(allocator, "int(-3.9)");
try std.testing.expectEqual(@as(i32, -3), value.asInt(got).?);
got = try testVmValue(allocator, "int(3.9)");
try std.testing.expectEqual(@as(i32, 3), value.asInt(got).?);
got = try testVmValue(allocator, "log(3.14)");
try std.testing.expectEqual(@as(f64, 1.144222799920162e+00), value.asFloat(got).?);
//try testLastValue("rand(10)", Value.new(.{ .uint = 10 }));
got = try testVmValue(allocator, "sin(3.14)");
try std.testing.expectEqual(@as(f64, 1.5926529164868282e-03), value.asFloat(got).?);
got = try testVmValue(allocator, "sqrt(49)");
try std.testing.expectEqual(@as(f64, 7), value.asFloat(got).?);
}
test "Vm each, map, filter, reduce " {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
var got = try testVmValue(allocator,
\\total := 0
\\[1, 2, 3].each() { total = total + it }
\\total
);
try std.testing.expectEqual(@as(u32, 6), value.asUint(got).?);
got = try testVmValue(allocator,
\\m := [1, 2, 3].map() { a => a * 2 + index }
\\m[1]
);
try std.testing.expectEqual(@as(u32, 5), value.asUint(got).?);
got = try testVmValue(allocator,
\\f := { a => a * 2 + index }
\\[1, 2, 3].map(f)[1]
);
try std.testing.expectEqual(@as(u32, 5), value.asUint(got).?);
got = try testVmValue(allocator,
\\[1, 2, 3].filter() { it > 1 }[1]
);
try std.testing.expectEqual(@as(u32, 3), value.asUint(got).?);
got = try testVmValue(allocator,
\\[1, 2, 3].reduce(1) { acc * it }
);
try std.testing.expectEqual(@as(u32, 6), value.asUint(got).?);
got = try testVmValue(allocator,
\\(1..=3).reduce(1) { acc * it }
);
try std.testing.expectEqual(@as(u32, 6), value.asUint(got).?);
}
test "Vm len" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
var got = try testVmValue(allocator, "[1, 2, 3].len()");
try std.testing.expectEqual(@as(u32, 3), value.asUint(got).?);
got = try testVmValue(allocator,
\\["a": 1, "b": 2, "c": 3].len()
);
try std.testing.expectEqual(@as(u32, 3), value.asUint(got).?);
got = try testVmValue(allocator,
\\"foo".len()
);
try std.testing.expectEqual(@as(u32, 3), value.asUint(got).?);
}
test "Vm map methods" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
var got = try testVmValue(allocator,
\\["a": 1, "b": 2, "c": 3].keys().len()
);
try std.testing.expectEqual(@as(u32, 3), value.asUint(got).?);
got = try testVmValue(allocator,
\\["a": 3, "b": 2, "c": 1].keysByValueAsc()[0]
);
var got_str = if (value.unboxStr(got)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(got).?.string;
try std.testing.expectEqualStrings("c", got_str);
got = try testVmValue(allocator,
\\["a": 3, "b": 2, "c": 1].keysByValueDesc()[0]
);
got_str = if (value.unboxStr(got)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(got).?.string;
try std.testing.expectEqualStrings("a", got_str);
got = try testVmValue(allocator,
\\["a": 1, "b": 2, "c": 3].values().len()
);
try std.testing.expectEqual(@as(u32, 3), value.asUint(got).?);
}
test "Vm statistics" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
const mean_input =
\\l := [1, 2, "foo", 3, nil]
\\l.mean()
;
const median_input =
\\l := [1, 2, "foo", 3, nil, 4]
\\l.median()
;
const mode_input =
\\l := [1, 1, "foo", 2, nil, 2, 3, 4]
\\l.mode().len()
;
const stdev_input =
\\l := [1, 1, "foo", 2, nil, 2, 3, 4]
\\l.stdev()
;
var got = try testVmValue(allocator, mean_input);
try std.testing.expectEqual(@as(f64, 2), value.asFloat(got).?);
got = try testVmValue(allocator, median_input);
try std.testing.expectEqual(@as(f64, 2.5), value.asFloat(got).?);
got = try testVmValue(allocator, mode_input);
try std.testing.expectEqual(@as(u32, 2), value.asUint(got).?);
got = try testVmValue(allocator, stdev_input);
try std.testing.expectEqual(@as(f64, 1.0671873729054748), value.asFloat(got).?);
}
test "Vm min max" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
var got = try testVmValue(allocator, "[1, 2, 3].min()");
try std.testing.expectEqual(@as(u32, 1), value.asUint(got).?);
got = try testVmValue(allocator, "[1, 2, 3].max()");
try std.testing.expectEqual(@as(u32, 3), value.asUint(got).?);
got = try testVmValue(allocator,
\\["a", "z", "B"].min()
);
var got_str = if (value.unboxStr(got)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(got).?.string;
try std.testing.expectEqualStrings("B", got_str);
}
test "Vm sort" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
var got = try testVmValue(allocator, "[2, 3, 1].sortAsc()[0]");
try std.testing.expectEqual(@as(u32, 1), value.asUint(got).?);
got = try testVmValue(allocator, "[2, 3, 1].sortDesc()[0]");
try std.testing.expectEqual(@as(u32, 3), value.asUint(got).?);
}
test "Vm contains indexOf lastIndexOf" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
var got = try testVmValue(allocator, "[2, 3, 1].contains(3)");
try std.testing.expectEqual(value.val_true, got);
got = try testVmValue(allocator, "[2, 3, 1].contains(4)");
try std.testing.expectEqual(value.val_false, got);
got = try testVmValue(allocator,
\\"foo".contains("oo")
);
try std.testing.expectEqual(value.val_true, got);
got = try testVmValue(allocator, "[2, 3, 1].indexOf(1)");
try std.testing.expectEqual(@as(u32, 2), value.asUint(got).?);
got = try testVmValue(allocator, "[2, 3, 1].indexOf(4)");
try std.testing.expectEqual(value.val_nil, got);
got = try testVmValue(allocator,
\\"H\u65\u301llo".indexOf("l")
);
try std.testing.expectEqual(@as(u32, 2), value.asUint(got).?);
got = try testVmValue(allocator,
\\"H\u65\u301llo".lastIndexOf("l")
);
try std.testing.expectEqual(@as(u32, 3), value.asUint(got).?);
}
test "Vm reverse, split, join" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
var got = try testVmValue(allocator, "[2, 3, 1].reverse()[0]");
try std.testing.expectEqual(@as(u32, 1), value.asUint(got).?);
got = try testVmValue(allocator,
\\"foo,bar,baz".split(",")[1]
);
var got_str = if (value.unboxStr(got)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(got).?.string;
try std.testing.expectEqualStrings("bar", got_str);
got = try testVmValue(allocator,
\\["foo", 1, 2.3, nil].join(",")
);
got_str = if (value.unboxStr(got)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(got).?.string;
try std.testing.expectEqualStrings("foo,1,2.3,", got_str);
}
test "Vm string methods" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
var got = try testVmValue(allocator,
\\"H\u65\u301llo".chars()[1]
);
var got_str = if (value.unboxStr(got)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(got).?.string;
try std.testing.expectEqualStrings("\u{65}\u{301}", got_str);
got = try testVmValue(allocator,
\\"Hello".startsWith("Hell")
);
try std.testing.expectEqual(value.val_true, got);
got = try testVmValue(allocator,
\\"Hello".endsWith("llo")
);
try std.testing.expectEqual(value.val_true, got);
got = try testVmValue(allocator,
\\"FOO".toLower()
);
got_str = if (value.unboxStr(got)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(got).?.string;
try std.testing.expectEqualStrings("foo", got_str);
got = try testVmValue(allocator,
\\"foo".toUpper()
);
got_str = if (value.unboxStr(got)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(got).?.string;
try std.testing.expectEqualStrings("FOO", got_str);
got = try testVmValue(allocator, "\"\"");
const got_u = value.unboxStr(got).?;
try std.testing.expectEqual(@as(u64, 0), got_u);
got = try testVmValue(allocator,
\\"foo".replace("oo", "ee")
);
got_str = if (value.unboxStr(got)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(got).?.string;
try std.testing.expectEqualStrings("fee", got_str);
got = try testVmValue(allocator,
\\pattern := `(?x) (?<month> \d{2}) / (?<day> \d{2}) / (?<year> \d{4})`
\\replacement := `${year}/${month}/${day}`
\\"12/25/1970".replace(pattern, replacement)
);
got_str = if (value.unboxStr(got)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(got).?.string;
try std.testing.expectEqualStrings("1970/12/25", got_str);
}
test "Vm list methods" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
var got = try testVmValue(allocator,
\\l := [1]
\\l.push(2)
\\l[1]
);
try std.testing.expectEqual(@as(u32, 2), value.asUint(got).?);
got = try testVmValue(allocator,
\\l := [1]
\\l.pop()
);
try std.testing.expectEqual(@as(u32, 1), value.asUint(got).?);
got = try testVmValue(allocator,
\\l := [1, 2, 1, 3, 1, 3]
\\u := l.unique()
\\u.reduce(0) { acc + it }
);
try std.testing.expectEqual(@as(u32, 6), value.asUint(got).?);
got = try testVmValue(allocator,
\\l := [1, 2, 1, 3, 1, 3]
\\u := l.unique()
\\u[0]
);
try std.testing.expectEqual(@as(u32, 1), value.asUint(got).?);
} | src/Vm.zig |
const std = @import("std");
const ecs = @import("ecs");
// override the EntityTraits used by ecs
pub const EntityTraits = ecs.EntityTraitsType(.medium);
pub const Velocity = struct { x: f32, y: f32 };
pub const Position = struct { x: f32, y: f32 };
const total_entities: usize = 10000;
/// logs the timing for views vs non-owning groups vs owning groups with 1,000,000 entities
pub fn main() !void {
var reg = ecs.Registry.init(std.heap.c_allocator);
defer reg.deinit();
createEntities(®);
owningGroup(®);
}
fn createEntities(reg: *ecs.Registry) void {
var r = std.rand.DefaultPrng.init(666);
var timer = std.time.Timer.start() catch unreachable;
var i: usize = 0;
while (i < total_entities) : (i += 1) {
var e1 = reg.create();
reg.add(e1, Position{ .x = 1, .y = r.random().float(f32) * 100 });
reg.add(e1, Velocity{ .x = 1, .y = r.random().float(f32) * 100 });
}
var end = timer.lap();
std.debug.print("create {d} entities: {d}\n", .{ total_entities, @intToFloat(f64, end) / 1000000000 });
}
fn owningGroup(reg: *ecs.Registry) void {
var group = reg.group(.{ Velocity, Position }, .{}, .{});
// var group_iter = group.iterator(struct { vel: *Velocity, pos: *Position });
// while (group_iter.next()) |e| {
// std.debug.print("pos.y {d:.3}, ent: {}\n", .{e.pos.y, group_iter.entity()});
// }
const SortContext = struct {
fn sort(_: void, a: Position, b: Position) bool {
return a.y < b.y;
}
};
var timer = std.time.Timer.start() catch unreachable;
group.sort(Position, {}, SortContext.sort);
var end = timer.lap();
std.debug.print("group (sort): {d}\n", .{@intToFloat(f64, end) / 1000000000});
timer.reset();
group.sort(Position, {}, SortContext.sort);
end = timer.lap();
std.debug.print("group (sort 2): {d}\n", .{@intToFloat(f64, end) / 1000000000});
// var group_iter2 = group.iterator(struct { vel: *Velocity, pos: *Position });
// while (group_iter2.next()) |e| {
// std.debug.print("pos.y {d:.3}, ent: {}\n", .{e.pos.y, group_iter2.entity()});
// }
} | examples/group_sort.zig |
pub const DTCINSTALL_E_CLIENT_ALREADY_INSTALLED = @as(i32, 384);
pub const DTCINSTALL_E_SERVER_ALREADY_INSTALLED = @as(i32, 385);
pub const XA_SWITCH_F_DTC = @as(u32, 1);
pub const XA_FMTID_DTC = @as(u32, 4478019);
pub const XA_FMTID_DTC_VER1 = @as(u32, 21255235);
pub const XIDDATASIZE = @as(u32, 128);
pub const MAXGTRIDSIZE = @as(u32, 64);
pub const MAXBQUALSIZE = @as(u32, 64);
pub const RMNAMESZ = @as(u32, 32);
pub const MAXINFOSIZE = @as(u32, 256);
pub const TMNOFLAGS = @as(i32, 0);
pub const TMREGISTER = @as(i32, 1);
pub const TMNOMIGRATE = @as(i32, 2);
pub const TMUSEASYNC = @as(i32, 4);
pub const TMASYNC = @as(i32, -2147483648);
pub const TMONEPHASE = @as(i32, 1073741824);
pub const TMFAIL = @as(i32, 536870912);
pub const TMNOWAIT = @as(i32, 268435456);
pub const TMRESUME = @as(i32, 134217728);
pub const TMSUCCESS = @as(i32, 67108864);
pub const TMSUSPEND = @as(i32, 33554432);
pub const TMSTARTRSCAN = @as(i32, 16777216);
pub const TMENDRSCAN = @as(i32, 8388608);
pub const TMMULTIPLE = @as(i32, 4194304);
pub const TMJOIN = @as(i32, 2097152);
pub const TMMIGRATE = @as(i32, 1048576);
pub const TM_JOIN = @as(u32, 2);
pub const TM_RESUME = @as(u32, 1);
pub const TM_OK = @as(u32, 0);
pub const TMER_TMERR = @as(i32, -1);
pub const TMER_INVAL = @as(i32, -2);
pub const TMER_PROTO = @as(i32, -3);
pub const XA_RBBASE = @as(u32, 100);
pub const XA_RBROLLBACK = @as(u32, 100);
pub const XA_RBCOMMFAIL = @as(u32, 101);
pub const XA_RBDEADLOCK = @as(u32, 102);
pub const XA_RBINTEGRITY = @as(u32, 103);
pub const XA_RBOTHER = @as(u32, 104);
pub const XA_RBPROTO = @as(u32, 105);
pub const XA_RBTIMEOUT = @as(u32, 106);
pub const XA_RBTRANSIENT = @as(u32, 107);
pub const XA_RBEND = @as(u32, 107);
pub const XA_NOMIGRATE = @as(u32, 9);
pub const XA_HEURHAZ = @as(u32, 8);
pub const XA_HEURCOM = @as(u32, 7);
pub const XA_HEURRB = @as(u32, 6);
pub const XA_HEURMIX = @as(u32, 5);
pub const XA_RETRY = @as(u32, 4);
pub const XA_RDONLY = @as(u32, 3);
pub const XA_OK = @as(u32, 0);
pub const XAER_ASYNC = @as(i32, -2);
pub const XAER_RMERR = @as(i32, -3);
pub const XAER_NOTA = @as(i32, -4);
pub const XAER_INVAL = @as(i32, -5);
pub const XAER_PROTO = @as(i32, -6);
pub const XAER_RMFAIL = @as(i32, -7);
pub const XAER_DUPID = @as(i32, -8);
pub const XAER_OUTSIDE = @as(i32, -9);
pub const DTC_INSTALL_OVERWRITE_CLIENT = @as(u32, 1);
pub const DTC_INSTALL_OVERWRITE_SERVER = @as(u32, 2);
pub const OLE_TM_CONFIG_VERSION_1 = @as(u32, 1);
pub const OLE_TM_CONFIG_VERSION_2 = @as(u32, 2);
pub const OLE_TM_FLAG_NONE = @as(u32, 0);
pub const OLE_TM_FLAG_NODEMANDSTART = @as(u32, 1);
pub const OLE_TM_FLAG_NOAGILERECOVERY = @as(u32, 2);
pub const OLE_TM_FLAG_QUERY_SERVICE_LOCKSTATUS = @as(u32, 2147483648);
pub const OLE_TM_FLAG_INTERNAL_TO_TM = @as(u32, 1073741824);
pub const CLSID_MSDtcTransactionManager = Guid.initString("5b18ab61-091d-11d1-97df-00c04fb9618a");
pub const CLSID_MSDtcTransaction = Guid.initString("39f8d76b-0928-11d1-97df-00c04fb9618a");
//--------------------------------------------------------------------------------
// Section: Types (110)
//--------------------------------------------------------------------------------
pub const DTC_STATUS_ = enum(i32) {
UNKNOWN = 0,
STARTING = 1,
STARTED = 2,
PAUSING = 3,
PAUSED = 4,
CONTINUING = 5,
STOPPING = 6,
STOPPED = 7,
E_CANTCONTROL = 8,
FAILED = 9,
};
pub const DTC_STATUS_UNKNOWN = DTC_STATUS_.UNKNOWN;
pub const DTC_STATUS_STARTING = DTC_STATUS_.STARTING;
pub const DTC_STATUS_STARTED = DTC_STATUS_.STARTED;
pub const DTC_STATUS_PAUSING = DTC_STATUS_.PAUSING;
pub const DTC_STATUS_PAUSED = DTC_STATUS_.PAUSED;
pub const DTC_STATUS_CONTINUING = DTC_STATUS_.CONTINUING;
pub const DTC_STATUS_STOPPING = DTC_STATUS_.STOPPING;
pub const DTC_STATUS_STOPPED = DTC_STATUS_.STOPPED;
pub const DTC_STATUS_E_CANTCONTROL = DTC_STATUS_.E_CANTCONTROL;
pub const DTC_STATUS_FAILED = DTC_STATUS_.FAILED;
pub const DTC_GET_TRANSACTION_MANAGER = fn(
pszHost: ?PSTR,
pszTmName: ?PSTR,
rid: ?*const Guid,
dwReserved1: u32,
wcbReserved2: u16,
pvReserved2: ?*anyopaque,
ppvObject: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const DTC_GET_TRANSACTION_MANAGER_EX_A = fn(
i_pszHost: ?PSTR,
i_pszTmName: ?PSTR,
i_riid: ?*const Guid,
i_grfOptions: u32,
i_pvConfigParams: ?*anyopaque,
o_ppvObject: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const DTC_GET_TRANSACTION_MANAGER_EX_W = fn(
i_pwszHost: ?PWSTR,
i_pwszTmName: ?PWSTR,
i_riid: ?*const Guid,
i_grfOptions: u32,
i_pvConfigParams: ?*anyopaque,
o_ppvObject: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const DTC_INSTALL_CLIENT = fn(
i_pszRemoteTmHostName: ?*i8,
i_dwProtocol: u32,
i_dwOverwrite: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const BOID = extern struct {
rgb: [16]u8,
};
pub const TX_MISC_CONSTANTS = enum(i32) {
C = 40,
};
pub const MAX_TRAN_DESC = TX_MISC_CONSTANTS.C;
pub const ISOLATIONLEVEL = enum(i32) {
UNSPECIFIED = -1,
CHAOS = 16,
READUNCOMMITTED = 256,
// BROWSE = 256, this enum value conflicts with READUNCOMMITTED
CURSORSTABILITY = 4096,
// READCOMMITTED = 4096, this enum value conflicts with CURSORSTABILITY
REPEATABLEREAD = 65536,
SERIALIZABLE = 1048576,
// ISOLATED = 1048576, this enum value conflicts with SERIALIZABLE
};
pub const ISOLATIONLEVEL_UNSPECIFIED = ISOLATIONLEVEL.UNSPECIFIED;
pub const ISOLATIONLEVEL_CHAOS = ISOLATIONLEVEL.CHAOS;
pub const ISOLATIONLEVEL_READUNCOMMITTED = ISOLATIONLEVEL.READUNCOMMITTED;
pub const ISOLATIONLEVEL_BROWSE = ISOLATIONLEVEL.READUNCOMMITTED;
pub const ISOLATIONLEVEL_CURSORSTABILITY = ISOLATIONLEVEL.CURSORSTABILITY;
pub const ISOLATIONLEVEL_READCOMMITTED = ISOLATIONLEVEL.CURSORSTABILITY;
pub const ISOLATIONLEVEL_REPEATABLEREAD = ISOLATIONLEVEL.REPEATABLEREAD;
pub const ISOLATIONLEVEL_SERIALIZABLE = ISOLATIONLEVEL.SERIALIZABLE;
pub const ISOLATIONLEVEL_ISOLATED = ISOLATIONLEVEL.SERIALIZABLE;
pub const XACTTRANSINFO = extern struct {
uow: BOID,
isoLevel: i32,
isoFlags: u32,
grfTCSupported: u32,
grfRMSupported: u32,
grfTCSupportedRetaining: u32,
grfRMSupportedRetaining: u32,
};
pub const XACTSTATS = extern struct {
cOpen: u32,
cCommitting: u32,
cCommitted: u32,
cAborting: u32,
cAborted: u32,
cInDoubt: u32,
cHeuristicDecision: u32,
timeTransactionsUp: FILETIME,
};
pub const ISOFLAG = enum(i32) {
RETAIN_COMMIT_DC = 1,
RETAIN_COMMIT = 2,
RETAIN_COMMIT_NO = 3,
RETAIN_ABORT_DC = 4,
RETAIN_ABORT = 8,
RETAIN_ABORT_NO = 12,
RETAIN_DONTCARE = 5,
RETAIN_BOTH = 10,
RETAIN_NONE = 15,
OPTIMISTIC = 16,
READONLY = 32,
};
pub const ISOFLAG_RETAIN_COMMIT_DC = ISOFLAG.RETAIN_COMMIT_DC;
pub const ISOFLAG_RETAIN_COMMIT = ISOFLAG.RETAIN_COMMIT;
pub const ISOFLAG_RETAIN_COMMIT_NO = ISOFLAG.RETAIN_COMMIT_NO;
pub const ISOFLAG_RETAIN_ABORT_DC = ISOFLAG.RETAIN_ABORT_DC;
pub const ISOFLAG_RETAIN_ABORT = ISOFLAG.RETAIN_ABORT;
pub const ISOFLAG_RETAIN_ABORT_NO = ISOFLAG.RETAIN_ABORT_NO;
pub const ISOFLAG_RETAIN_DONTCARE = ISOFLAG.RETAIN_DONTCARE;
pub const ISOFLAG_RETAIN_BOTH = ISOFLAG.RETAIN_BOTH;
pub const ISOFLAG_RETAIN_NONE = ISOFLAG.RETAIN_NONE;
pub const ISOFLAG_OPTIMISTIC = ISOFLAG.OPTIMISTIC;
pub const ISOFLAG_READONLY = ISOFLAG.READONLY;
pub const XACTTC = enum(i32) {
NONE = 0,
SYNC_PHASEONE = 1,
SYNC_PHASETWO = 2,
// SYNC = 2, this enum value conflicts with SYNC_PHASETWO
ASYNC_PHASEONE = 4,
// ASYNC = 4, this enum value conflicts with ASYNC_PHASEONE
};
pub const XACTTC_NONE = XACTTC.NONE;
pub const XACTTC_SYNC_PHASEONE = XACTTC.SYNC_PHASEONE;
pub const XACTTC_SYNC_PHASETWO = XACTTC.SYNC_PHASETWO;
pub const XACTTC_SYNC = XACTTC.SYNC_PHASETWO;
pub const XACTTC_ASYNC_PHASEONE = XACTTC.ASYNC_PHASEONE;
pub const XACTTC_ASYNC = XACTTC.ASYNC_PHASEONE;
pub const XACTRM = enum(i32) {
OPTIMISTICLASTWINS = 1,
NOREADONLYPREPARES = 2,
};
pub const XACTRM_OPTIMISTICLASTWINS = XACTRM.OPTIMISTICLASTWINS;
pub const XACTRM_NOREADONLYPREPARES = XACTRM.NOREADONLYPREPARES;
pub const XACTCONST = enum(i32) {
E = 0,
};
pub const XACTCONST_TIMEOUTINFINITE = XACTCONST.E;
pub const XACTHEURISTIC = enum(i32) {
ABORT = 1,
COMMIT = 2,
DAMAGE = 3,
DANGER = 4,
};
pub const XACTHEURISTIC_ABORT = XACTHEURISTIC.ABORT;
pub const XACTHEURISTIC_COMMIT = XACTHEURISTIC.COMMIT;
pub const XACTHEURISTIC_DAMAGE = XACTHEURISTIC.DAMAGE;
pub const XACTHEURISTIC_DANGER = XACTHEURISTIC.DANGER;
pub const XACTSTAT = enum(i32) {
NONE = 0,
OPENNORMAL = 1,
OPENREFUSED = 2,
PREPARING = 4,
PREPARED = 8,
PREPARERETAINING = 16,
PREPARERETAINED = 32,
COMMITTING = 64,
COMMITRETAINING = 128,
ABORTING = 256,
ABORTED = 512,
COMMITTED = 1024,
HEURISTIC_ABORT = 2048,
HEURISTIC_COMMIT = 4096,
HEURISTIC_DAMAGE = 8192,
HEURISTIC_DANGER = 16384,
FORCED_ABORT = 32768,
FORCED_COMMIT = 65536,
INDOUBT = 131072,
CLOSED = 262144,
OPEN = 3,
NOTPREPARED = 524227,
ALL = 524287,
};
pub const XACTSTAT_NONE = XACTSTAT.NONE;
pub const XACTSTAT_OPENNORMAL = XACTSTAT.OPENNORMAL;
pub const XACTSTAT_OPENREFUSED = XACTSTAT.OPENREFUSED;
pub const XACTSTAT_PREPARING = XACTSTAT.PREPARING;
pub const XACTSTAT_PREPARED = XACTSTAT.PREPARED;
pub const XACTSTAT_PREPARERETAINING = XACTSTAT.PREPARERETAINING;
pub const XACTSTAT_PREPARERETAINED = XACTSTAT.PREPARERETAINED;
pub const XACTSTAT_COMMITTING = XACTSTAT.COMMITTING;
pub const XACTSTAT_COMMITRETAINING = XACTSTAT.COMMITRETAINING;
pub const XACTSTAT_ABORTING = XACTSTAT.ABORTING;
pub const XACTSTAT_ABORTED = XACTSTAT.ABORTED;
pub const XACTSTAT_COMMITTED = XACTSTAT.COMMITTED;
pub const XACTSTAT_HEURISTIC_ABORT = XACTSTAT.HEURISTIC_ABORT;
pub const XACTSTAT_HEURISTIC_COMMIT = XACTSTAT.HEURISTIC_COMMIT;
pub const XACTSTAT_HEURISTIC_DAMAGE = XACTSTAT.HEURISTIC_DAMAGE;
pub const XACTSTAT_HEURISTIC_DANGER = XACTSTAT.HEURISTIC_DANGER;
pub const XACTSTAT_FORCED_ABORT = XACTSTAT.FORCED_ABORT;
pub const XACTSTAT_FORCED_COMMIT = XACTSTAT.FORCED_COMMIT;
pub const XACTSTAT_INDOUBT = XACTSTAT.INDOUBT;
pub const XACTSTAT_CLOSED = XACTSTAT.CLOSED;
pub const XACTSTAT_OPEN = XACTSTAT.OPEN;
pub const XACTSTAT_NOTPREPARED = XACTSTAT.NOTPREPARED;
pub const XACTSTAT_ALL = XACTSTAT.ALL;
pub const XACTOPT = extern struct {
ulTimeout: u32,
szDescription: [40]u8,
};
const IID_ITransaction_Value = @import("../zig.zig").Guid.initString("0fb15084-af41-11ce-bd2b-204c4f4f5020");
pub const IID_ITransaction = &IID_ITransaction_Value;
pub const ITransaction = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Commit: fn(
self: *const ITransaction,
fRetaining: BOOL,
grfTC: u32,
grfRM: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Abort: fn(
self: *const ITransaction,
pboidReason: ?*BOID,
fRetaining: BOOL,
fAsync: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetTransactionInfo: fn(
self: *const ITransaction,
pinfo: ?*XACTTRANSINFO,
) 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 ITransaction_Commit(self: *const T, fRetaining: BOOL, grfTC: u32, grfRM: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransaction.VTable, self.vtable).Commit(@ptrCast(*const ITransaction, self), fRetaining, grfTC, grfRM);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransaction_Abort(self: *const T, pboidReason: ?*BOID, fRetaining: BOOL, fAsync: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransaction.VTable, self.vtable).Abort(@ptrCast(*const ITransaction, self), pboidReason, fRetaining, fAsync);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransaction_GetTransactionInfo(self: *const T, pinfo: ?*XACTTRANSINFO) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransaction.VTable, self.vtable).GetTransactionInfo(@ptrCast(*const ITransaction, self), pinfo);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ITransactionCloner_Value = @import("../zig.zig").Guid.initString("02656950-2152-11d0-944c-00a0c905416e");
pub const IID_ITransactionCloner = &IID_ITransactionCloner_Value;
pub const ITransactionCloner = extern struct {
pub const VTable = extern struct {
base: ITransaction.VTable,
CloneWithCommitDisabled: fn(
self: *const ITransactionCloner,
ppITransaction: ?*?*ITransaction,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace ITransaction.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransactionCloner_CloneWithCommitDisabled(self: *const T, ppITransaction: ?*?*ITransaction) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionCloner.VTable, self.vtable).CloneWithCommitDisabled(@ptrCast(*const ITransactionCloner, self), ppITransaction);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ITransaction2_Value = @import("../zig.zig").Guid.initString("34021548-0065-11d3-bac1-00c04f797be2");
pub const IID_ITransaction2 = &IID_ITransaction2_Value;
pub const ITransaction2 = extern struct {
pub const VTable = extern struct {
base: ITransactionCloner.VTable,
GetTransactionInfo2: fn(
self: *const ITransaction2,
pinfo: ?*XACTTRANSINFO,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace ITransactionCloner.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransaction2_GetTransactionInfo2(self: *const T, pinfo: ?*XACTTRANSINFO) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransaction2.VTable, self.vtable).GetTransactionInfo2(@ptrCast(*const ITransaction2, self), pinfo);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ITransactionDispenser_Value = @import("../zig.zig").Guid.initString("3a6ad9e1-23b9-11cf-ad60-00aa00a74ccd");
pub const IID_ITransactionDispenser = &IID_ITransactionDispenser_Value;
pub const ITransactionDispenser = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetOptionsObject: fn(
self: *const ITransactionDispenser,
ppOptions: ?*?*ITransactionOptions,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
BeginTransaction: fn(
self: *const ITransactionDispenser,
punkOuter: ?*IUnknown,
isoLevel: i32,
isoFlags: u32,
pOptions: ?*ITransactionOptions,
ppTransaction: ?*?*ITransaction,
) 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 ITransactionDispenser_GetOptionsObject(self: *const T, ppOptions: ?*?*ITransactionOptions) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionDispenser.VTable, self.vtable).GetOptionsObject(@ptrCast(*const ITransactionDispenser, self), ppOptions);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransactionDispenser_BeginTransaction(self: *const T, punkOuter: ?*IUnknown, isoLevel: i32, isoFlags: u32, pOptions: ?*ITransactionOptions, ppTransaction: ?*?*ITransaction) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionDispenser.VTable, self.vtable).BeginTransaction(@ptrCast(*const ITransactionDispenser, self), punkOuter, isoLevel, isoFlags, pOptions, ppTransaction);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ITransactionOptions_Value = @import("../zig.zig").Guid.initString("3a6ad9e0-23b9-11cf-ad60-00aa00a74ccd");
pub const IID_ITransactionOptions = &IID_ITransactionOptions_Value;
pub const ITransactionOptions = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetOptions: fn(
self: *const ITransactionOptions,
pOptions: ?*XACTOPT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetOptions: fn(
self: *const ITransactionOptions,
pOptions: ?*XACTOPT,
) 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 ITransactionOptions_SetOptions(self: *const T, pOptions: ?*XACTOPT) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionOptions.VTable, self.vtable).SetOptions(@ptrCast(*const ITransactionOptions, self), pOptions);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransactionOptions_GetOptions(self: *const T, pOptions: ?*XACTOPT) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionOptions.VTable, self.vtable).GetOptions(@ptrCast(*const ITransactionOptions, self), pOptions);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ITransactionOutcomeEvents_Value = @import("../zig.zig").Guid.initString("3a6ad9e2-23b9-11cf-ad60-00aa00a74ccd");
pub const IID_ITransactionOutcomeEvents = &IID_ITransactionOutcomeEvents_Value;
pub const ITransactionOutcomeEvents = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Committed: fn(
self: *const ITransactionOutcomeEvents,
fRetaining: BOOL,
pNewUOW: ?*BOID,
hr: HRESULT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Aborted: fn(
self: *const ITransactionOutcomeEvents,
pboidReason: ?*BOID,
fRetaining: BOOL,
pNewUOW: ?*BOID,
hr: HRESULT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
HeuristicDecision: fn(
self: *const ITransactionOutcomeEvents,
dwDecision: u32,
pboidReason: ?*BOID,
hr: HRESULT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Indoubt: fn(
self: *const ITransactionOutcomeEvents,
) 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 ITransactionOutcomeEvents_Committed(self: *const T, fRetaining: BOOL, pNewUOW: ?*BOID, hr: HRESULT) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionOutcomeEvents.VTable, self.vtable).Committed(@ptrCast(*const ITransactionOutcomeEvents, self), fRetaining, pNewUOW, hr);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransactionOutcomeEvents_Aborted(self: *const T, pboidReason: ?*BOID, fRetaining: BOOL, pNewUOW: ?*BOID, hr: HRESULT) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionOutcomeEvents.VTable, self.vtable).Aborted(@ptrCast(*const ITransactionOutcomeEvents, self), pboidReason, fRetaining, pNewUOW, hr);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransactionOutcomeEvents_HeuristicDecision(self: *const T, dwDecision: u32, pboidReason: ?*BOID, hr: HRESULT) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionOutcomeEvents.VTable, self.vtable).HeuristicDecision(@ptrCast(*const ITransactionOutcomeEvents, self), dwDecision, pboidReason, hr);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransactionOutcomeEvents_Indoubt(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionOutcomeEvents.VTable, self.vtable).Indoubt(@ptrCast(*const ITransactionOutcomeEvents, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ITmNodeName_Value = @import("../zig.zig").Guid.initString("30274f88-6ee4-474e-9b95-7807bc9ef8cf");
pub const IID_ITmNodeName = &IID_ITmNodeName_Value;
pub const ITmNodeName = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetNodeNameSize: fn(
self: *const ITmNodeName,
pcbNodeNameSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetNodeName: fn(
self: *const ITmNodeName,
cbNodeNameBufferSize: u32,
pNodeNameBuffer: ?PWSTR,
) 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 ITmNodeName_GetNodeNameSize(self: *const T, pcbNodeNameSize: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITmNodeName.VTable, self.vtable).GetNodeNameSize(@ptrCast(*const ITmNodeName, self), pcbNodeNameSize);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITmNodeName_GetNodeName(self: *const T, cbNodeNameBufferSize: u32, pNodeNameBuffer: ?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITmNodeName.VTable, self.vtable).GetNodeName(@ptrCast(*const ITmNodeName, self), cbNodeNameBufferSize, pNodeNameBuffer);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IKernelTransaction_Value = @import("../zig.zig").Guid.initString("79427a2b-f895-40e0-be79-b57dc82ed231");
pub const IID_IKernelTransaction = &IID_IKernelTransaction_Value;
pub const IKernelTransaction = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetHandle: fn(
self: *const IKernelTransaction,
pHandle: ?*?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 IKernelTransaction_GetHandle(self: *const T, pHandle: ?*?HANDLE) callconv(.Inline) HRESULT {
return @ptrCast(*const IKernelTransaction.VTable, self.vtable).GetHandle(@ptrCast(*const IKernelTransaction, self), pHandle);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ITransactionResourceAsync_Value = @import("../zig.zig").Guid.initString("69e971f0-23ce-11cf-ad60-00aa00a74ccd");
pub const IID_ITransactionResourceAsync = &IID_ITransactionResourceAsync_Value;
pub const ITransactionResourceAsync = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
PrepareRequest: fn(
self: *const ITransactionResourceAsync,
fRetaining: BOOL,
grfRM: u32,
fWantMoniker: BOOL,
fSinglePhase: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CommitRequest: fn(
self: *const ITransactionResourceAsync,
grfRM: u32,
pNewUOW: ?*BOID,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AbortRequest: fn(
self: *const ITransactionResourceAsync,
pboidReason: ?*BOID,
fRetaining: BOOL,
pNewUOW: ?*BOID,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TMDown: fn(
self: *const ITransactionResourceAsync,
) 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 ITransactionResourceAsync_PrepareRequest(self: *const T, fRetaining: BOOL, grfRM: u32, fWantMoniker: BOOL, fSinglePhase: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionResourceAsync.VTable, self.vtable).PrepareRequest(@ptrCast(*const ITransactionResourceAsync, self), fRetaining, grfRM, fWantMoniker, fSinglePhase);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransactionResourceAsync_CommitRequest(self: *const T, grfRM: u32, pNewUOW: ?*BOID) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionResourceAsync.VTable, self.vtable).CommitRequest(@ptrCast(*const ITransactionResourceAsync, self), grfRM, pNewUOW);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransactionResourceAsync_AbortRequest(self: *const T, pboidReason: ?*BOID, fRetaining: BOOL, pNewUOW: ?*BOID) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionResourceAsync.VTable, self.vtable).AbortRequest(@ptrCast(*const ITransactionResourceAsync, self), pboidReason, fRetaining, pNewUOW);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransactionResourceAsync_TMDown(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionResourceAsync.VTable, self.vtable).TMDown(@ptrCast(*const ITransactionResourceAsync, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ITransactionLastResourceAsync_Value = @import("../zig.zig").Guid.initString("c82bd532-5b30-11d3-8a91-00c04f79eb6d");
pub const IID_ITransactionLastResourceAsync = &IID_ITransactionLastResourceAsync_Value;
pub const ITransactionLastResourceAsync = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
DelegateCommit: fn(
self: *const ITransactionLastResourceAsync,
grfRM: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ForgetRequest: fn(
self: *const ITransactionLastResourceAsync,
pNewUOW: ?*BOID,
) 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 ITransactionLastResourceAsync_DelegateCommit(self: *const T, grfRM: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionLastResourceAsync.VTable, self.vtable).DelegateCommit(@ptrCast(*const ITransactionLastResourceAsync, self), grfRM);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransactionLastResourceAsync_ForgetRequest(self: *const T, pNewUOW: ?*BOID) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionLastResourceAsync.VTable, self.vtable).ForgetRequest(@ptrCast(*const ITransactionLastResourceAsync, self), pNewUOW);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ITransactionResource_Value = @import("../zig.zig").Guid.initString("ee5ff7b3-4572-11d0-9452-00a0c905416e");
pub const IID_ITransactionResource = &IID_ITransactionResource_Value;
pub const ITransactionResource = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
PrepareRequest: fn(
self: *const ITransactionResource,
fRetaining: BOOL,
grfRM: u32,
fWantMoniker: BOOL,
fSinglePhase: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CommitRequest: fn(
self: *const ITransactionResource,
grfRM: u32,
pNewUOW: ?*BOID,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AbortRequest: fn(
self: *const ITransactionResource,
pboidReason: ?*BOID,
fRetaining: BOOL,
pNewUOW: ?*BOID,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TMDown: fn(
self: *const ITransactionResource,
) 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 ITransactionResource_PrepareRequest(self: *const T, fRetaining: BOOL, grfRM: u32, fWantMoniker: BOOL, fSinglePhase: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionResource.VTable, self.vtable).PrepareRequest(@ptrCast(*const ITransactionResource, self), fRetaining, grfRM, fWantMoniker, fSinglePhase);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransactionResource_CommitRequest(self: *const T, grfRM: u32, pNewUOW: ?*BOID) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionResource.VTable, self.vtable).CommitRequest(@ptrCast(*const ITransactionResource, self), grfRM, pNewUOW);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransactionResource_AbortRequest(self: *const T, pboidReason: ?*BOID, fRetaining: BOOL, pNewUOW: ?*BOID) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionResource.VTable, self.vtable).AbortRequest(@ptrCast(*const ITransactionResource, self), pboidReason, fRetaining, pNewUOW);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransactionResource_TMDown(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionResource.VTable, self.vtable).TMDown(@ptrCast(*const ITransactionResource, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ITransactionEnlistmentAsync_Value = @import("../zig.zig").Guid.initString("0fb15081-af41-11ce-bd2b-204c4f4f5020");
pub const IID_ITransactionEnlistmentAsync = &IID_ITransactionEnlistmentAsync_Value;
pub const ITransactionEnlistmentAsync = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
PrepareRequestDone: fn(
self: *const ITransactionEnlistmentAsync,
hr: HRESULT,
pmk: ?*IMoniker,
pboidReason: ?*BOID,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CommitRequestDone: fn(
self: *const ITransactionEnlistmentAsync,
hr: HRESULT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AbortRequestDone: fn(
self: *const ITransactionEnlistmentAsync,
hr: HRESULT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransactionEnlistmentAsync_PrepareRequestDone(self: *const T, hr: HRESULT, pmk: ?*IMoniker, pboidReason: ?*BOID) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionEnlistmentAsync.VTable, self.vtable).PrepareRequestDone(@ptrCast(*const ITransactionEnlistmentAsync, self), hr, pmk, pboidReason);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransactionEnlistmentAsync_CommitRequestDone(self: *const T, hr: HRESULT) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionEnlistmentAsync.VTable, self.vtable).CommitRequestDone(@ptrCast(*const ITransactionEnlistmentAsync, self), hr);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransactionEnlistmentAsync_AbortRequestDone(self: *const T, hr: HRESULT) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionEnlistmentAsync.VTable, self.vtable).AbortRequestDone(@ptrCast(*const ITransactionEnlistmentAsync, self), hr);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ITransactionLastEnlistmentAsync_Value = @import("../zig.zig").Guid.initString("c82bd533-5b30-11d3-8a91-00c04f79eb6d");
pub const IID_ITransactionLastEnlistmentAsync = &IID_ITransactionLastEnlistmentAsync_Value;
pub const ITransactionLastEnlistmentAsync = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
TransactionOutcome: fn(
self: *const ITransactionLastEnlistmentAsync,
XactStat: XACTSTAT,
pboidReason: ?*BOID,
) 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 ITransactionLastEnlistmentAsync_TransactionOutcome(self: *const T, XactStat: XACTSTAT, pboidReason: ?*BOID) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionLastEnlistmentAsync.VTable, self.vtable).TransactionOutcome(@ptrCast(*const ITransactionLastEnlistmentAsync, self), XactStat, pboidReason);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ITransactionExportFactory_Value = @import("../zig.zig").Guid.initString("e1cf9b53-8745-11ce-a9ba-00aa006c3706");
pub const IID_ITransactionExportFactory = &IID_ITransactionExportFactory_Value;
pub const ITransactionExportFactory = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetRemoteClassId: fn(
self: *const ITransactionExportFactory,
pclsid: ?*Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Create: fn(
self: *const ITransactionExportFactory,
cbWhereabouts: u32,
rgbWhereabouts: [*:0]u8,
ppExport: ?*?*ITransactionExport,
) 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 ITransactionExportFactory_GetRemoteClassId(self: *const T, pclsid: ?*Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionExportFactory.VTable, self.vtable).GetRemoteClassId(@ptrCast(*const ITransactionExportFactory, self), pclsid);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransactionExportFactory_Create(self: *const T, cbWhereabouts: u32, rgbWhereabouts: [*:0]u8, ppExport: ?*?*ITransactionExport) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionExportFactory.VTable, self.vtable).Create(@ptrCast(*const ITransactionExportFactory, self), cbWhereabouts, rgbWhereabouts, ppExport);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ITransactionImportWhereabouts_Value = @import("../zig.zig").Guid.initString("0141fda4-8fc0-11ce-bd18-204c4f4f5020");
pub const IID_ITransactionImportWhereabouts = &IID_ITransactionImportWhereabouts_Value;
pub const ITransactionImportWhereabouts = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetWhereaboutsSize: fn(
self: *const ITransactionImportWhereabouts,
pcbWhereabouts: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetWhereabouts: fn(
self: *const ITransactionImportWhereabouts,
cbWhereabouts: u32,
rgbWhereabouts: [*:0]u8,
pcbUsed: ?*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 ITransactionImportWhereabouts_GetWhereaboutsSize(self: *const T, pcbWhereabouts: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionImportWhereabouts.VTable, self.vtable).GetWhereaboutsSize(@ptrCast(*const ITransactionImportWhereabouts, self), pcbWhereabouts);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransactionImportWhereabouts_GetWhereabouts(self: *const T, cbWhereabouts: u32, rgbWhereabouts: [*:0]u8, pcbUsed: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionImportWhereabouts.VTable, self.vtable).GetWhereabouts(@ptrCast(*const ITransactionImportWhereabouts, self), cbWhereabouts, rgbWhereabouts, pcbUsed);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ITransactionExport_Value = @import("../zig.zig").Guid.initString("0141fda5-8fc0-11ce-bd18-204c4f4f5020");
pub const IID_ITransactionExport = &IID_ITransactionExport_Value;
pub const ITransactionExport = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Export: fn(
self: *const ITransactionExport,
punkTransaction: ?*IUnknown,
pcbTransactionCookie: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetTransactionCookie: fn(
self: *const ITransactionExport,
punkTransaction: ?*IUnknown,
cbTransactionCookie: u32,
rgbTransactionCookie: [*:0]u8,
pcbUsed: ?*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 ITransactionExport_Export(self: *const T, punkTransaction: ?*IUnknown, pcbTransactionCookie: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionExport.VTable, self.vtable).Export(@ptrCast(*const ITransactionExport, self), punkTransaction, pcbTransactionCookie);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransactionExport_GetTransactionCookie(self: *const T, punkTransaction: ?*IUnknown, cbTransactionCookie: u32, rgbTransactionCookie: [*:0]u8, pcbUsed: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionExport.VTable, self.vtable).GetTransactionCookie(@ptrCast(*const ITransactionExport, self), punkTransaction, cbTransactionCookie, rgbTransactionCookie, pcbUsed);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ITransactionImport_Value = @import("../zig.zig").Guid.initString("e1cf9b5a-8745-11ce-a9ba-00aa006c3706");
pub const IID_ITransactionImport = &IID_ITransactionImport_Value;
pub const ITransactionImport = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Import: fn(
self: *const ITransactionImport,
cbTransactionCookie: u32,
rgbTransactionCookie: [*:0]u8,
piid: ?*const Guid,
ppvTransaction: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransactionImport_Import(self: *const T, cbTransactionCookie: u32, rgbTransactionCookie: [*:0]u8, piid: ?*const Guid, ppvTransaction: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionImport.VTable, self.vtable).Import(@ptrCast(*const ITransactionImport, self), cbTransactionCookie, rgbTransactionCookie, piid, ppvTransaction);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ITipTransaction_Value = @import("../zig.zig").Guid.initString("17cf72d0-bac5-11d1-b1bf-00c04fc2f3ef");
pub const IID_ITipTransaction = &IID_ITipTransaction_Value;
pub const ITipTransaction = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Push: fn(
self: *const ITipTransaction,
i_pszRemoteTmUrl: ?*u8,
o_ppszRemoteTxUrl: ?*?PSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetTransactionUrl: fn(
self: *const ITipTransaction,
o_ppszLocalTxUrl: ?*?PSTR,
) 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 ITipTransaction_Push(self: *const T, i_pszRemoteTmUrl: ?*u8, o_ppszRemoteTxUrl: ?*?PSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITipTransaction.VTable, self.vtable).Push(@ptrCast(*const ITipTransaction, self), i_pszRemoteTmUrl, o_ppszRemoteTxUrl);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITipTransaction_GetTransactionUrl(self: *const T, o_ppszLocalTxUrl: ?*?PSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITipTransaction.VTable, self.vtable).GetTransactionUrl(@ptrCast(*const ITipTransaction, self), o_ppszLocalTxUrl);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ITipHelper_Value = @import("../zig.zig").Guid.initString("17cf72d1-bac5-11d1-b1bf-00c04fc2f3ef");
pub const IID_ITipHelper = &IID_ITipHelper_Value;
pub const ITipHelper = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Pull: fn(
self: *const ITipHelper,
i_pszTxUrl: ?*u8,
o_ppITransaction: ?*?*ITransaction,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
PullAsync: fn(
self: *const ITipHelper,
i_pszTxUrl: ?*u8,
i_pTipPullSink: ?*ITipPullSink,
o_ppITransaction: ?*?*ITransaction,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLocalTmUrl: fn(
self: *const ITipHelper,
o_ppszLocalTmUrl: ?*?*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 ITipHelper_Pull(self: *const T, i_pszTxUrl: ?*u8, o_ppITransaction: ?*?*ITransaction) callconv(.Inline) HRESULT {
return @ptrCast(*const ITipHelper.VTable, self.vtable).Pull(@ptrCast(*const ITipHelper, self), i_pszTxUrl, o_ppITransaction);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITipHelper_PullAsync(self: *const T, i_pszTxUrl: ?*u8, i_pTipPullSink: ?*ITipPullSink, o_ppITransaction: ?*?*ITransaction) callconv(.Inline) HRESULT {
return @ptrCast(*const ITipHelper.VTable, self.vtable).PullAsync(@ptrCast(*const ITipHelper, self), i_pszTxUrl, i_pTipPullSink, o_ppITransaction);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITipHelper_GetLocalTmUrl(self: *const T, o_ppszLocalTmUrl: ?*?*u8) callconv(.Inline) HRESULT {
return @ptrCast(*const ITipHelper.VTable, self.vtable).GetLocalTmUrl(@ptrCast(*const ITipHelper, self), o_ppszLocalTmUrl);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ITipPullSink_Value = @import("../zig.zig").Guid.initString("17cf72d2-bac5-11d1-b1bf-00c04fc2f3ef");
pub const IID_ITipPullSink = &IID_ITipPullSink_Value;
pub const ITipPullSink = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
PullComplete: fn(
self: *const ITipPullSink,
i_hrPull: HRESULT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITipPullSink_PullComplete(self: *const T, i_hrPull: HRESULT) callconv(.Inline) HRESULT {
return @ptrCast(*const ITipPullSink.VTable, self.vtable).PullComplete(@ptrCast(*const ITipPullSink, self), i_hrPull);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDtcNetworkAccessConfig_Value = @import("../zig.zig").Guid.initString("9797c15d-a428-4291-87b6-0995031a678d");
pub const IID_IDtcNetworkAccessConfig = &IID_IDtcNetworkAccessConfig_Value;
pub const IDtcNetworkAccessConfig = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetAnyNetworkAccess: fn(
self: *const IDtcNetworkAccessConfig,
pbAnyNetworkAccess: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetAnyNetworkAccess: fn(
self: *const IDtcNetworkAccessConfig,
bAnyNetworkAccess: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetNetworkAdministrationAccess: fn(
self: *const IDtcNetworkAccessConfig,
pbNetworkAdministrationAccess: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetNetworkAdministrationAccess: fn(
self: *const IDtcNetworkAccessConfig,
bNetworkAdministrationAccess: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetNetworkTransactionAccess: fn(
self: *const IDtcNetworkAccessConfig,
pbNetworkTransactionAccess: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetNetworkTransactionAccess: fn(
self: *const IDtcNetworkAccessConfig,
bNetworkTransactionAccess: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetNetworkClientAccess: fn(
self: *const IDtcNetworkAccessConfig,
pbNetworkClientAccess: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetNetworkClientAccess: fn(
self: *const IDtcNetworkAccessConfig,
bNetworkClientAccess: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetNetworkTIPAccess: fn(
self: *const IDtcNetworkAccessConfig,
pbNetworkTIPAccess: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetNetworkTIPAccess: fn(
self: *const IDtcNetworkAccessConfig,
bNetworkTIPAccess: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetXAAccess: fn(
self: *const IDtcNetworkAccessConfig,
pbXAAccess: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetXAAccess: fn(
self: *const IDtcNetworkAccessConfig,
bXAAccess: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RestartDtcService: fn(
self: *const IDtcNetworkAccessConfig,
) 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 IDtcNetworkAccessConfig_GetAnyNetworkAccess(self: *const T, pbAnyNetworkAccess: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcNetworkAccessConfig.VTable, self.vtable).GetAnyNetworkAccess(@ptrCast(*const IDtcNetworkAccessConfig, self), pbAnyNetworkAccess);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcNetworkAccessConfig_SetAnyNetworkAccess(self: *const T, bAnyNetworkAccess: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcNetworkAccessConfig.VTable, self.vtable).SetAnyNetworkAccess(@ptrCast(*const IDtcNetworkAccessConfig, self), bAnyNetworkAccess);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcNetworkAccessConfig_GetNetworkAdministrationAccess(self: *const T, pbNetworkAdministrationAccess: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcNetworkAccessConfig.VTable, self.vtable).GetNetworkAdministrationAccess(@ptrCast(*const IDtcNetworkAccessConfig, self), pbNetworkAdministrationAccess);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcNetworkAccessConfig_SetNetworkAdministrationAccess(self: *const T, bNetworkAdministrationAccess: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcNetworkAccessConfig.VTable, self.vtable).SetNetworkAdministrationAccess(@ptrCast(*const IDtcNetworkAccessConfig, self), bNetworkAdministrationAccess);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcNetworkAccessConfig_GetNetworkTransactionAccess(self: *const T, pbNetworkTransactionAccess: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcNetworkAccessConfig.VTable, self.vtable).GetNetworkTransactionAccess(@ptrCast(*const IDtcNetworkAccessConfig, self), pbNetworkTransactionAccess);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcNetworkAccessConfig_SetNetworkTransactionAccess(self: *const T, bNetworkTransactionAccess: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcNetworkAccessConfig.VTable, self.vtable).SetNetworkTransactionAccess(@ptrCast(*const IDtcNetworkAccessConfig, self), bNetworkTransactionAccess);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcNetworkAccessConfig_GetNetworkClientAccess(self: *const T, pbNetworkClientAccess: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcNetworkAccessConfig.VTable, self.vtable).GetNetworkClientAccess(@ptrCast(*const IDtcNetworkAccessConfig, self), pbNetworkClientAccess);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcNetworkAccessConfig_SetNetworkClientAccess(self: *const T, bNetworkClientAccess: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcNetworkAccessConfig.VTable, self.vtable).SetNetworkClientAccess(@ptrCast(*const IDtcNetworkAccessConfig, self), bNetworkClientAccess);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcNetworkAccessConfig_GetNetworkTIPAccess(self: *const T, pbNetworkTIPAccess: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcNetworkAccessConfig.VTable, self.vtable).GetNetworkTIPAccess(@ptrCast(*const IDtcNetworkAccessConfig, self), pbNetworkTIPAccess);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcNetworkAccessConfig_SetNetworkTIPAccess(self: *const T, bNetworkTIPAccess: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcNetworkAccessConfig.VTable, self.vtable).SetNetworkTIPAccess(@ptrCast(*const IDtcNetworkAccessConfig, self), bNetworkTIPAccess);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcNetworkAccessConfig_GetXAAccess(self: *const T, pbXAAccess: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcNetworkAccessConfig.VTable, self.vtable).GetXAAccess(@ptrCast(*const IDtcNetworkAccessConfig, self), pbXAAccess);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcNetworkAccessConfig_SetXAAccess(self: *const T, bXAAccess: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcNetworkAccessConfig.VTable, self.vtable).SetXAAccess(@ptrCast(*const IDtcNetworkAccessConfig, self), bXAAccess);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcNetworkAccessConfig_RestartDtcService(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcNetworkAccessConfig.VTable, self.vtable).RestartDtcService(@ptrCast(*const IDtcNetworkAccessConfig, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const AUTHENTICATION_LEVEL = enum(i32) {
NO_AUTHENTICATION_REQUIRED = 0,
INCOMING_AUTHENTICATION_REQUIRED = 1,
MUTUAL_AUTHENTICATION_REQUIRED = 2,
};
pub const NO_AUTHENTICATION_REQUIRED = AUTHENTICATION_LEVEL.NO_AUTHENTICATION_REQUIRED;
pub const INCOMING_AUTHENTICATION_REQUIRED = AUTHENTICATION_LEVEL.INCOMING_AUTHENTICATION_REQUIRED;
pub const MUTUAL_AUTHENTICATION_REQUIRED = AUTHENTICATION_LEVEL.MUTUAL_AUTHENTICATION_REQUIRED;
const IID_IDtcNetworkAccessConfig2_Value = @import("../zig.zig").Guid.initString("a7aa013b-eb7d-4f42-b41c-b2dec09ae034");
pub const IID_IDtcNetworkAccessConfig2 = &IID_IDtcNetworkAccessConfig2_Value;
pub const IDtcNetworkAccessConfig2 = extern struct {
pub const VTable = extern struct {
base: IDtcNetworkAccessConfig.VTable,
GetNetworkInboundAccess: fn(
self: *const IDtcNetworkAccessConfig2,
pbInbound: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetNetworkOutboundAccess: fn(
self: *const IDtcNetworkAccessConfig2,
pbOutbound: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetNetworkInboundAccess: fn(
self: *const IDtcNetworkAccessConfig2,
bInbound: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetNetworkOutboundAccess: fn(
self: *const IDtcNetworkAccessConfig2,
bOutbound: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetAuthenticationLevel: fn(
self: *const IDtcNetworkAccessConfig2,
pAuthLevel: ?*AUTHENTICATION_LEVEL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetAuthenticationLevel: fn(
self: *const IDtcNetworkAccessConfig2,
AuthLevel: AUTHENTICATION_LEVEL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDtcNetworkAccessConfig.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcNetworkAccessConfig2_GetNetworkInboundAccess(self: *const T, pbInbound: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcNetworkAccessConfig2.VTable, self.vtable).GetNetworkInboundAccess(@ptrCast(*const IDtcNetworkAccessConfig2, self), pbInbound);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcNetworkAccessConfig2_GetNetworkOutboundAccess(self: *const T, pbOutbound: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcNetworkAccessConfig2.VTable, self.vtable).GetNetworkOutboundAccess(@ptrCast(*const IDtcNetworkAccessConfig2, self), pbOutbound);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcNetworkAccessConfig2_SetNetworkInboundAccess(self: *const T, bInbound: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcNetworkAccessConfig2.VTable, self.vtable).SetNetworkInboundAccess(@ptrCast(*const IDtcNetworkAccessConfig2, self), bInbound);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcNetworkAccessConfig2_SetNetworkOutboundAccess(self: *const T, bOutbound: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcNetworkAccessConfig2.VTable, self.vtable).SetNetworkOutboundAccess(@ptrCast(*const IDtcNetworkAccessConfig2, self), bOutbound);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcNetworkAccessConfig2_GetAuthenticationLevel(self: *const T, pAuthLevel: ?*AUTHENTICATION_LEVEL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcNetworkAccessConfig2.VTable, self.vtable).GetAuthenticationLevel(@ptrCast(*const IDtcNetworkAccessConfig2, self), pAuthLevel);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcNetworkAccessConfig2_SetAuthenticationLevel(self: *const T, AuthLevel: AUTHENTICATION_LEVEL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcNetworkAccessConfig2.VTable, self.vtable).SetAuthenticationLevel(@ptrCast(*const IDtcNetworkAccessConfig2, self), AuthLevel);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDtcNetworkAccessConfig3_Value = @import("../zig.zig").Guid.initString("76e4b4f3-2ca5-466b-89d5-fd218ee75b49");
pub const IID_IDtcNetworkAccessConfig3 = &IID_IDtcNetworkAccessConfig3_Value;
pub const IDtcNetworkAccessConfig3 = extern struct {
pub const VTable = extern struct {
base: IDtcNetworkAccessConfig2.VTable,
GetLUAccess: fn(
self: *const IDtcNetworkAccessConfig3,
pbLUAccess: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetLUAccess: fn(
self: *const IDtcNetworkAccessConfig3,
bLUAccess: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDtcNetworkAccessConfig2.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcNetworkAccessConfig3_GetLUAccess(self: *const T, pbLUAccess: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcNetworkAccessConfig3.VTable, self.vtable).GetLUAccess(@ptrCast(*const IDtcNetworkAccessConfig3, self), pbLUAccess);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcNetworkAccessConfig3_SetLUAccess(self: *const T, bLUAccess: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcNetworkAccessConfig3.VTable, self.vtable).SetLUAccess(@ptrCast(*const IDtcNetworkAccessConfig3, self), bLUAccess);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const xid_t = extern struct {
formatID: i32,
gtrid_length: i32,
bqual_length: i32,
data: [128]CHAR,
};
pub const xa_switch_t = extern struct {
name: [32]CHAR,
flags: i32,
version: i32,
xa_open_entry: isize,
xa_close_entry: isize,
xa_start_entry: isize,
xa_end_entry: isize,
xa_rollback_entry: isize,
xa_prepare_entry: isize,
xa_commit_entry: isize,
xa_recover_entry: isize,
xa_forget_entry: isize,
xa_complete_entry: isize,
};
pub const XA_OPEN_EPT = fn(
param0: ?PSTR,
param1: i32,
param2: i32,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const XA_CLOSE_EPT = fn(
param0: ?PSTR,
param1: i32,
param2: i32,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const XA_START_EPT = fn(
param0: ?*xid_t,
param1: i32,
param2: i32,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const XA_END_EPT = fn(
param0: ?*xid_t,
param1: i32,
param2: i32,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const XA_ROLLBACK_EPT = fn(
param0: ?*xid_t,
param1: i32,
param2: i32,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const XA_PREPARE_EPT = fn(
param0: ?*xid_t,
param1: i32,
param2: i32,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const XA_COMMIT_EPT = fn(
param0: ?*xid_t,
param1: i32,
param2: i32,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const XA_RECOVER_EPT = fn(
param0: ?*xid_t,
param1: i32,
param2: i32,
param3: i32,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const XA_FORGET_EPT = fn(
param0: ?*xid_t,
param1: i32,
param2: i32,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const XA_COMPLETE_EPT = fn(
param0: ?*i32,
param1: ?*i32,
param2: i32,
param3: i32,
) callconv(@import("std").os.windows.WINAPI) i32;
const IID_IDtcToXaMapper_Value = @import("../zig.zig").Guid.initString("64ffabe0-7ce9-11d0-8ce6-00c04fdc877e");
pub const IID_IDtcToXaMapper = &IID_IDtcToXaMapper_Value;
pub const IDtcToXaMapper = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
RequestNewResourceManager: fn(
self: *const IDtcToXaMapper,
pszDSN: ?PSTR,
pszClientDllName: ?PSTR,
pdwRMCookie: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TranslateTridToXid: fn(
self: *const IDtcToXaMapper,
pdwITransaction: ?*u32,
dwRMCookie: u32,
pXid: ?*xid_t,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
EnlistResourceManager: fn(
self: *const IDtcToXaMapper,
dwRMCookie: u32,
pdwITransaction: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ReleaseResourceManager: fn(
self: *const IDtcToXaMapper,
dwRMCookie: 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 IDtcToXaMapper_RequestNewResourceManager(self: *const T, pszDSN: ?PSTR, pszClientDllName: ?PSTR, pdwRMCookie: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcToXaMapper.VTable, self.vtable).RequestNewResourceManager(@ptrCast(*const IDtcToXaMapper, self), pszDSN, pszClientDllName, pdwRMCookie);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcToXaMapper_TranslateTridToXid(self: *const T, pdwITransaction: ?*u32, dwRMCookie: u32, pXid: ?*xid_t) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcToXaMapper.VTable, self.vtable).TranslateTridToXid(@ptrCast(*const IDtcToXaMapper, self), pdwITransaction, dwRMCookie, pXid);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcToXaMapper_EnlistResourceManager(self: *const T, dwRMCookie: u32, pdwITransaction: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcToXaMapper.VTable, self.vtable).EnlistResourceManager(@ptrCast(*const IDtcToXaMapper, self), dwRMCookie, pdwITransaction);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcToXaMapper_ReleaseResourceManager(self: *const T, dwRMCookie: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcToXaMapper.VTable, self.vtable).ReleaseResourceManager(@ptrCast(*const IDtcToXaMapper, self), dwRMCookie);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDtcToXaHelperFactory_Value = @import("../zig.zig").Guid.initString("a9861610-304a-11d1-9813-00a0c905416e");
pub const IID_IDtcToXaHelperFactory = &IID_IDtcToXaHelperFactory_Value;
pub const IDtcToXaHelperFactory = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Create: fn(
self: *const IDtcToXaHelperFactory,
pszDSN: ?PSTR,
pszClientDllName: ?PSTR,
pguidRm: ?*Guid,
ppXaHelper: ?*?*IDtcToXaHelper,
) 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 IDtcToXaHelperFactory_Create(self: *const T, pszDSN: ?PSTR, pszClientDllName: ?PSTR, pguidRm: ?*Guid, ppXaHelper: ?*?*IDtcToXaHelper) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcToXaHelperFactory.VTable, self.vtable).Create(@ptrCast(*const IDtcToXaHelperFactory, self), pszDSN, pszClientDllName, pguidRm, ppXaHelper);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDtcToXaHelper_Value = @import("../zig.zig").Guid.initString("a9861611-304a-11d1-9813-00a0c905416e");
pub const IID_IDtcToXaHelper = &IID_IDtcToXaHelper_Value;
pub const IDtcToXaHelper = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Close: fn(
self: *const IDtcToXaHelper,
i_fDoRecovery: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TranslateTridToXid: fn(
self: *const IDtcToXaHelper,
pITransaction: ?*ITransaction,
pguidBqual: ?*Guid,
pXid: ?*xid_t,
) 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 IDtcToXaHelper_Close(self: *const T, i_fDoRecovery: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcToXaHelper.VTable, self.vtable).Close(@ptrCast(*const IDtcToXaHelper, self), i_fDoRecovery);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcToXaHelper_TranslateTridToXid(self: *const T, pITransaction: ?*ITransaction, pguidBqual: ?*Guid, pXid: ?*xid_t) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcToXaHelper.VTable, self.vtable).TranslateTridToXid(@ptrCast(*const IDtcToXaHelper, self), pITransaction, pguidBqual, pXid);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDtcToXaHelperSinglePipe_Value = @import("../zig.zig").Guid.initString("47ed4971-53b3-11d1-bbb9-00c04fd658f6");
pub const IID_IDtcToXaHelperSinglePipe = &IID_IDtcToXaHelperSinglePipe_Value;
pub const IDtcToXaHelperSinglePipe = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
XARMCreate: fn(
self: *const IDtcToXaHelperSinglePipe,
pszDSN: ?PSTR,
pszClientDll: ?PSTR,
pdwRMCookie: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ConvertTridToXID: fn(
self: *const IDtcToXaHelperSinglePipe,
pdwITrans: ?*u32,
dwRMCookie: u32,
pxid: ?*xid_t,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
EnlistWithRM: fn(
self: *const IDtcToXaHelperSinglePipe,
dwRMCookie: u32,
i_pITransaction: ?*ITransaction,
i_pITransRes: ?*ITransactionResourceAsync,
o_ppITransEnslitment: ?*?*ITransactionEnlistmentAsync,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ReleaseRMCookie: fn(
self: *const IDtcToXaHelperSinglePipe,
i_dwRMCookie: u32,
i_fNormal: BOOL,
) 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 IDtcToXaHelperSinglePipe_XARMCreate(self: *const T, pszDSN: ?PSTR, pszClientDll: ?PSTR, pdwRMCookie: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcToXaHelperSinglePipe.VTable, self.vtable).XARMCreate(@ptrCast(*const IDtcToXaHelperSinglePipe, self), pszDSN, pszClientDll, pdwRMCookie);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcToXaHelperSinglePipe_ConvertTridToXID(self: *const T, pdwITrans: ?*u32, dwRMCookie: u32, pxid: ?*xid_t) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcToXaHelperSinglePipe.VTable, self.vtable).ConvertTridToXID(@ptrCast(*const IDtcToXaHelperSinglePipe, self), pdwITrans, dwRMCookie, pxid);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcToXaHelperSinglePipe_EnlistWithRM(self: *const T, dwRMCookie: u32, i_pITransaction: ?*ITransaction, i_pITransRes: ?*ITransactionResourceAsync, o_ppITransEnslitment: ?*?*ITransactionEnlistmentAsync) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcToXaHelperSinglePipe.VTable, self.vtable).EnlistWithRM(@ptrCast(*const IDtcToXaHelperSinglePipe, self), dwRMCookie, i_pITransaction, i_pITransRes, o_ppITransEnslitment);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcToXaHelperSinglePipe_ReleaseRMCookie(self: *const T, i_dwRMCookie: u32, i_fNormal: BOOL) callconv(.Inline) void {
return @ptrCast(*const IDtcToXaHelperSinglePipe.VTable, self.vtable).ReleaseRMCookie(@ptrCast(*const IDtcToXaHelperSinglePipe, self), i_dwRMCookie, i_fNormal);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const APPLICATIONTYPE = enum(i32) {
LOCAL_APPLICATIONTYPE = 0,
CLUSTERRESOURCE_APPLICATIONTYPE = 1,
};
pub const LOCAL_APPLICATIONTYPE = APPLICATIONTYPE.LOCAL_APPLICATIONTYPE;
pub const CLUSTERRESOURCE_APPLICATIONTYPE = APPLICATIONTYPE.CLUSTERRESOURCE_APPLICATIONTYPE;
pub const OLE_TM_CONFIG_PARAMS_V1 = extern struct {
dwVersion: u32,
dwcConcurrencyHint: u32,
};
pub const OLE_TM_CONFIG_PARAMS_V2 = extern struct {
dwVersion: u32,
dwcConcurrencyHint: u32,
applicationType: APPLICATIONTYPE,
clusterResourceId: Guid,
};
pub const XACT_DTC_CONSTANTS = enum(i32) {
XACT_E_CONNECTION_REQUEST_DENIED = -2147168000,
XACT_E_TOOMANY_ENLISTMENTS = -2147167999,
XACT_E_DUPLICATE_GUID = -2147167998,
XACT_E_NOTSINGLEPHASE = -2147167997,
XACT_E_RECOVERYALREADYDONE = -2147167996,
XACT_E_PROTOCOL = -2147167995,
XACT_E_RM_FAILURE = -2147167994,
XACT_E_RECOVERY_FAILED = -2147167993,
XACT_E_LU_NOT_FOUND = -2147167992,
XACT_E_DUPLICATE_LU = -2147167991,
XACT_E_LU_NOT_CONNECTED = -2147167990,
XACT_E_DUPLICATE_TRANSID = -2147167989,
XACT_E_LU_BUSY = -2147167988,
XACT_E_LU_NO_RECOVERY_PROCESS = -2147167987,
XACT_E_LU_DOWN = -2147167986,
XACT_E_LU_RECOVERING = -2147167985,
XACT_E_LU_RECOVERY_MISMATCH = -2147167984,
XACT_E_RM_UNAVAILABLE = -2147167983,
XACT_E_LRMRECOVERYALREADYDONE = -2147167982,
XACT_E_NOLASTRESOURCEINTERFACE = -2147167981,
XACT_S_NONOTIFY = 315648,
XACT_OK_NONOTIFY = 315649,
dwUSER_MS_SQLSERVER = 65535,
};
pub const XACT_E_CONNECTION_REQUEST_DENIED = XACT_DTC_CONSTANTS.XACT_E_CONNECTION_REQUEST_DENIED;
pub const XACT_E_TOOMANY_ENLISTMENTS = XACT_DTC_CONSTANTS.XACT_E_TOOMANY_ENLISTMENTS;
pub const XACT_E_DUPLICATE_GUID = XACT_DTC_CONSTANTS.XACT_E_DUPLICATE_GUID;
pub const XACT_E_NOTSINGLEPHASE = XACT_DTC_CONSTANTS.XACT_E_NOTSINGLEPHASE;
pub const XACT_E_RECOVERYALREADYDONE = XACT_DTC_CONSTANTS.XACT_E_RECOVERYALREADYDONE;
pub const XACT_E_PROTOCOL = XACT_DTC_CONSTANTS.XACT_E_PROTOCOL;
pub const XACT_E_RM_FAILURE = XACT_DTC_CONSTANTS.XACT_E_RM_FAILURE;
pub const XACT_E_RECOVERY_FAILED = XACT_DTC_CONSTANTS.XACT_E_RECOVERY_FAILED;
pub const XACT_E_LU_NOT_FOUND = XACT_DTC_CONSTANTS.XACT_E_LU_NOT_FOUND;
pub const XACT_E_DUPLICATE_LU = XACT_DTC_CONSTANTS.XACT_E_DUPLICATE_LU;
pub const XACT_E_LU_NOT_CONNECTED = XACT_DTC_CONSTANTS.XACT_E_LU_NOT_CONNECTED;
pub const XACT_E_DUPLICATE_TRANSID = XACT_DTC_CONSTANTS.XACT_E_DUPLICATE_TRANSID;
pub const XACT_E_LU_BUSY = XACT_DTC_CONSTANTS.XACT_E_LU_BUSY;
pub const XACT_E_LU_NO_RECOVERY_PROCESS = XACT_DTC_CONSTANTS.XACT_E_LU_NO_RECOVERY_PROCESS;
pub const XACT_E_LU_DOWN = XACT_DTC_CONSTANTS.XACT_E_LU_DOWN;
pub const XACT_E_LU_RECOVERING = XACT_DTC_CONSTANTS.XACT_E_LU_RECOVERING;
pub const XACT_E_LU_RECOVERY_MISMATCH = XACT_DTC_CONSTANTS.XACT_E_LU_RECOVERY_MISMATCH;
pub const XACT_E_RM_UNAVAILABLE = XACT_DTC_CONSTANTS.XACT_E_RM_UNAVAILABLE;
pub const XACT_E_LRMRECOVERYALREADYDONE = XACT_DTC_CONSTANTS.XACT_E_LRMRECOVERYALREADYDONE;
pub const XACT_E_NOLASTRESOURCEINTERFACE = XACT_DTC_CONSTANTS.XACT_E_NOLASTRESOURCEINTERFACE;
pub const XACT_S_NONOTIFY = XACT_DTC_CONSTANTS.XACT_S_NONOTIFY;
pub const XACT_OK_NONOTIFY = XACT_DTC_CONSTANTS.XACT_OK_NONOTIFY;
pub const dwUSER_MS_SQLSERVER = XACT_DTC_CONSTANTS.dwUSER_MS_SQLSERVER;
const IID_IXATransLookup_Value = @import("../zig.zig").Guid.initString("f3b1f131-eeda-11ce-aed4-00aa0051e2c4");
pub const IID_IXATransLookup = &IID_IXATransLookup_Value;
pub const IXATransLookup = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Lookup: fn(
self: *const IXATransLookup,
ppTransaction: ?*?*ITransaction,
) 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 IXATransLookup_Lookup(self: *const T, ppTransaction: ?*?*ITransaction) callconv(.Inline) HRESULT {
return @ptrCast(*const IXATransLookup.VTable, self.vtable).Lookup(@ptrCast(*const IXATransLookup, self), ppTransaction);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXATransLookup2_Value = @import("../zig.zig").Guid.initString("bf193c85-0d1a-4290-b88f-d2cb8873d1e7");
pub const IID_IXATransLookup2 = &IID_IXATransLookup2_Value;
pub const IXATransLookup2 = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Lookup: fn(
self: *const IXATransLookup2,
pXID: ?*xid_t,
ppTransaction: ?*?*ITransaction,
) 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 IXATransLookup2_Lookup(self: *const T, pXID: ?*xid_t, ppTransaction: ?*?*ITransaction) callconv(.Inline) HRESULT {
return @ptrCast(*const IXATransLookup2.VTable, self.vtable).Lookup(@ptrCast(*const IXATransLookup2, self), pXID, ppTransaction);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IResourceManagerSink_Value = @import("../zig.zig").Guid.initString("0d563181-defb-11ce-aed1-00aa0051e2c4");
pub const IID_IResourceManagerSink = &IID_IResourceManagerSink_Value;
pub const IResourceManagerSink = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
TMDown: fn(
self: *const IResourceManagerSink,
) 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 IResourceManagerSink_TMDown(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IResourceManagerSink.VTable, self.vtable).TMDown(@ptrCast(*const IResourceManagerSink, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.0'
const IID_IResourceManager_Value = @import("../zig.zig").Guid.initString("13741d21-87eb-11ce-8081-0080c758527e");
pub const IID_IResourceManager = &IID_IResourceManager_Value;
pub const IResourceManager = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Enlist: fn(
self: *const IResourceManager,
pTransaction: ?*ITransaction,
pRes: ?*ITransactionResourceAsync,
pUOW: ?*BOID,
pisoLevel: ?*i32,
ppEnlist: ?*?*ITransactionEnlistmentAsync,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Reenlist: fn(
self: *const IResourceManager,
pPrepInfo: [*:0]u8,
cbPrepInfo: u32,
lTimeout: u32,
pXactStat: ?*XACTSTAT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ReenlistmentComplete: fn(
self: *const IResourceManager,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDistributedTransactionManager: fn(
self: *const IResourceManager,
iid: ?*const Guid,
ppvObject: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IResourceManager_Enlist(self: *const T, pTransaction: ?*ITransaction, pRes: ?*ITransactionResourceAsync, pUOW: ?*BOID, pisoLevel: ?*i32, ppEnlist: ?*?*ITransactionEnlistmentAsync) callconv(.Inline) HRESULT {
return @ptrCast(*const IResourceManager.VTable, self.vtable).Enlist(@ptrCast(*const IResourceManager, self), pTransaction, pRes, pUOW, pisoLevel, ppEnlist);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IResourceManager_Reenlist(self: *const T, pPrepInfo: [*:0]u8, cbPrepInfo: u32, lTimeout: u32, pXactStat: ?*XACTSTAT) callconv(.Inline) HRESULT {
return @ptrCast(*const IResourceManager.VTable, self.vtable).Reenlist(@ptrCast(*const IResourceManager, self), pPrepInfo, cbPrepInfo, lTimeout, pXactStat);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IResourceManager_ReenlistmentComplete(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IResourceManager.VTable, self.vtable).ReenlistmentComplete(@ptrCast(*const IResourceManager, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IResourceManager_GetDistributedTransactionManager(self: *const T, iid: ?*const Guid, ppvObject: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IResourceManager.VTable, self.vtable).GetDistributedTransactionManager(@ptrCast(*const IResourceManager, self), iid, ppvObject);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ILastResourceManager_Value = @import("../zig.zig").Guid.initString("4d964ad4-5b33-11d3-8a91-00c04f79eb6d");
pub const IID_ILastResourceManager = &IID_ILastResourceManager_Value;
pub const ILastResourceManager = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
TransactionCommitted: fn(
self: *const ILastResourceManager,
pPrepInfo: [*:0]u8,
cbPrepInfo: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RecoveryDone: fn(
self: *const ILastResourceManager,
) 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 ILastResourceManager_TransactionCommitted(self: *const T, pPrepInfo: [*:0]u8, cbPrepInfo: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ILastResourceManager.VTable, self.vtable).TransactionCommitted(@ptrCast(*const ILastResourceManager, self), pPrepInfo, cbPrepInfo);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ILastResourceManager_RecoveryDone(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ILastResourceManager.VTable, self.vtable).RecoveryDone(@ptrCast(*const ILastResourceManager, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IResourceManager2_Value = @import("../zig.zig").Guid.initString("d136c69a-f749-11d1-8f47-00c04f8ee57d");
pub const IID_IResourceManager2 = &IID_IResourceManager2_Value;
pub const IResourceManager2 = extern struct {
pub const VTable = extern struct {
base: IResourceManager.VTable,
Enlist2: fn(
self: *const IResourceManager2,
pTransaction: ?*ITransaction,
pResAsync: ?*ITransactionResourceAsync,
pUOW: ?*BOID,
pisoLevel: ?*i32,
pXid: ?*xid_t,
ppEnlist: ?*?*ITransactionEnlistmentAsync,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Reenlist2: fn(
self: *const IResourceManager2,
pXid: ?*xid_t,
dwTimeout: u32,
pXactStat: ?*XACTSTAT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IResourceManager.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IResourceManager2_Enlist2(self: *const T, pTransaction: ?*ITransaction, pResAsync: ?*ITransactionResourceAsync, pUOW: ?*BOID, pisoLevel: ?*i32, pXid: ?*xid_t, ppEnlist: ?*?*ITransactionEnlistmentAsync) callconv(.Inline) HRESULT {
return @ptrCast(*const IResourceManager2.VTable, self.vtable).Enlist2(@ptrCast(*const IResourceManager2, self), pTransaction, pResAsync, pUOW, pisoLevel, pXid, ppEnlist);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IResourceManager2_Reenlist2(self: *const T, pXid: ?*xid_t, dwTimeout: u32, pXactStat: ?*XACTSTAT) callconv(.Inline) HRESULT {
return @ptrCast(*const IResourceManager2.VTable, self.vtable).Reenlist2(@ptrCast(*const IResourceManager2, self), pXid, dwTimeout, pXactStat);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IResourceManagerRejoinable_Value = @import("../zig.zig").Guid.initString("6f6de620-b5df-4f3e-9cfa-c8aebd05172b");
pub const IID_IResourceManagerRejoinable = &IID_IResourceManagerRejoinable_Value;
pub const IResourceManagerRejoinable = extern struct {
pub const VTable = extern struct {
base: IResourceManager2.VTable,
Rejoin: fn(
self: *const IResourceManagerRejoinable,
pPrepInfo: [*:0]u8,
cbPrepInfo: u32,
lTimeout: u32,
pXactStat: ?*XACTSTAT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IResourceManager2.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IResourceManagerRejoinable_Rejoin(self: *const T, pPrepInfo: [*:0]u8, cbPrepInfo: u32, lTimeout: u32, pXactStat: ?*XACTSTAT) callconv(.Inline) HRESULT {
return @ptrCast(*const IResourceManagerRejoinable.VTable, self.vtable).Rejoin(@ptrCast(*const IResourceManagerRejoinable, self), pPrepInfo, cbPrepInfo, lTimeout, pXactStat);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXAConfig_Value = @import("../zig.zig").Guid.initString("c8a6e3a1-9a8c-11cf-a308-00a0c905416e");
pub const IID_IXAConfig = &IID_IXAConfig_Value;
pub const IXAConfig = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Initialize: fn(
self: *const IXAConfig,
clsidHelperDll: Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Terminate: fn(
self: *const IXAConfig,
) 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 IXAConfig_Initialize(self: *const T, clsidHelperDll: Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAConfig.VTable, self.vtable).Initialize(@ptrCast(*const IXAConfig, self), clsidHelperDll);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXAConfig_Terminate(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAConfig.VTable, self.vtable).Terminate(@ptrCast(*const IXAConfig, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IRMHelper_Value = @import("../zig.zig").Guid.initString("e793f6d1-f53d-11cf-a60d-00a0c905416e");
pub const IID_IRMHelper = &IID_IRMHelper_Value;
pub const IRMHelper = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
RMCount: fn(
self: *const IRMHelper,
dwcTotalNumberOfRMs: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RMInfo: fn(
self: *const IRMHelper,
pXa_Switch: ?*xa_switch_t,
fCDeclCallingConv: BOOL,
pszOpenString: ?PSTR,
pszCloseString: ?PSTR,
guidRMRecovery: Guid,
) 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 IRMHelper_RMCount(self: *const T, dwcTotalNumberOfRMs: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRMHelper.VTable, self.vtable).RMCount(@ptrCast(*const IRMHelper, self), dwcTotalNumberOfRMs);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRMHelper_RMInfo(self: *const T, pXa_Switch: ?*xa_switch_t, fCDeclCallingConv: BOOL, pszOpenString: ?PSTR, pszCloseString: ?PSTR, guidRMRecovery: Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const IRMHelper.VTable, self.vtable).RMInfo(@ptrCast(*const IRMHelper, self), pXa_Switch, fCDeclCallingConv, pszOpenString, pszCloseString, guidRMRecovery);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXAObtainRMInfo_Value = @import("../zig.zig").Guid.initString("e793f6d2-f53d-11cf-a60d-00a0c905416e");
pub const IID_IXAObtainRMInfo = &IID_IXAObtainRMInfo_Value;
pub const IXAObtainRMInfo = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
ObtainRMInfo: fn(
self: *const IXAObtainRMInfo,
pIRMHelper: ?*IRMHelper,
) 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 IXAObtainRMInfo_ObtainRMInfo(self: *const T, pIRMHelper: ?*IRMHelper) callconv(.Inline) HRESULT {
return @ptrCast(*const IXAObtainRMInfo.VTable, self.vtable).ObtainRMInfo(@ptrCast(*const IXAObtainRMInfo, self), pIRMHelper);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IResourceManagerFactory_Value = @import("../zig.zig").Guid.initString("13741d20-87eb-11ce-8081-0080c758527e");
pub const IID_IResourceManagerFactory = &IID_IResourceManagerFactory_Value;
pub const IResourceManagerFactory = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Create: fn(
self: *const IResourceManagerFactory,
pguidRM: ?*Guid,
pszRMName: ?PSTR,
pIResMgrSink: ?*IResourceManagerSink,
ppResMgr: ?*?*IResourceManager,
) 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 IResourceManagerFactory_Create(self: *const T, pguidRM: ?*Guid, pszRMName: ?PSTR, pIResMgrSink: ?*IResourceManagerSink, ppResMgr: ?*?*IResourceManager) callconv(.Inline) HRESULT {
return @ptrCast(*const IResourceManagerFactory.VTable, self.vtable).Create(@ptrCast(*const IResourceManagerFactory, self), pguidRM, pszRMName, pIResMgrSink, ppResMgr);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IResourceManagerFactory2_Value = @import("../zig.zig").Guid.initString("6b369c21-fbd2-11d1-8f47-00c04f8ee57d");
pub const IID_IResourceManagerFactory2 = &IID_IResourceManagerFactory2_Value;
pub const IResourceManagerFactory2 = extern struct {
pub const VTable = extern struct {
base: IResourceManagerFactory.VTable,
CreateEx: fn(
self: *const IResourceManagerFactory2,
pguidRM: ?*Guid,
pszRMName: ?PSTR,
pIResMgrSink: ?*IResourceManagerSink,
riidRequested: ?*const Guid,
ppvResMgr: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IResourceManagerFactory.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IResourceManagerFactory2_CreateEx(self: *const T, pguidRM: ?*Guid, pszRMName: ?PSTR, pIResMgrSink: ?*IResourceManagerSink, riidRequested: ?*const Guid, ppvResMgr: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IResourceManagerFactory2.VTable, self.vtable).CreateEx(@ptrCast(*const IResourceManagerFactory2, self), pguidRM, pszRMName, pIResMgrSink, riidRequested, ppvResMgr);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IPrepareInfo_Value = @import("../zig.zig").Guid.initString("80c7bfd0-87ee-11ce-8081-0080c758527e");
pub const IID_IPrepareInfo = &IID_IPrepareInfo_Value;
pub const IPrepareInfo = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetPrepareInfoSize: fn(
self: *const IPrepareInfo,
pcbPrepInfo: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPrepareInfo: fn(
self: *const IPrepareInfo,
pPrepInfo: ?*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 IPrepareInfo_GetPrepareInfoSize(self: *const T, pcbPrepInfo: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IPrepareInfo.VTable, self.vtable).GetPrepareInfoSize(@ptrCast(*const IPrepareInfo, self), pcbPrepInfo);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPrepareInfo_GetPrepareInfo(self: *const T, pPrepInfo: ?*u8) callconv(.Inline) HRESULT {
return @ptrCast(*const IPrepareInfo.VTable, self.vtable).GetPrepareInfo(@ptrCast(*const IPrepareInfo, self), pPrepInfo);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IPrepareInfo2_Value = @import("../zig.zig").Guid.initString("5fab2547-9779-11d1-b886-00c04fb9618a");
pub const IID_IPrepareInfo2 = &IID_IPrepareInfo2_Value;
pub const IPrepareInfo2 = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetPrepareInfoSize: fn(
self: *const IPrepareInfo2,
pcbPrepInfo: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPrepareInfo: fn(
self: *const IPrepareInfo2,
cbPrepareInfo: u32,
pPrepInfo: [*:0]u8,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPrepareInfo2_GetPrepareInfoSize(self: *const T, pcbPrepInfo: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IPrepareInfo2.VTable, self.vtable).GetPrepareInfoSize(@ptrCast(*const IPrepareInfo2, self), pcbPrepInfo);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPrepareInfo2_GetPrepareInfo(self: *const T, cbPrepareInfo: u32, pPrepInfo: [*:0]u8) callconv(.Inline) HRESULT {
return @ptrCast(*const IPrepareInfo2.VTable, self.vtable).GetPrepareInfo(@ptrCast(*const IPrepareInfo2, self), cbPrepareInfo, pPrepInfo);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IGetDispenser_Value = @import("../zig.zig").Guid.initString("c23cc370-87ef-11ce-8081-0080c758527e");
pub const IID_IGetDispenser = &IID_IGetDispenser_Value;
pub const IGetDispenser = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetDispenser: fn(
self: *const IGetDispenser,
iid: ?*const Guid,
ppvObject: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IGetDispenser_GetDispenser(self: *const T, iid: ?*const Guid, ppvObject: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IGetDispenser.VTable, self.vtable).GetDispenser(@ptrCast(*const IGetDispenser, self), iid, ppvObject);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ITransactionVoterBallotAsync2_Value = @import("../zig.zig").Guid.initString("5433376c-414d-11d3-b206-00c04fc2f3ef");
pub const IID_ITransactionVoterBallotAsync2 = &IID_ITransactionVoterBallotAsync2_Value;
pub const ITransactionVoterBallotAsync2 = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
VoteRequestDone: fn(
self: *const ITransactionVoterBallotAsync2,
hr: HRESULT,
pboidReason: ?*BOID,
) 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 ITransactionVoterBallotAsync2_VoteRequestDone(self: *const T, hr: HRESULT, pboidReason: ?*BOID) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionVoterBallotAsync2.VTable, self.vtable).VoteRequestDone(@ptrCast(*const ITransactionVoterBallotAsync2, self), hr, pboidReason);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ITransactionVoterNotifyAsync2_Value = @import("../zig.zig").Guid.initString("5433376b-414d-11d3-b206-00c04fc2f3ef");
pub const IID_ITransactionVoterNotifyAsync2 = &IID_ITransactionVoterNotifyAsync2_Value;
pub const ITransactionVoterNotifyAsync2 = extern struct {
pub const VTable = extern struct {
base: ITransactionOutcomeEvents.VTable,
VoteRequest: fn(
self: *const ITransactionVoterNotifyAsync2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace ITransactionOutcomeEvents.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransactionVoterNotifyAsync2_VoteRequest(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionVoterNotifyAsync2.VTable, self.vtable).VoteRequest(@ptrCast(*const ITransactionVoterNotifyAsync2, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ITransactionVoterFactory2_Value = @import("../zig.zig").Guid.initString("5433376a-414d-11d3-b206-00c04fc2f3ef");
pub const IID_ITransactionVoterFactory2 = &IID_ITransactionVoterFactory2_Value;
pub const ITransactionVoterFactory2 = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Create: fn(
self: *const ITransactionVoterFactory2,
pTransaction: ?*ITransaction,
pVoterNotify: ?*ITransactionVoterNotifyAsync2,
ppVoterBallot: ?*?*ITransactionVoterBallotAsync2,
) 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 ITransactionVoterFactory2_Create(self: *const T, pTransaction: ?*ITransaction, pVoterNotify: ?*ITransactionVoterNotifyAsync2, ppVoterBallot: ?*?*ITransactionVoterBallotAsync2) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionVoterFactory2.VTable, self.vtable).Create(@ptrCast(*const ITransactionVoterFactory2, self), pTransaction, pVoterNotify, ppVoterBallot);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ITransactionPhase0EnlistmentAsync_Value = @import("../zig.zig").Guid.initString("82dc88e1-a954-11d1-8f88-00600895e7d5");
pub const IID_ITransactionPhase0EnlistmentAsync = &IID_ITransactionPhase0EnlistmentAsync_Value;
pub const ITransactionPhase0EnlistmentAsync = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Enable: fn(
self: *const ITransactionPhase0EnlistmentAsync,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WaitForEnlistment: fn(
self: *const ITransactionPhase0EnlistmentAsync,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Phase0Done: fn(
self: *const ITransactionPhase0EnlistmentAsync,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Unenlist: fn(
self: *const ITransactionPhase0EnlistmentAsync,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetTransaction: fn(
self: *const ITransactionPhase0EnlistmentAsync,
ppITransaction: ?*?*ITransaction,
) 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 ITransactionPhase0EnlistmentAsync_Enable(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionPhase0EnlistmentAsync.VTable, self.vtable).Enable(@ptrCast(*const ITransactionPhase0EnlistmentAsync, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransactionPhase0EnlistmentAsync_WaitForEnlistment(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionPhase0EnlistmentAsync.VTable, self.vtable).WaitForEnlistment(@ptrCast(*const ITransactionPhase0EnlistmentAsync, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransactionPhase0EnlistmentAsync_Phase0Done(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionPhase0EnlistmentAsync.VTable, self.vtable).Phase0Done(@ptrCast(*const ITransactionPhase0EnlistmentAsync, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransactionPhase0EnlistmentAsync_Unenlist(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionPhase0EnlistmentAsync.VTable, self.vtable).Unenlist(@ptrCast(*const ITransactionPhase0EnlistmentAsync, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransactionPhase0EnlistmentAsync_GetTransaction(self: *const T, ppITransaction: ?*?*ITransaction) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionPhase0EnlistmentAsync.VTable, self.vtable).GetTransaction(@ptrCast(*const ITransactionPhase0EnlistmentAsync, self), ppITransaction);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ITransactionPhase0NotifyAsync_Value = @import("../zig.zig").Guid.initString("ef081809-0c76-11d2-87a6-00c04f990f34");
pub const IID_ITransactionPhase0NotifyAsync = &IID_ITransactionPhase0NotifyAsync_Value;
pub const ITransactionPhase0NotifyAsync = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Phase0Request: fn(
self: *const ITransactionPhase0NotifyAsync,
fAbortingHint: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
EnlistCompleted: fn(
self: *const ITransactionPhase0NotifyAsync,
status: HRESULT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransactionPhase0NotifyAsync_Phase0Request(self: *const T, fAbortingHint: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionPhase0NotifyAsync.VTable, self.vtable).Phase0Request(@ptrCast(*const ITransactionPhase0NotifyAsync, self), fAbortingHint);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransactionPhase0NotifyAsync_EnlistCompleted(self: *const T, status: HRESULT) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionPhase0NotifyAsync.VTable, self.vtable).EnlistCompleted(@ptrCast(*const ITransactionPhase0NotifyAsync, self), status);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ITransactionPhase0Factory_Value = @import("../zig.zig").Guid.initString("82dc88e0-a954-11d1-8f88-00600895e7d5");
pub const IID_ITransactionPhase0Factory = &IID_ITransactionPhase0Factory_Value;
pub const ITransactionPhase0Factory = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Create: fn(
self: *const ITransactionPhase0Factory,
pPhase0Notify: ?*ITransactionPhase0NotifyAsync,
ppPhase0Enlistment: ?*?*ITransactionPhase0EnlistmentAsync,
) 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 ITransactionPhase0Factory_Create(self: *const T, pPhase0Notify: ?*ITransactionPhase0NotifyAsync, ppPhase0Enlistment: ?*?*ITransactionPhase0EnlistmentAsync) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionPhase0Factory.VTable, self.vtable).Create(@ptrCast(*const ITransactionPhase0Factory, self), pPhase0Notify, ppPhase0Enlistment);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ITransactionTransmitter_Value = @import("../zig.zig").Guid.initString("59313e01-b36c-11cf-a539-00aa006887c3");
pub const IID_ITransactionTransmitter = &IID_ITransactionTransmitter_Value;
pub const ITransactionTransmitter = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Set: fn(
self: *const ITransactionTransmitter,
pTransaction: ?*ITransaction,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPropagationTokenSize: fn(
self: *const ITransactionTransmitter,
pcbToken: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
MarshalPropagationToken: fn(
self: *const ITransactionTransmitter,
cbToken: u32,
rgbToken: [*:0]u8,
pcbUsed: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
UnmarshalReturnToken: fn(
self: *const ITransactionTransmitter,
cbReturnToken: u32,
rgbReturnToken: [*:0]u8,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Reset: fn(
self: *const ITransactionTransmitter,
) 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 ITransactionTransmitter_Set(self: *const T, pTransaction: ?*ITransaction) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionTransmitter.VTable, self.vtable).Set(@ptrCast(*const ITransactionTransmitter, self), pTransaction);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransactionTransmitter_GetPropagationTokenSize(self: *const T, pcbToken: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionTransmitter.VTable, self.vtable).GetPropagationTokenSize(@ptrCast(*const ITransactionTransmitter, self), pcbToken);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransactionTransmitter_MarshalPropagationToken(self: *const T, cbToken: u32, rgbToken: [*:0]u8, pcbUsed: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionTransmitter.VTable, self.vtable).MarshalPropagationToken(@ptrCast(*const ITransactionTransmitter, self), cbToken, rgbToken, pcbUsed);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransactionTransmitter_UnmarshalReturnToken(self: *const T, cbReturnToken: u32, rgbReturnToken: [*:0]u8) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionTransmitter.VTable, self.vtable).UnmarshalReturnToken(@ptrCast(*const ITransactionTransmitter, self), cbReturnToken, rgbReturnToken);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransactionTransmitter_Reset(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionTransmitter.VTable, self.vtable).Reset(@ptrCast(*const ITransactionTransmitter, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ITransactionTransmitterFactory_Value = @import("../zig.zig").Guid.initString("59313e00-b36c-11cf-a539-00aa006887c3");
pub const IID_ITransactionTransmitterFactory = &IID_ITransactionTransmitterFactory_Value;
pub const ITransactionTransmitterFactory = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Create: fn(
self: *const ITransactionTransmitterFactory,
ppTransmitter: ?*?*ITransactionTransmitter,
) 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 ITransactionTransmitterFactory_Create(self: *const T, ppTransmitter: ?*?*ITransactionTransmitter) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionTransmitterFactory.VTable, self.vtable).Create(@ptrCast(*const ITransactionTransmitterFactory, self), ppTransmitter);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ITransactionReceiver_Value = @import("../zig.zig").Guid.initString("59313e03-b36c-11cf-a539-00aa006887c3");
pub const IID_ITransactionReceiver = &IID_ITransactionReceiver_Value;
pub const ITransactionReceiver = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
UnmarshalPropagationToken: fn(
self: *const ITransactionReceiver,
cbToken: u32,
rgbToken: [*:0]u8,
ppTransaction: ?*?*ITransaction,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetReturnTokenSize: fn(
self: *const ITransactionReceiver,
pcbReturnToken: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
MarshalReturnToken: fn(
self: *const ITransactionReceiver,
cbReturnToken: u32,
rgbReturnToken: [*:0]u8,
pcbUsed: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Reset: fn(
self: *const ITransactionReceiver,
) 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 ITransactionReceiver_UnmarshalPropagationToken(self: *const T, cbToken: u32, rgbToken: [*:0]u8, ppTransaction: ?*?*ITransaction) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionReceiver.VTable, self.vtable).UnmarshalPropagationToken(@ptrCast(*const ITransactionReceiver, self), cbToken, rgbToken, ppTransaction);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransactionReceiver_GetReturnTokenSize(self: *const T, pcbReturnToken: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionReceiver.VTable, self.vtable).GetReturnTokenSize(@ptrCast(*const ITransactionReceiver, self), pcbReturnToken);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransactionReceiver_MarshalReturnToken(self: *const T, cbReturnToken: u32, rgbReturnToken: [*:0]u8, pcbUsed: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionReceiver.VTable, self.vtable).MarshalReturnToken(@ptrCast(*const ITransactionReceiver, self), cbReturnToken, rgbReturnToken, pcbUsed);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITransactionReceiver_Reset(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionReceiver.VTable, self.vtable).Reset(@ptrCast(*const ITransactionReceiver, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ITransactionReceiverFactory_Value = @import("../zig.zig").Guid.initString("59313e02-b36c-11cf-a539-00aa006887c3");
pub const IID_ITransactionReceiverFactory = &IID_ITransactionReceiverFactory_Value;
pub const ITransactionReceiverFactory = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Create: fn(
self: *const ITransactionReceiverFactory,
ppReceiver: ?*?*ITransactionReceiver,
) 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 ITransactionReceiverFactory_Create(self: *const T, ppReceiver: ?*?*ITransactionReceiver) callconv(.Inline) HRESULT {
return @ptrCast(*const ITransactionReceiverFactory.VTable, self.vtable).Create(@ptrCast(*const ITransactionReceiverFactory, self), ppReceiver);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const _ProxyConfigParams = extern struct {
wcThreadsMax: u16,
};
const IID_IDtcLuConfigure_Value = @import("../zig.zig").Guid.initString("4131e760-1aea-11d0-944b-00a0c905416e");
pub const IID_IDtcLuConfigure = &IID_IDtcLuConfigure_Value;
pub const IDtcLuConfigure = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Add: fn(
self: *const IDtcLuConfigure,
pucLuPair: [*:0]u8,
cbLuPair: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Delete: fn(
self: *const IDtcLuConfigure,
pucLuPair: [*:0]u8,
cbLuPair: 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 IDtcLuConfigure_Add(self: *const T, pucLuPair: [*:0]u8, cbLuPair: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuConfigure.VTable, self.vtable).Add(@ptrCast(*const IDtcLuConfigure, self), pucLuPair, cbLuPair);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuConfigure_Delete(self: *const T, pucLuPair: [*:0]u8, cbLuPair: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuConfigure.VTable, self.vtable).Delete(@ptrCast(*const IDtcLuConfigure, self), pucLuPair, cbLuPair);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDtcLuRecovery_Value = @import("../zig.zig").Guid.initString("ac2b8ad2-d6f0-11d0-b386-00a0c9083365");
pub const IID_IDtcLuRecovery = &IID_IDtcLuRecovery_Value;
pub const IDtcLuRecovery = 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());
};
const IID_IDtcLuRecoveryFactory_Value = @import("../zig.zig").Guid.initString("4131e762-1aea-11d0-944b-00a0c905416e");
pub const IID_IDtcLuRecoveryFactory = &IID_IDtcLuRecoveryFactory_Value;
pub const IDtcLuRecoveryFactory = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Create: fn(
self: *const IDtcLuRecoveryFactory,
pucLuPair: [*:0]u8,
cbLuPair: u32,
ppRecovery: ?*?*IDtcLuRecovery,
) 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 IDtcLuRecoveryFactory_Create(self: *const T, pucLuPair: [*:0]u8, cbLuPair: u32, ppRecovery: ?*?*IDtcLuRecovery) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRecoveryFactory.VTable, self.vtable).Create(@ptrCast(*const IDtcLuRecoveryFactory, self), pucLuPair, cbLuPair, ppRecovery);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const _DtcLu_LocalRecovery_Work = enum(i32) {
CHECKLUSTATUS = 1,
TRANS = 2,
TMDOWN = 3,
};
pub const DTCINITIATEDRECOVERYWORK_CHECKLUSTATUS = _DtcLu_LocalRecovery_Work.CHECKLUSTATUS;
pub const DTCINITIATEDRECOVERYWORK_TRANS = _DtcLu_LocalRecovery_Work.TRANS;
pub const DTCINITIATEDRECOVERYWORK_TMDOWN = _DtcLu_LocalRecovery_Work.TMDOWN;
pub const _DtcLu_Xln = enum(i32) {
COLD = 1,
WARM = 2,
};
pub const DTCLUXLN_COLD = _DtcLu_Xln.COLD;
pub const DTCLUXLN_WARM = _DtcLu_Xln.WARM;
pub const _DtcLu_Xln_Confirmation = enum(i32) {
CONFIRM = 1,
LOGNAMEMISMATCH = 2,
COLDWARMMISMATCH = 3,
OBSOLETE = 4,
};
pub const DTCLUXLNCONFIRMATION_CONFIRM = _DtcLu_Xln_Confirmation.CONFIRM;
pub const DTCLUXLNCONFIRMATION_LOGNAMEMISMATCH = _DtcLu_Xln_Confirmation.LOGNAMEMISMATCH;
pub const DTCLUXLNCONFIRMATION_COLDWARMMISMATCH = _DtcLu_Xln_Confirmation.COLDWARMMISMATCH;
pub const DTCLUXLNCONFIRMATION_OBSOLETE = _DtcLu_Xln_Confirmation.OBSOLETE;
pub const _DtcLu_Xln_Response = enum(i32) {
OK_SENDOURXLNBACK = 1,
OK_SENDCONFIRMATION = 2,
LOGNAMEMISMATCH = 3,
COLDWARMMISMATCH = 4,
};
pub const DTCLUXLNRESPONSE_OK_SENDOURXLNBACK = _DtcLu_Xln_Response.OK_SENDOURXLNBACK;
pub const DTCLUXLNRESPONSE_OK_SENDCONFIRMATION = _DtcLu_Xln_Response.OK_SENDCONFIRMATION;
pub const DTCLUXLNRESPONSE_LOGNAMEMISMATCH = _DtcLu_Xln_Response.LOGNAMEMISMATCH;
pub const DTCLUXLNRESPONSE_COLDWARMMISMATCH = _DtcLu_Xln_Response.COLDWARMMISMATCH;
pub const _DtcLu_Xln_Error = enum(i32) {
PROTOCOL = 1,
LOGNAMEMISMATCH = 2,
COLDWARMMISMATCH = 3,
};
pub const DTCLUXLNERROR_PROTOCOL = _DtcLu_Xln_Error.PROTOCOL;
pub const DTCLUXLNERROR_LOGNAMEMISMATCH = _DtcLu_Xln_Error.LOGNAMEMISMATCH;
pub const DTCLUXLNERROR_COLDWARMMISMATCH = _DtcLu_Xln_Error.COLDWARMMISMATCH;
pub const _DtcLu_CompareState = enum(i32) {
COMMITTED = 1,
HEURISTICCOMMITTED = 2,
HEURISTICMIXED = 3,
HEURISTICRESET = 4,
INDOUBT = 5,
RESET = 6,
};
pub const DTCLUCOMPARESTATE_COMMITTED = _DtcLu_CompareState.COMMITTED;
pub const DTCLUCOMPARESTATE_HEURISTICCOMMITTED = _DtcLu_CompareState.HEURISTICCOMMITTED;
pub const DTCLUCOMPARESTATE_HEURISTICMIXED = _DtcLu_CompareState.HEURISTICMIXED;
pub const DTCLUCOMPARESTATE_HEURISTICRESET = _DtcLu_CompareState.HEURISTICRESET;
pub const DTCLUCOMPARESTATE_INDOUBT = _DtcLu_CompareState.INDOUBT;
pub const DTCLUCOMPARESTATE_RESET = _DtcLu_CompareState.RESET;
pub const _DtcLu_CompareStates_Confirmation = enum(i32) {
CONFIRM = 1,
PROTOCOL = 2,
};
pub const DTCLUCOMPARESTATESCONFIRMATION_CONFIRM = _DtcLu_CompareStates_Confirmation.CONFIRM;
pub const DTCLUCOMPARESTATESCONFIRMATION_PROTOCOL = _DtcLu_CompareStates_Confirmation.PROTOCOL;
pub const _DtcLu_CompareStates_Error = enum(i32) {
L = 1,
};
pub const DTCLUCOMPARESTATESERROR_PROTOCOL = _DtcLu_CompareStates_Error.L;
pub const _DtcLu_CompareStates_Response = enum(i32) {
OK = 1,
PROTOCOL = 2,
};
pub const DTCLUCOMPARESTATESRESPONSE_OK = _DtcLu_CompareStates_Response.OK;
pub const DTCLUCOMPARESTATESRESPONSE_PROTOCOL = _DtcLu_CompareStates_Response.PROTOCOL;
const IID_IDtcLuRecoveryInitiatedByDtcTransWork_Value = @import("../zig.zig").Guid.initString("4131e765-1aea-11d0-944b-00a0c905416e");
pub const IID_IDtcLuRecoveryInitiatedByDtcTransWork = &IID_IDtcLuRecoveryInitiatedByDtcTransWork_Value;
pub const IDtcLuRecoveryInitiatedByDtcTransWork = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetLogNameSizes: fn(
self: *const IDtcLuRecoveryInitiatedByDtcTransWork,
pcbOurLogName: ?*u32,
pcbRemoteLogName: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetOurXln: fn(
self: *const IDtcLuRecoveryInitiatedByDtcTransWork,
pXln: ?*_DtcLu_Xln,
pOurLogName: ?*u8,
pRemoteLogName: ?*u8,
pdwProtocol: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
HandleConfirmationFromOurXln: fn(
self: *const IDtcLuRecoveryInitiatedByDtcTransWork,
Confirmation: _DtcLu_Xln_Confirmation,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
HandleTheirXlnResponse: fn(
self: *const IDtcLuRecoveryInitiatedByDtcTransWork,
Xln: _DtcLu_Xln,
pRemoteLogName: ?*u8,
cbRemoteLogName: u32,
dwProtocol: u32,
pConfirmation: ?*_DtcLu_Xln_Confirmation,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
HandleErrorFromOurXln: fn(
self: *const IDtcLuRecoveryInitiatedByDtcTransWork,
Error: _DtcLu_Xln_Error,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CheckForCompareStates: fn(
self: *const IDtcLuRecoveryInitiatedByDtcTransWork,
fCompareStates: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetOurTransIdSize: fn(
self: *const IDtcLuRecoveryInitiatedByDtcTransWork,
pcbOurTransId: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetOurCompareStates: fn(
self: *const IDtcLuRecoveryInitiatedByDtcTransWork,
pOurTransId: ?*u8,
pCompareState: ?*_DtcLu_CompareState,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
HandleTheirCompareStatesResponse: fn(
self: *const IDtcLuRecoveryInitiatedByDtcTransWork,
CompareState: _DtcLu_CompareState,
pConfirmation: ?*_DtcLu_CompareStates_Confirmation,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
HandleErrorFromOurCompareStates: fn(
self: *const IDtcLuRecoveryInitiatedByDtcTransWork,
Error: _DtcLu_CompareStates_Error,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ConversationLost: fn(
self: *const IDtcLuRecoveryInitiatedByDtcTransWork,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetRecoverySeqNum: fn(
self: *const IDtcLuRecoveryInitiatedByDtcTransWork,
plRecoverySeqNum: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ObsoleteRecoverySeqNum: fn(
self: *const IDtcLuRecoveryInitiatedByDtcTransWork,
lNewRecoverySeqNum: i32,
) 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 IDtcLuRecoveryInitiatedByDtcTransWork_GetLogNameSizes(self: *const T, pcbOurLogName: ?*u32, pcbRemoteLogName: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRecoveryInitiatedByDtcTransWork.VTable, self.vtable).GetLogNameSizes(@ptrCast(*const IDtcLuRecoveryInitiatedByDtcTransWork, self), pcbOurLogName, pcbRemoteLogName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuRecoveryInitiatedByDtcTransWork_GetOurXln(self: *const T, pXln: ?*_DtcLu_Xln, pOurLogName: ?*u8, pRemoteLogName: ?*u8, pdwProtocol: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRecoveryInitiatedByDtcTransWork.VTable, self.vtable).GetOurXln(@ptrCast(*const IDtcLuRecoveryInitiatedByDtcTransWork, self), pXln, pOurLogName, pRemoteLogName, pdwProtocol);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuRecoveryInitiatedByDtcTransWork_HandleConfirmationFromOurXln(self: *const T, Confirmation: _DtcLu_Xln_Confirmation) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRecoveryInitiatedByDtcTransWork.VTable, self.vtable).HandleConfirmationFromOurXln(@ptrCast(*const IDtcLuRecoveryInitiatedByDtcTransWork, self), Confirmation);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuRecoveryInitiatedByDtcTransWork_HandleTheirXlnResponse(self: *const T, Xln: _DtcLu_Xln, pRemoteLogName: ?*u8, cbRemoteLogName: u32, dwProtocol: u32, pConfirmation: ?*_DtcLu_Xln_Confirmation) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRecoveryInitiatedByDtcTransWork.VTable, self.vtable).HandleTheirXlnResponse(@ptrCast(*const IDtcLuRecoveryInitiatedByDtcTransWork, self), Xln, pRemoteLogName, cbRemoteLogName, dwProtocol, pConfirmation);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuRecoveryInitiatedByDtcTransWork_HandleErrorFromOurXln(self: *const T, Error: _DtcLu_Xln_Error) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRecoveryInitiatedByDtcTransWork.VTable, self.vtable).HandleErrorFromOurXln(@ptrCast(*const IDtcLuRecoveryInitiatedByDtcTransWork, self), Error);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuRecoveryInitiatedByDtcTransWork_CheckForCompareStates(self: *const T, fCompareStates: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRecoveryInitiatedByDtcTransWork.VTable, self.vtable).CheckForCompareStates(@ptrCast(*const IDtcLuRecoveryInitiatedByDtcTransWork, self), fCompareStates);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuRecoveryInitiatedByDtcTransWork_GetOurTransIdSize(self: *const T, pcbOurTransId: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRecoveryInitiatedByDtcTransWork.VTable, self.vtable).GetOurTransIdSize(@ptrCast(*const IDtcLuRecoveryInitiatedByDtcTransWork, self), pcbOurTransId);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuRecoveryInitiatedByDtcTransWork_GetOurCompareStates(self: *const T, pOurTransId: ?*u8, pCompareState: ?*_DtcLu_CompareState) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRecoveryInitiatedByDtcTransWork.VTable, self.vtable).GetOurCompareStates(@ptrCast(*const IDtcLuRecoveryInitiatedByDtcTransWork, self), pOurTransId, pCompareState);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuRecoveryInitiatedByDtcTransWork_HandleTheirCompareStatesResponse(self: *const T, CompareState: _DtcLu_CompareState, pConfirmation: ?*_DtcLu_CompareStates_Confirmation) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRecoveryInitiatedByDtcTransWork.VTable, self.vtable).HandleTheirCompareStatesResponse(@ptrCast(*const IDtcLuRecoveryInitiatedByDtcTransWork, self), CompareState, pConfirmation);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuRecoveryInitiatedByDtcTransWork_HandleErrorFromOurCompareStates(self: *const T, Error: _DtcLu_CompareStates_Error) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRecoveryInitiatedByDtcTransWork.VTable, self.vtable).HandleErrorFromOurCompareStates(@ptrCast(*const IDtcLuRecoveryInitiatedByDtcTransWork, self), Error);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuRecoveryInitiatedByDtcTransWork_ConversationLost(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRecoveryInitiatedByDtcTransWork.VTable, self.vtable).ConversationLost(@ptrCast(*const IDtcLuRecoveryInitiatedByDtcTransWork, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuRecoveryInitiatedByDtcTransWork_GetRecoverySeqNum(self: *const T, plRecoverySeqNum: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRecoveryInitiatedByDtcTransWork.VTable, self.vtable).GetRecoverySeqNum(@ptrCast(*const IDtcLuRecoveryInitiatedByDtcTransWork, self), plRecoverySeqNum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuRecoveryInitiatedByDtcTransWork_ObsoleteRecoverySeqNum(self: *const T, lNewRecoverySeqNum: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRecoveryInitiatedByDtcTransWork.VTable, self.vtable).ObsoleteRecoverySeqNum(@ptrCast(*const IDtcLuRecoveryInitiatedByDtcTransWork, self), lNewRecoverySeqNum);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDtcLuRecoveryInitiatedByDtcStatusWork_Value = @import("../zig.zig").Guid.initString("4131e766-1aea-11d0-944b-00a0c905416e");
pub const IID_IDtcLuRecoveryInitiatedByDtcStatusWork = &IID_IDtcLuRecoveryInitiatedByDtcStatusWork_Value;
pub const IDtcLuRecoveryInitiatedByDtcStatusWork = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
HandleCheckLuStatus: fn(
self: *const IDtcLuRecoveryInitiatedByDtcStatusWork,
lRecoverySeqNum: i32,
) 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 IDtcLuRecoveryInitiatedByDtcStatusWork_HandleCheckLuStatus(self: *const T, lRecoverySeqNum: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRecoveryInitiatedByDtcStatusWork.VTable, self.vtable).HandleCheckLuStatus(@ptrCast(*const IDtcLuRecoveryInitiatedByDtcStatusWork, self), lRecoverySeqNum);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDtcLuRecoveryInitiatedByDtc_Value = @import("../zig.zig").Guid.initString("4131e764-1aea-11d0-944b-00a0c905416e");
pub const IID_IDtcLuRecoveryInitiatedByDtc = &IID_IDtcLuRecoveryInitiatedByDtc_Value;
pub const IDtcLuRecoveryInitiatedByDtc = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetWork: fn(
self: *const IDtcLuRecoveryInitiatedByDtc,
pWork: ?*_DtcLu_LocalRecovery_Work,
ppv: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuRecoveryInitiatedByDtc_GetWork(self: *const T, pWork: ?*_DtcLu_LocalRecovery_Work, ppv: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRecoveryInitiatedByDtc.VTable, self.vtable).GetWork(@ptrCast(*const IDtcLuRecoveryInitiatedByDtc, self), pWork, ppv);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDtcLuRecoveryInitiatedByLuWork_Value = @import("../zig.zig").Guid.initString("ac2b8ad1-d6f0-11d0-b386-00a0c9083365");
pub const IID_IDtcLuRecoveryInitiatedByLuWork = &IID_IDtcLuRecoveryInitiatedByLuWork_Value;
pub const IDtcLuRecoveryInitiatedByLuWork = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
HandleTheirXln: fn(
self: *const IDtcLuRecoveryInitiatedByLuWork,
lRecoverySeqNum: i32,
Xln: _DtcLu_Xln,
pRemoteLogName: ?*u8,
cbRemoteLogName: u32,
pOurLogName: ?*u8,
cbOurLogName: u32,
dwProtocol: u32,
pResponse: ?*_DtcLu_Xln_Response,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetOurLogNameSize: fn(
self: *const IDtcLuRecoveryInitiatedByLuWork,
pcbOurLogName: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetOurXln: fn(
self: *const IDtcLuRecoveryInitiatedByLuWork,
pXln: ?*_DtcLu_Xln,
pOurLogName: ?*u8,
pdwProtocol: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
HandleConfirmationOfOurXln: fn(
self: *const IDtcLuRecoveryInitiatedByLuWork,
Confirmation: _DtcLu_Xln_Confirmation,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
HandleTheirCompareStates: fn(
self: *const IDtcLuRecoveryInitiatedByLuWork,
pRemoteTransId: ?*u8,
cbRemoteTransId: u32,
CompareState: _DtcLu_CompareState,
pResponse: ?*_DtcLu_CompareStates_Response,
pCompareState: ?*_DtcLu_CompareState,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
HandleConfirmationOfOurCompareStates: fn(
self: *const IDtcLuRecoveryInitiatedByLuWork,
Confirmation: _DtcLu_CompareStates_Confirmation,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
HandleErrorFromOurCompareStates: fn(
self: *const IDtcLuRecoveryInitiatedByLuWork,
Error: _DtcLu_CompareStates_Error,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ConversationLost: fn(
self: *const IDtcLuRecoveryInitiatedByLuWork,
) 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 IDtcLuRecoveryInitiatedByLuWork_HandleTheirXln(self: *const T, lRecoverySeqNum: i32, Xln: _DtcLu_Xln, pRemoteLogName: ?*u8, cbRemoteLogName: u32, pOurLogName: ?*u8, cbOurLogName: u32, dwProtocol: u32, pResponse: ?*_DtcLu_Xln_Response) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRecoveryInitiatedByLuWork.VTable, self.vtable).HandleTheirXln(@ptrCast(*const IDtcLuRecoveryInitiatedByLuWork, self), lRecoverySeqNum, Xln, pRemoteLogName, cbRemoteLogName, pOurLogName, cbOurLogName, dwProtocol, pResponse);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuRecoveryInitiatedByLuWork_GetOurLogNameSize(self: *const T, pcbOurLogName: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRecoveryInitiatedByLuWork.VTable, self.vtable).GetOurLogNameSize(@ptrCast(*const IDtcLuRecoveryInitiatedByLuWork, self), pcbOurLogName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuRecoveryInitiatedByLuWork_GetOurXln(self: *const T, pXln: ?*_DtcLu_Xln, pOurLogName: ?*u8, pdwProtocol: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRecoveryInitiatedByLuWork.VTable, self.vtable).GetOurXln(@ptrCast(*const IDtcLuRecoveryInitiatedByLuWork, self), pXln, pOurLogName, pdwProtocol);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuRecoveryInitiatedByLuWork_HandleConfirmationOfOurXln(self: *const T, Confirmation: _DtcLu_Xln_Confirmation) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRecoveryInitiatedByLuWork.VTable, self.vtable).HandleConfirmationOfOurXln(@ptrCast(*const IDtcLuRecoveryInitiatedByLuWork, self), Confirmation);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuRecoveryInitiatedByLuWork_HandleTheirCompareStates(self: *const T, pRemoteTransId: ?*u8, cbRemoteTransId: u32, CompareState: _DtcLu_CompareState, pResponse: ?*_DtcLu_CompareStates_Response, pCompareState: ?*_DtcLu_CompareState) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRecoveryInitiatedByLuWork.VTable, self.vtable).HandleTheirCompareStates(@ptrCast(*const IDtcLuRecoveryInitiatedByLuWork, self), pRemoteTransId, cbRemoteTransId, CompareState, pResponse, pCompareState);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuRecoveryInitiatedByLuWork_HandleConfirmationOfOurCompareStates(self: *const T, Confirmation: _DtcLu_CompareStates_Confirmation) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRecoveryInitiatedByLuWork.VTable, self.vtable).HandleConfirmationOfOurCompareStates(@ptrCast(*const IDtcLuRecoveryInitiatedByLuWork, self), Confirmation);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuRecoveryInitiatedByLuWork_HandleErrorFromOurCompareStates(self: *const T, Error: _DtcLu_CompareStates_Error) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRecoveryInitiatedByLuWork.VTable, self.vtable).HandleErrorFromOurCompareStates(@ptrCast(*const IDtcLuRecoveryInitiatedByLuWork, self), Error);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuRecoveryInitiatedByLuWork_ConversationLost(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRecoveryInitiatedByLuWork.VTable, self.vtable).ConversationLost(@ptrCast(*const IDtcLuRecoveryInitiatedByLuWork, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDtcLuRecoveryInitiatedByLu_Value = @import("../zig.zig").Guid.initString("4131e768-1aea-11d0-944b-00a0c905416e");
pub const IID_IDtcLuRecoveryInitiatedByLu = &IID_IDtcLuRecoveryInitiatedByLu_Value;
pub const IDtcLuRecoveryInitiatedByLu = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetObjectToHandleWorkFromLu: fn(
self: *const IDtcLuRecoveryInitiatedByLu,
ppWork: ?*?*IDtcLuRecoveryInitiatedByLuWork,
) 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 IDtcLuRecoveryInitiatedByLu_GetObjectToHandleWorkFromLu(self: *const T, ppWork: ?*?*IDtcLuRecoveryInitiatedByLuWork) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRecoveryInitiatedByLu.VTable, self.vtable).GetObjectToHandleWorkFromLu(@ptrCast(*const IDtcLuRecoveryInitiatedByLu, self), ppWork);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDtcLuRmEnlistment_Value = @import("../zig.zig").Guid.initString("4131e769-1aea-11d0-944b-00a0c905416e");
pub const IID_IDtcLuRmEnlistment = &IID_IDtcLuRmEnlistment_Value;
pub const IDtcLuRmEnlistment = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Unplug: fn(
self: *const IDtcLuRmEnlistment,
fConversationLost: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
BackedOut: fn(
self: *const IDtcLuRmEnlistment,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
BackOut: fn(
self: *const IDtcLuRmEnlistment,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Committed: fn(
self: *const IDtcLuRmEnlistment,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Forget: fn(
self: *const IDtcLuRmEnlistment,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RequestCommit: fn(
self: *const IDtcLuRmEnlistment,
) 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 IDtcLuRmEnlistment_Unplug(self: *const T, fConversationLost: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRmEnlistment.VTable, self.vtable).Unplug(@ptrCast(*const IDtcLuRmEnlistment, self), fConversationLost);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuRmEnlistment_BackedOut(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRmEnlistment.VTable, self.vtable).BackedOut(@ptrCast(*const IDtcLuRmEnlistment, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuRmEnlistment_BackOut(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRmEnlistment.VTable, self.vtable).BackOut(@ptrCast(*const IDtcLuRmEnlistment, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuRmEnlistment_Committed(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRmEnlistment.VTable, self.vtable).Committed(@ptrCast(*const IDtcLuRmEnlistment, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuRmEnlistment_Forget(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRmEnlistment.VTable, self.vtable).Forget(@ptrCast(*const IDtcLuRmEnlistment, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuRmEnlistment_RequestCommit(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRmEnlistment.VTable, self.vtable).RequestCommit(@ptrCast(*const IDtcLuRmEnlistment, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDtcLuRmEnlistmentSink_Value = @import("../zig.zig").Guid.initString("4131e770-1aea-11d0-944b-00a0c905416e");
pub const IID_IDtcLuRmEnlistmentSink = &IID_IDtcLuRmEnlistmentSink_Value;
pub const IDtcLuRmEnlistmentSink = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
AckUnplug: fn(
self: *const IDtcLuRmEnlistmentSink,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TmDown: fn(
self: *const IDtcLuRmEnlistmentSink,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SessionLost: fn(
self: *const IDtcLuRmEnlistmentSink,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
BackedOut: fn(
self: *const IDtcLuRmEnlistmentSink,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
BackOut: fn(
self: *const IDtcLuRmEnlistmentSink,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Committed: fn(
self: *const IDtcLuRmEnlistmentSink,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Forget: fn(
self: *const IDtcLuRmEnlistmentSink,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Prepare: fn(
self: *const IDtcLuRmEnlistmentSink,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RequestCommit: fn(
self: *const IDtcLuRmEnlistmentSink,
) 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 IDtcLuRmEnlistmentSink_AckUnplug(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRmEnlistmentSink.VTable, self.vtable).AckUnplug(@ptrCast(*const IDtcLuRmEnlistmentSink, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuRmEnlistmentSink_TmDown(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRmEnlistmentSink.VTable, self.vtable).TmDown(@ptrCast(*const IDtcLuRmEnlistmentSink, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuRmEnlistmentSink_SessionLost(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRmEnlistmentSink.VTable, self.vtable).SessionLost(@ptrCast(*const IDtcLuRmEnlistmentSink, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuRmEnlistmentSink_BackedOut(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRmEnlistmentSink.VTable, self.vtable).BackedOut(@ptrCast(*const IDtcLuRmEnlistmentSink, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuRmEnlistmentSink_BackOut(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRmEnlistmentSink.VTable, self.vtable).BackOut(@ptrCast(*const IDtcLuRmEnlistmentSink, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuRmEnlistmentSink_Committed(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRmEnlistmentSink.VTable, self.vtable).Committed(@ptrCast(*const IDtcLuRmEnlistmentSink, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuRmEnlistmentSink_Forget(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRmEnlistmentSink.VTable, self.vtable).Forget(@ptrCast(*const IDtcLuRmEnlistmentSink, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuRmEnlistmentSink_Prepare(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRmEnlistmentSink.VTable, self.vtable).Prepare(@ptrCast(*const IDtcLuRmEnlistmentSink, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuRmEnlistmentSink_RequestCommit(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRmEnlistmentSink.VTable, self.vtable).RequestCommit(@ptrCast(*const IDtcLuRmEnlistmentSink, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDtcLuRmEnlistmentFactory_Value = @import("../zig.zig").Guid.initString("4131e771-1aea-11d0-944b-00a0c905416e");
pub const IID_IDtcLuRmEnlistmentFactory = &IID_IDtcLuRmEnlistmentFactory_Value;
pub const IDtcLuRmEnlistmentFactory = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Create: fn(
self: *const IDtcLuRmEnlistmentFactory,
pucLuPair: ?*u8,
cbLuPair: u32,
pITransaction: ?*ITransaction,
pTransId: ?*u8,
cbTransId: u32,
pRmEnlistmentSink: ?*IDtcLuRmEnlistmentSink,
ppRmEnlistment: ?*?*IDtcLuRmEnlistment,
) 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 IDtcLuRmEnlistmentFactory_Create(self: *const T, pucLuPair: ?*u8, cbLuPair: u32, pITransaction: ?*ITransaction, pTransId: ?*u8, cbTransId: u32, pRmEnlistmentSink: ?*IDtcLuRmEnlistmentSink, ppRmEnlistment: ?*?*IDtcLuRmEnlistment) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuRmEnlistmentFactory.VTable, self.vtable).Create(@ptrCast(*const IDtcLuRmEnlistmentFactory, self), pucLuPair, cbLuPair, pITransaction, pTransId, cbTransId, pRmEnlistmentSink, ppRmEnlistment);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDtcLuSubordinateDtc_Value = @import("../zig.zig").Guid.initString("4131e773-1aea-11d0-944b-00a0c905416e");
pub const IID_IDtcLuSubordinateDtc = &IID_IDtcLuSubordinateDtc_Value;
pub const IDtcLuSubordinateDtc = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Unplug: fn(
self: *const IDtcLuSubordinateDtc,
fConversationLost: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
BackedOut: fn(
self: *const IDtcLuSubordinateDtc,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
BackOut: fn(
self: *const IDtcLuSubordinateDtc,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Committed: fn(
self: *const IDtcLuSubordinateDtc,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Forget: fn(
self: *const IDtcLuSubordinateDtc,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Prepare: fn(
self: *const IDtcLuSubordinateDtc,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RequestCommit: fn(
self: *const IDtcLuSubordinateDtc,
) 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 IDtcLuSubordinateDtc_Unplug(self: *const T, fConversationLost: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuSubordinateDtc.VTable, self.vtable).Unplug(@ptrCast(*const IDtcLuSubordinateDtc, self), fConversationLost);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuSubordinateDtc_BackedOut(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuSubordinateDtc.VTable, self.vtable).BackedOut(@ptrCast(*const IDtcLuSubordinateDtc, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuSubordinateDtc_BackOut(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuSubordinateDtc.VTable, self.vtable).BackOut(@ptrCast(*const IDtcLuSubordinateDtc, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuSubordinateDtc_Committed(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuSubordinateDtc.VTable, self.vtable).Committed(@ptrCast(*const IDtcLuSubordinateDtc, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuSubordinateDtc_Forget(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuSubordinateDtc.VTable, self.vtable).Forget(@ptrCast(*const IDtcLuSubordinateDtc, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuSubordinateDtc_Prepare(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuSubordinateDtc.VTable, self.vtable).Prepare(@ptrCast(*const IDtcLuSubordinateDtc, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuSubordinateDtc_RequestCommit(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuSubordinateDtc.VTable, self.vtable).RequestCommit(@ptrCast(*const IDtcLuSubordinateDtc, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDtcLuSubordinateDtcSink_Value = @import("../zig.zig").Guid.initString("4131e774-1aea-11d0-944b-00a0c905416e");
pub const IID_IDtcLuSubordinateDtcSink = &IID_IDtcLuSubordinateDtcSink_Value;
pub const IDtcLuSubordinateDtcSink = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
AckUnplug: fn(
self: *const IDtcLuSubordinateDtcSink,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TmDown: fn(
self: *const IDtcLuSubordinateDtcSink,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SessionLost: fn(
self: *const IDtcLuSubordinateDtcSink,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
BackedOut: fn(
self: *const IDtcLuSubordinateDtcSink,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
BackOut: fn(
self: *const IDtcLuSubordinateDtcSink,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Committed: fn(
self: *const IDtcLuSubordinateDtcSink,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Forget: fn(
self: *const IDtcLuSubordinateDtcSink,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RequestCommit: fn(
self: *const IDtcLuSubordinateDtcSink,
) 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 IDtcLuSubordinateDtcSink_AckUnplug(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuSubordinateDtcSink.VTable, self.vtable).AckUnplug(@ptrCast(*const IDtcLuSubordinateDtcSink, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuSubordinateDtcSink_TmDown(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuSubordinateDtcSink.VTable, self.vtable).TmDown(@ptrCast(*const IDtcLuSubordinateDtcSink, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuSubordinateDtcSink_SessionLost(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuSubordinateDtcSink.VTable, self.vtable).SessionLost(@ptrCast(*const IDtcLuSubordinateDtcSink, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuSubordinateDtcSink_BackedOut(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuSubordinateDtcSink.VTable, self.vtable).BackedOut(@ptrCast(*const IDtcLuSubordinateDtcSink, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuSubordinateDtcSink_BackOut(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuSubordinateDtcSink.VTable, self.vtable).BackOut(@ptrCast(*const IDtcLuSubordinateDtcSink, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuSubordinateDtcSink_Committed(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuSubordinateDtcSink.VTable, self.vtable).Committed(@ptrCast(*const IDtcLuSubordinateDtcSink, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuSubordinateDtcSink_Forget(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuSubordinateDtcSink.VTable, self.vtable).Forget(@ptrCast(*const IDtcLuSubordinateDtcSink, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDtcLuSubordinateDtcSink_RequestCommit(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuSubordinateDtcSink.VTable, self.vtable).RequestCommit(@ptrCast(*const IDtcLuSubordinateDtcSink, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDtcLuSubordinateDtcFactory_Value = @import("../zig.zig").Guid.initString("4131e775-1aea-11d0-944b-00a0c905416e");
pub const IID_IDtcLuSubordinateDtcFactory = &IID_IDtcLuSubordinateDtcFactory_Value;
pub const IDtcLuSubordinateDtcFactory = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Create: fn(
self: *const IDtcLuSubordinateDtcFactory,
pucLuPair: ?*u8,
cbLuPair: u32,
punkTransactionOuter: ?*IUnknown,
isoLevel: i32,
isoFlags: u32,
pOptions: ?*ITransactionOptions,
ppTransaction: ?*?*ITransaction,
pTransId: ?*u8,
cbTransId: u32,
pSubordinateDtcSink: ?*IDtcLuSubordinateDtcSink,
ppSubordinateDtc: ?*?*IDtcLuSubordinateDtc,
) 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 IDtcLuSubordinateDtcFactory_Create(self: *const T, pucLuPair: ?*u8, cbLuPair: u32, punkTransactionOuter: ?*IUnknown, isoLevel: i32, isoFlags: u32, pOptions: ?*ITransactionOptions, ppTransaction: ?*?*ITransaction, pTransId: ?*u8, cbTransId: u32, pSubordinateDtcSink: ?*IDtcLuSubordinateDtcSink, ppSubordinateDtc: ?*?*IDtcLuSubordinateDtc) callconv(.Inline) HRESULT {
return @ptrCast(*const IDtcLuSubordinateDtcFactory.VTable, self.vtable).Create(@ptrCast(*const IDtcLuSubordinateDtcFactory, self), pucLuPair, cbLuPair, punkTransactionOuter, isoLevel, isoFlags, pOptions, ppTransaction, pTransId, cbTransId, pSubordinateDtcSink, ppSubordinateDtc);
}
};}
pub usingnamespace MethodMixin(@This());
};
//--------------------------------------------------------------------------------
// Section: Functions (4)
//--------------------------------------------------------------------------------
pub extern "XOLEHLP" fn DtcGetTransactionManager(
i_pszHost: ?PSTR,
i_pszTmName: ?PSTR,
i_riid: ?*const Guid,
i_dwReserved1: u32,
i_wcbReserved2: u16,
// TODO: what to do with BytesParamIndex 4?
i_pvReserved2: ?*anyopaque,
o_ppvObject: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "XOLEHLP" fn DtcGetTransactionManagerC(
i_pszHost: ?PSTR,
i_pszTmName: ?PSTR,
i_riid: ?*const Guid,
i_dwReserved1: u32,
i_wcbReserved2: u16,
// TODO: what to do with BytesParamIndex 4?
i_pvReserved2: ?*anyopaque,
o_ppvObject: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "XOLEHLP" fn DtcGetTransactionManagerExA(
i_pszHost: ?PSTR,
i_pszTmName: ?PSTR,
i_riid: ?*const Guid,
i_grfOptions: u32,
i_pvConfigParams: ?*anyopaque,
o_ppvObject: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "XOLEHLP" fn DtcGetTransactionManagerExW(
i_pwszHost: ?PWSTR,
i_pwszTmName: ?PWSTR,
i_riid: ?*const Guid,
i_grfOptions: u32,
i_pvConfigParams: ?*anyopaque,
o_ppvObject: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (2)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../zig.zig").unicode_mode) {
.ansi => struct {
pub const DTC_GET_TRANSACTION_MANAGER_EX_ = thismodule.DTC_GET_TRANSACTION_MANAGER_EX_A;
pub const DtcGetTransactionManagerEx = thismodule.DtcGetTransactionManagerExA;
},
.wide => struct {
pub const DTC_GET_TRANSACTION_MANAGER_EX_ = thismodule.DTC_GET_TRANSACTION_MANAGER_EX_W;
pub const DtcGetTransactionManagerEx = thismodule.DtcGetTransactionManagerExW;
},
.unspecified => if (@import("builtin").is_test) struct {
pub const DTC_GET_TRANSACTION_MANAGER_EX_ = *opaque{};
pub const DtcGetTransactionManagerEx = *opaque{};
} else struct {
pub const DTC_GET_TRANSACTION_MANAGER_EX_ = @compileError("'DTC_GET_TRANSACTION_MANAGER_EX_' requires that UNICODE be set to true or false in the root module");
pub const DtcGetTransactionManagerEx = @compileError("'DtcGetTransactionManagerEx' requires that UNICODE be set to true or false in the root module");
},
};
//--------------------------------------------------------------------------------
// Section: Imports (10)
//--------------------------------------------------------------------------------
const Guid = @import("../zig.zig").Guid;
const BOOL = @import("../foundation.zig").BOOL;
const CHAR = @import("../foundation.zig").CHAR;
const FILETIME = @import("../foundation.zig").FILETIME;
const HANDLE = @import("../foundation.zig").HANDLE;
const HRESULT = @import("../foundation.zig").HRESULT;
const IMoniker = @import("../system/com.zig").IMoniker;
const IUnknown = @import("../system/com.zig").IUnknown;
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(), "DTC_GET_TRANSACTION_MANAGER")) { _ = DTC_GET_TRANSACTION_MANAGER; }
if (@hasDecl(@This(), "DTC_GET_TRANSACTION_MANAGER_EX_A")) { _ = DTC_GET_TRANSACTION_MANAGER_EX_A; }
if (@hasDecl(@This(), "DTC_GET_TRANSACTION_MANAGER_EX_W")) { _ = DTC_GET_TRANSACTION_MANAGER_EX_W; }
if (@hasDecl(@This(), "DTC_INSTALL_CLIENT")) { _ = DTC_INSTALL_CLIENT; }
if (@hasDecl(@This(), "XA_OPEN_EPT")) { _ = XA_OPEN_EPT; }
if (@hasDecl(@This(), "XA_CLOSE_EPT")) { _ = XA_CLOSE_EPT; }
if (@hasDecl(@This(), "XA_START_EPT")) { _ = XA_START_EPT; }
if (@hasDecl(@This(), "XA_END_EPT")) { _ = XA_END_EPT; }
if (@hasDecl(@This(), "XA_ROLLBACK_EPT")) { _ = XA_ROLLBACK_EPT; }
if (@hasDecl(@This(), "XA_PREPARE_EPT")) { _ = XA_PREPARE_EPT; }
if (@hasDecl(@This(), "XA_COMMIT_EPT")) { _ = XA_COMMIT_EPT; }
if (@hasDecl(@This(), "XA_RECOVER_EPT")) { _ = XA_RECOVER_EPT; }
if (@hasDecl(@This(), "XA_FORGET_EPT")) { _ = XA_FORGET_EPT; }
if (@hasDecl(@This(), "XA_COMPLETE_EPT")) { _ = XA_COMPLETE_EPT; }
@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/distributed_transaction_coordinator.zig |
const pokemon = @import("index.zig");
pub const Info = struct {
game_title: [12]u8,
gamecode: [4]u8,
version: pokemon.Version,
hm_tm_prefix: []const u8,
base_stats: []const u8,
level_up_moves: []const u8,
moves: []const u8,
trainers: []const u8,
parties: []const u8,
evolutions: []const u8,
wild_pokemons: []const u8,
};
pub const infos = []Info{
hg_info,
ss_info,
diamond_info,
pearl_info,
platinum_info,
};
const hg_info = Info{
.game_title = "POKEMON HG\x00\x00",
.gamecode = "IPKE",
.version = pokemon.Version.HeartGold,
.hm_tm_prefix = "\x1E\x00\x32\x00",
.base_stats = "/a/0/0/2",
.level_up_moves = "/a/0/3/3",
.moves = "/a/0/1/1",
.trainers = "/a/0/5/5",
.parties = "/a/0/5/6",
.evolutions = "/a/0/3/4",
.wild_pokemons = "a/0/3/7",
};
const ss_info = blk: {
var res = hg_info;
res.game_title = "POKEMON SS\x00\x00";
res.gamecode = "IPGE";
res.version = pokemon.Version.SoulSilver;
res.wild_pokemons = "a/0/3/6";
break :blk res;
};
const diamond_info = Info{
.game_title = "POKEMON D\x00\x00\x00",
.gamecode = "ADAE",
.version = pokemon.Version.Diamond,
.hm_tm_prefix = "\xD1\x00\xD2\x00\xD3\x00\xD4\x00",
.base_stats = "/poketool/personal/personal.narc",
.level_up_moves = "/poketool/personal/wotbl.narc",
.moves = "/poketool/waza/waza_tbl.narc",
.trainers = "/poketool/trainer/trdata.narc",
.parties = "/poketool/trainer/trpoke.narc",
.evolutions = "/poketool/personal/evo.narc",
.wild_pokemons = "fielddata/encountdata/d_enc_data.narc",
};
const pearl_info = blk: {
var res = diamond_info;
res.game_title = "POKEMON P\x00\x00\x00";
res.gamecode = "APAE";
res.version = pokemon.Version.Pearl;
res.base_stats = "/poketool/personal_pearl/personal.narc";
res.wild_pokemons = "fielddata/encountdata/p_enc_data.narc";
break :blk res;
};
const platinum_info = blk: {
var res = diamond_info;
res.game_title = "POKEMON PL\x00\x00";
res.gamecode = "CPUE";
res.version = pokemon.Version.Platinum;
res.base_stats = "/poketool/personal/pl_personal.narc";
res.moves = "/poketool/waza/pl_waza_tbl.narc";
res.wild_pokemons = "fielddata/encountdata/pl_enc_data.narc";
break :blk res;
};
pub const tm_count = 92;
pub const hm_count = 8; | src/pokemon/gen4-constants.zig |
const sf = struct {
usingnamespace @import("sfml");
usingnamespace sf.graphics;
usingnamespace sf.window;
usingnamespace sf.system;
};
pub fn main() !void {
var window = try sf.RenderWindow.createDefault(.{ .x = 600, .y = 600 }, "Heat");
defer window.destroy();
window.setVerticalSyncEnabled(true);
var object_texture = try sf.Texture.createFromFile("cute_image.png");
defer object_texture.destroy();
var object = try sf.Sprite.createFromTexture(object_texture);
defer object.destroy();
//object.setScale(.{ .x = 0.5, .y = 0.5 });
var distortion_map = try sf.Texture.createFromFile("distortion_map.png");
defer distortion_map.destroy();
distortion_map.setRepeated(true);
distortion_map.setSmooth(true);
var render_texture = try sf.RenderTexture.create(.{ .x = 400, .y = 300 });
defer render_texture.destroy();
var sprite = try sf.Sprite.createFromTexture(render_texture.getTexture());
sprite.setPosition(.{ .x = 100, .y = 150 });
//var shader = try sf.Shader.createFromFile(null, null, "heat_shader.fs");
var shader = try sf.Shader.createFromMemory(null, null, @embedFile("../../heat_shader.fs"));
defer shader.destroy();
shader.setUniform("currentTexture", sf.Shader.CurrentTexture);
shader.setUniform("distortionMapTexture", distortion_map);
var distortion_factor: f32 = 0.05;
var rise_factor: f32 = 2;
var clock = try sf.Clock.create();
defer clock.destroy();
while (true) {
while (window.pollEvent()) |event| {
switch (event) {
.closed => return,
.keyPressed => |kp| {
switch (kp.code) {
.Escape => return,
.Up => distortion_factor *= 2,
.Down => distortion_factor /= 2,
.Right => rise_factor *= 2,
.Left => rise_factor /= 2,
else => {}
}
},
else => {}
}
}
shader.setUniform("time", clock.getElapsedTime().asSeconds());
shader.setUniform("distortionFactor", distortion_factor);
shader.setUniform("riseFactor", rise_factor);
render_texture.clear(sf.Color.Black);
render_texture.draw(object, null);
render_texture.display();
window.clear(sf.Color.Black);
window.draw(sprite, sf.RenderStates{ .shader = shader });
window.display();
}
} | src/examples/heat_haze.zig |
const std = @import("std");
const util = @import("util.zig");
const data = @embedFile("../data/day08.txt");
/// Mapping where each index contains a string representing the segments that digit should normally
/// be using.
const digitMap = [_][]const u8{ "abcefg", "cf", "acdeg", "acdfg", "bcdf", "abdfg", "abdefg", "acf", "abcdefg", "abcdfg" };
const NoteEntry = struct {
const Self = @This();
/// Series of 10 unique combination of segments seen on this LCD
inputs: [][]const u8,
/// The 4 output digits seen on this LCD (represented by the segments on in that output)
digits: [][]const u8,
/// A map of the LCD's segment to the actual segment it corresponds to in the actual configuration
segment_map: util.Map(u8, u8),
/// Allocator used for memory allocation.
allocator: *util.Allocator,
pub fn initFromSerializedEntry(allocator: *util.Allocator, serialized_data: []const u8) !Self {
// Create input/output list structures
var inputs = util.List([]const u8).init(allocator);
defer inputs.deinit();
var digits = util.List([]const u8).init(allocator);
defer digits.deinit();
// Parse input and output sections out of text
var in_out_it = util.tokenize(u8, serialized_data, "|");
const input_data = in_out_it.next() orelse return error.InvalidInput;
const digits_data = in_out_it.next() orelse return error.InvalidInput;
// Parse through input and output sections
try appendSlicesFromInputSection(input_data, &inputs);
if (inputs.items.len != 10) return error.InvalidInput;
try appendSlicesFromInputSection(digits_data, &digits);
if (digits.items.len != 4) return error.InvalidInput;
// Create an appropriate structure
var result = Self{
.inputs = inputs.toOwnedSlice(),
.digits = digits.toOwnedSlice(),
.segment_map = util.Map(u8, u8).init(allocator),
.allocator = allocator,
};
errdefer result.deinit();
// Create the segment map for the entry
try result.createSegmentMapping();
// Return created entry
return result;
}
/// Deinitializes the entry and performs necessary deallocation.
pub fn deinit(self: *Self) void {
self.allocator.free(self.inputs);
self.allocator.free(self.digits);
self.segment_map.deinit();
}
// Creates mapping from input to output numbers
fn createSegmentMapping(self: *Self) !void {
// Identify a handful of easy numbers that use unique number of segments.
var one: ?[]const u8 = null;
var four: ?[]const u8 = null;
var seven: ?[]const u8 = null;
var eight: ?[]const u8 = null;
for (self.inputs) |input| {
switch (input.len) {
2 => one = input,
3 => seven = input,
4 => four = input,
7 => eight = input,
else => {},
}
}
if (one == null or four == null or seven == null or eight == null) return error.InvalidInput;
// There is precisely 1 segment active in 7 but not in 1; segment A. Therefore, we can
// identify segment A by comparing.
for (seven.?) |char| {
if (!util.contains(u8, one.?, char)) {
try self.segment_map.put(char, 'a');
break;
}
} else return error.InvalidInput;
// Create a map of the frequency of each character in the input set, since 3 can be identified
// uniquely (and the other 4 broken into groups of 2) exclusively based on this
var frequency = util.Map(u8, u8).init(self.allocator);
defer frequency.deinit();
for (self.inputs) |input| {
for (input) |ch| {
try frequency.put(ch, (frequency.get(ch) orelse 0) + 1);
}
}
// B, E, and F are uniquely identified based on their frequency in the inputs; so add those
// to our map.
var it = frequency.iterator();
while (it.next()) |entry| {
switch (entry.value_ptr.*) {
4 => try self.segment_map.put(entry.key_ptr.*, 'e'),
6 => try self.segment_map.put(entry.key_ptr.*, 'b'),
9 => try self.segment_map.put(entry.key_ptr.*, 'f'),
else => {},
}
}
// 1 contains precisely segments C and F, in some order. We've identified F but not C,
// so whatever is in 1 that doesn't already have a key in our decoded map has to be C.
for (one.?) |char| {
if (!self.segment_map.contains(char)) {
try self.segment_map.put(char, 'c');
break;
}
} else return error.InvalidInput;
// Only segments D and G remain to be identified. 4 contains D but not G; so since we have
// identified everything else, the one thing we find in 4 that we haven't already identified
// has to be D.
for (four.?) |char| {
if (!self.segment_map.contains(char)) {
try self.segment_map.put(char, 'd');
break;
}
} else return error.InvalidInput;
// We now only have D left to ID; so D is whatever identifier between a and g that we haven't
// already used in our map.
for ("abcdefg") |char| {
if (!self.segment_map.contains(char)) {
try self.segment_map.put(char, 'g');
break;
}
} else return error.InvalidInput;
if (self.segment_map.count() != 7) return error.InvalidInput;
}
/// Given the entry and the determined mappings for the LCD, produce an integer representing
/// the number that the submarine is trying to display on the LCD.
pub fn getDisplayedNumber(self: Self) !u32 {
std.debug.assert(self.digits.len == 4);
var number: u32 = 0;
for (self.digits) |digit_segments, idx| {
// Find which digit this is, using the mapping of the standard segments to digits, and
// our segment translation map.
digit_loop: for (digitMap) |actual_digit_segments, actual_digit| {
if (digit_segments.len != actual_digit_segments.len) continue :digit_loop;
for (digit_segments) |ch| {
const digit_from_mapping = self.segment_map.get(ch) orelse return error.InvalidInput;
if (!util.contains(u8, actual_digit_segments, digit_from_mapping)) continue :digit_loop;
}
// Found digit, so move it to its proper place in output.
number += @intCast(u32, actual_digit) * std.math.pow(u32, 10, @intCast(u32, self.digits.len - idx - 1));
break;
} else unreachable;
}
return number;
}
fn appendSlicesFromInputSection(input_section: []const u8, list: *util.List([]const u8)) !void {
var slices_it = util.tokenize(u8, input_section, " ");
while (slices_it.next()) |slice| {
try list.append(slice);
}
}
};
/// Assuming output values as per the problem statement, counts the number of times where
/// unique numbers of segments are used (corresponding to 1, 4, 7, or 8). We could also find this
/// by simply counting the number of times 1, 4, 7, and 8 appear in the output since we can also
/// decode that, but for the sake of doing this as you would in part 1, we'll do it this way.
pub fn countOutputsUsingUniqueNumOfSegments(entries: []const NoteEntry) u32 {
var sum: u32 = 0;
for (entries) |*entry| {
for (entry.digits) |digit| {
if (digit.len == 2 or digit.len == 3 or digit.len == 4 or digit.len == 7) {
sum += 1;
}
}
}
return sum;
}
/// Sums up all of the LCD values being displayed on the LCDs represented by these entries, as per
/// part 2 problem description.
pub fn sumAllLCDValues(entries: []const NoteEntry) !u32 {
var sum: u32 = 0;
for (entries) |*entry| {
sum += try entry.getDisplayedNumber();
}
return sum;
}
pub fn main() !void {
defer {
const leaks = util.gpa_impl.deinit();
std.debug.assert(!leaks);
}
// Store note entries in list
var note_entries = util.List(NoteEntry).init(util.gpa);
defer {
for (note_entries.items) |*entry| {
entry.deinit();
}
note_entries.deinit();
}
// Parse and create note entries
var it = util.tokenize(u8, data, "\n");
while (it.next()) |note_entry_data| {
try note_entries.append(try NoteEntry.initFromSerializedEntry(util.gpa, note_entry_data));
}
const uniqueSegmentInstances = countOutputsUsingUniqueNumOfSegments(note_entries.items);
util.print("Part 1: {} segments.\n", .{uniqueSegmentInstances});
const lcdValueSum = try sumAllLCDValues(note_entries.items);
util.print("Part 2: Sum of entries on LCD Displays: {d}\n", .{lcdValueSum});
} | src/day08.zig |
const std = @import("std");
const ArenaAllocator = std.heap.ArenaAllocator;
const zigly = @import("zigly.zig");
const Dictionary = zigly.Dictionary;
const UserAgent = zigly.UserAgent;
const Request = zigly.Request;
const Logger = zigly.Logger;
fn start() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{ .safety = true }){};
defer _ = gpa.deinit();
var allocator = &gpa.allocator;
try zigly.compatibilityCheck();
var downstream = try zigly.downstream();
var request = downstream.request;
{
var arena = ArenaAllocator.init(allocator);
defer arena.deinit();
const body = try request.body.readAll(&arena.allocator, 0);
std.debug.print("[{s}]\n", .{body});
}
{
var arena = ArenaAllocator.init(allocator);
defer arena.deinit();
const names = try request.headers.names(&arena.allocator);
for (names) |name| {
std.debug.print("[{s}]\n", .{name});
}
}
{
var arena = ArenaAllocator.init(allocator);
defer arena.deinit();
try request.headers.set("x-test", "test");
try request.headers.remove("x-test");
}
{
var arena = ArenaAllocator.init(allocator);
defer arena.deinit();
const ua = try request.headers.get(&arena.allocator, "user-agent");
std.debug.print("UA: [{s}]\n", .{ua});
}
{
var method_buf: [16]u8 = undefined;
const method = try request.getMethod(&method_buf);
std.debug.print("[{s}]\n", .{method});
_ = try request.isPost();
}
{
var arena = ArenaAllocator.init(allocator);
defer arena.deinit();
var query = try Request.new("GET", "https://www.google.com");
try query.setCachingPolicy(.{ .no_cache = true });
var response = try query.send("google");
const body = try response.body.readAll(&arena.allocator, 0);
std.debug.print("{s}\n", .{body});
}
{
var arena = ArenaAllocator.init(allocator);
defer arena.deinit();
var response = downstream.response;
try response.headers.set("X-MyHeader", "XYZ");
try response.setStatus(205);
try response.body.writeAll("OK!\n");
try response.finish();
}
{
var arena = ArenaAllocator.init(allocator);
defer arena.deinit();
var query = try Request.new("GET", "https://www.google.com");
var upstream_response = try query.send("google");
try downstream.response.pipe(&upstream_response, false, false);
}
}
pub export fn _start() callconv(.C) void {
start() catch unreachable;
} | src/tests.zig |
const Wwise = @import("../wwise.zig").Wwise;
const ImGui = @import("../imgui.zig").ImGui;
const DemoInterface = @import("demo_interface.zig").DemoInterface;
const std = @import("std");
const SurfaceInfo = struct {
bank_name: []const u8,
switch_id: u32,
const Self = @This();
pub fn init(bank_name: []const u8) !Self {
const dotPosition = std.mem.lastIndexOfScalar(u8, bank_name, '.');
const bank_name_without_ext = if (dotPosition) |pos| bank_name[0..pos] else bank_name;
return Self{
.bank_name = bank_name,
.switch_id = try Wwise.getIDFromString(bank_name_without_ext),
};
}
};
var Surfaces: [4]SurfaceInfo = undefined;
pub const FootstepsDemo = struct {
allocator: std.mem.Allocator = undefined,
isVisibleState: bool = false,
bankID: u32 = 0,
posX: f32 = 0,
posY: f32 = 0,
lastX: f32 = 0,
lastY: f32 = 0,
weight: f32 = 0,
surface: usize = 0,
current_banks: u32 = 0,
tick_count: isize = 0,
last_tick_count: isize = 0,
const Self = @This();
const DemoGameObjectID = 5;
const CursorSpeed = 5.0;
const BufferZone: f32 = 20.0;
const DistanceToSpeed = 10 / CursorSpeed;
const WalkPeriod = 30;
var SurfaceGroup: u32 = undefined;
pub fn init(self: *Self, allocator: std.mem.Allocator) !void {
self.allocator = allocator;
self.bankID = 0;
self.posX = 300;
self.posY = 240;
self.lastX = 300;
self.lastY = 240;
self.surface = std.math.maxInt(@TypeOf(self.surface));
self.current_banks = 0;
self.weight = 25.0;
self.tick_count = 0;
self.last_tick_count = 0;
try Wwise.registerGameObj(DemoGameObjectID, "Human");
Surfaces = [_]SurfaceInfo{
try SurfaceInfo.init("Dirt.bnk"),
try SurfaceInfo.init("Wood.bnk"),
try SurfaceInfo.init("Metal.bnk"),
try SurfaceInfo.init("Gravel.bnk"),
};
SurfaceGroup = try Wwise.getIDFromString("Surface");
}
pub fn deinit(self: *Self) void {
_ = Wwise.unloadBankByID(self.bankID);
Wwise.unregisterGameObj(DemoGameObjectID);
for (Surfaces) |surface| {
Wwise.unloadBankByString(surface.bank_name) catch {};
}
self.allocator.destroy(self);
}
pub fn onUI(self: *Self) !void {
self.tick_count += 1;
if (ImGui.igBegin("Footsteps Demo", &self.isVisibleState, ImGui.ImGuiWindowFlags_None)) {
var draw_list = ImGui.igGetWindowDrawList();
_ = ImGui.igSliderFloat("Weight", &self.weight, 0.0, 100.0, "%.3f", 1.0);
const whiteColor = ImGui.igGetColorU32Vec4(.{ .x = 1.0, .y = 1.0, .z = 1.0, .w = 1.0 });
const redColor = ImGui.igGetColorU32Vec4(.{ .x = 1.0, .y = 0.0, .z = 0.0, .w = 1.0 });
if (ImGui.igIsKeyDown(ImGui.igGetKeyIndex(ImGui.ImGuiKey_UpArrow))) {
self.posY -= CursorSpeed;
} else if (ImGui.igIsKeyDown(ImGui.igGetKeyIndex(ImGui.ImGuiKey_DownArrow))) {
self.posY += CursorSpeed;
} else if (ImGui.igIsKeyDown(ImGui.igGetKeyIndex(ImGui.ImGuiKey_LeftArrow))) {
self.posX -= CursorSpeed;
} else if (ImGui.igIsKeyDown(ImGui.igGetKeyIndex(ImGui.ImGuiKey_RightArrow))) {
self.posX += CursorSpeed;
}
var window_pos: ImGui.ImVec2 = undefined;
ImGui.igGetCursorScreenPos_nonUDT(&window_pos);
var window_size: ImGui.ImVec2 = undefined;
ImGui.igGetContentRegionAvail_nonUDT(&window_size);
if (self.posX < 7) {
self.posX = 7;
} else if (self.posX >= window_size.x - 7) {
self.posX = window_size.x - 7;
}
if (self.posY < 7) {
self.posY = 7;
} else if (self.posY >= window_size.y - 7) {
self.posY = window_size.y - 7;
}
ImGui.ImDrawList_AddRect(draw_list, window_pos, .{ .x = window_pos.x + window_size.x, .y = window_pos.y + window_size.y }, whiteColor, 0.0, ImGui.ImDrawCornerFlags_All, 1.0);
const half_width: f32 = window_size.x / 2.0;
const half_height: f32 = window_size.y / 2.0;
const text_width: f32 = 40.0;
const text_height: f32 = 36.0;
ImGui.ImDrawList_AddText(draw_list, .{ .x = window_pos.x + (half_width - BufferZone - text_width), .y = window_pos.y + (half_height - BufferZone - text_height) }, whiteColor, "Dirt", null);
ImGui.ImDrawList_AddText(draw_list, .{ .x = window_pos.x + (half_width + BufferZone), .y = window_pos.y + (half_height - BufferZone - text_height) }, whiteColor, "Wood", null);
ImGui.ImDrawList_AddText(draw_list, .{ .x = window_pos.x + (half_width - BufferZone - text_width), .y = window_pos.y + (half_height + BufferZone) }, whiteColor, "Metal", null);
ImGui.ImDrawList_AddText(draw_list, .{ .x = window_pos.x + (half_width + BufferZone), .y = window_pos.y + (half_height + BufferZone) }, whiteColor, "Gravel", null);
ImGui.ImDrawList_AddCircle(draw_list, .{ .x = window_pos.x + self.posX, .y = window_pos.y + self.posY }, 7.0, redColor, 8, 2.0);
ImGui.igEnd();
self.manageSurfaces(window_size);
try self.playFootstep();
}
if (!self.isVisibleState) {
Wwise.stopAllOnGameObject(DemoGameObjectID);
}
}
pub fn isVisible(self: *Self) bool {
return self.isVisibleState;
}
pub fn show(self: *Self) void {
self.isVisibleState = true;
}
pub fn getInterface(self: *Self) DemoInterface {
return DemoInterface{
.instance = @ptrCast(DemoInterface.InstanceType, self),
.initFn = @ptrCast(DemoInterface.InitFn, init),
.deinitFn = @ptrCast(DemoInterface.DeinitFn, deinit),
.onUIFn = @ptrCast(DemoInterface.OnUIFn, onUI),
.isVisibleFn = @ptrCast(DemoInterface.IsVisibleFn, isVisible),
.showFn = @ptrCast(DemoInterface.ShowFn, show),
};
}
fn manageSurfaces(self: *Self, window_size: ImGui.ImVec2) void {
var bankMasks: u32 = self.computeUsedBankMask(window_size);
var i: usize = 0;
while (i < Surfaces.len) : (i += 1) {
const bit = @as(u32, 1) << @intCast(u5, i);
if ((bankMasks & bit) == bit and (self.current_banks & bit) != bit) {
_ = Wwise.loadBankByString(Surfaces[i].bank_name) catch {
bankMasks &= ~bit;
};
}
if ((bankMasks & bit) != bit and ((self.current_banks & bit) == bit)) {
Wwise.unloadBankByString(Surfaces[i].bank_name) catch {
bankMasks |= bit;
};
}
}
self.current_banks = bankMasks;
const half_width = @floatToInt(usize, window_size.x / 2.0);
const half_height = @floatToInt(usize, window_size.y / 2.0);
const index_surface = @boolToInt(@floatToInt(usize, self.posX) > half_width) | (@as(usize, @boolToInt(@floatToInt(usize, self.posY) > half_height)) << @as(u6, 1));
if (self.surface != index_surface) {
Wwise.setSwitchByID(SurfaceGroup, Surfaces[index_surface].switch_id, DemoGameObjectID);
self.surface = index_surface;
}
}
fn computeUsedBankMask(self: Self, window_size: ImGui.ImVec2) u32 {
const half_width = @floatToInt(i32, window_size.x / 2);
const half_height = @floatToInt(i32, window_size.y / 2);
const buffer_zone = @floatToInt(i32, BufferZone * 2);
const left_div = @as(i32, @boolToInt(@floatToInt(i32, self.posX) > (half_width - buffer_zone)));
const right_div = @as(i32, @boolToInt(@floatToInt(i32, self.posX) < (half_width + buffer_zone)));
const top_div = @as(i32, @boolToInt(@floatToInt(i32, self.posY) > (half_height - buffer_zone)));
const bottom_div = @as(i32, @boolToInt(@floatToInt(i32, self.posY) < (half_height + buffer_zone)));
return @bitCast(u32, ((right_div & bottom_div) << 0) | ((left_div & bottom_div) << 1) | ((right_div & top_div) << 2) | ((left_div & top_div) << 3)) & 0x0F;
}
fn playFootstep(self: *Self) !void {
const dx = self.posX - self.lastX;
const dy = self.posY - self.lastY;
const distance = std.math.sqrt(dx * dx + dy * dy);
const speed = distance * DistanceToSpeed;
try Wwise.setRTPCValueByString("Footstep_Speed", speed, DemoGameObjectID);
const period = @floatToInt(isize, WalkPeriod - speed);
if (distance < 0.1 and self.last_tick_count != -1) {
try Wwise.setRTPCValueByString("Footstep_Weight", self.weight / 2.0, DemoGameObjectID);
_ = try Wwise.postEvent("Play_Footsteps", DemoGameObjectID);
self.last_tick_count = -1;
} else if (distance > 0.1 and (self.tick_count - self.last_tick_count) > period) {
try Wwise.setRTPCValueByString("Footstep_Weight", self.weight, DemoGameObjectID);
_ = try Wwise.postEvent("Play_Footsteps", DemoGameObjectID);
self.last_tick_count = self.tick_count;
}
self.lastX = self.posX;
self.lastY = self.posY;
}
}; | src/demos/footsteps_demo.zig |
const std = @import("std");
const Obj = @import("./object.zig").Obj;
const NAN_BOXING = @import("./debug.zig").NAN_BOXING;
pub const Value = if (NAN_BOXING) NanBoxedValue else UnionValue;
pub const NanBoxedValue = packed struct {
data: u64,
const SIGN_BIT: u64 = 0x8000000000000000;
const QNAN: u64 = 0x7ffc000000000000;
const TAG_NIL = 1; // 01.
const TAG_FALSE = 2; // 10.
const TAG_TRUE = 3; // 11.
const NIL_VAL = NanBoxedValue{ .data = QNAN | TAG_NIL };
const TRUE_VAL = NanBoxedValue{ .data = QNAN | TAG_TRUE };
const FALSE_VAL = NanBoxedValue{ .data = QNAN | TAG_FALSE };
pub fn isBool(self: NanBoxedValue) bool {
return (self.data & FALSE_VAL.data) == FALSE_VAL.data;
}
pub fn isNil(self: NanBoxedValue) bool {
return self.data == NIL_VAL.data;
}
pub fn isNumber(self: NanBoxedValue) bool {
return (self.data & QNAN) != QNAN;
}
pub fn isObj(self: NanBoxedValue) bool {
return (self.data & (QNAN | SIGN_BIT)) == (QNAN | SIGN_BIT);
}
pub fn asNumber(self: NanBoxedValue) f64 {
std.debug.assert(self.isNumber());
return @bitCast(f64, self.data);
}
pub fn asBool(self: NanBoxedValue) bool {
std.debug.assert(self.isBool());
return self.data == TRUE_VAL.data;
}
pub fn asObj(self: NanBoxedValue) *Obj {
std.debug.assert(self.isObj());
return @intToPtr(*Obj, @intCast(usize, self.data & ~(SIGN_BIT | QNAN)));
}
pub fn fromNumber(x: f64) NanBoxedValue {
return NanBoxedValue{ .data = @bitCast(u64, x) };
}
pub fn fromBool(x: bool) NanBoxedValue {
return if (x) TRUE_VAL else FALSE_VAL;
}
pub fn fromObj(x: *Obj) NanBoxedValue {
return NanBoxedValue{ .data = SIGN_BIT | QNAN | @ptrToInt(x) };
}
pub fn nil() NanBoxedValue {
return NIL_VAL;
}
pub fn isFalsey(self: NanBoxedValue) bool {
if (self.isBool()) return !self.asBool();
if (self.isNil()) return true;
return false;
}
pub fn equals(self: NanBoxedValue, other: NanBoxedValue) bool {
// Be careful about IEEE NaN equality semantics
if (self.isNumber() and other.isNumber()) return self.asNumber() == other.asNumber();
return self.data == other.data;
}
pub fn format(self: NanBoxedValue, comptime fmt: []const u8, options: std.fmt.FormatOptions, out_stream: anytype) !void {
if (self.isNumber()) {
try out_stream.print("{d}", .{self.asNumber()});
} else if (self.isBool()) {
try out_stream.print("{}", .{self.asBool()});
} else if (self.isNil()) {
try out_stream.print("nil", .{});
} else {
const obj = self.asObj();
try printObject(obj, out_stream);
}
}
};
pub const UnionValue = union(enum) {
Bool: bool,
Nil,
Number: f64,
Obj: *Obj,
pub fn isBool(self: UnionValue) bool {
return self == .Bool;
}
pub fn isNil(self: UnionValue) bool {
return self == .Nil;
}
pub fn isNumber(self: UnionValue) bool {
return self == .Number;
}
pub fn isObj(self: UnionValue) bool {
return self == .Obj;
}
pub fn asBool(self: UnionValue) bool {
std.debug.assert(self.isBool());
return self.Bool;
}
pub fn asNumber(self: UnionValue) f64 {
std.debug.assert(self.isNumber());
return self.Number;
}
pub fn asObj(self: UnionValue) *Obj {
std.debug.assert(self.isObj());
return self.Obj;
}
pub fn fromBool(x: bool) UnionValue {
return UnionValue{ .Bool = x };
}
pub fn nil() UnionValue {
return .Nil;
}
pub fn fromNumber(x: f64) UnionValue {
return UnionValue{ .Number = x };
}
pub fn fromObj(x: *Obj) UnionValue {
return UnionValue{ .Obj = x };
}
pub fn isFalsey(self: UnionValue) bool {
return switch (self) {
.Bool => |x| !x,
.Nil => true,
.Number => false,
.Obj => false,
};
}
pub fn equals(aBoxed: UnionValue, bBoxed: UnionValue) bool {
return switch (aBoxed) {
.Bool => |a| {
return switch (bBoxed) {
.Bool => |b| a == b,
else => false,
};
},
.Nil => |a| {
return switch (bBoxed) {
.Nil => true,
else => false,
};
},
.Number => |a| {
return switch (bBoxed) {
.Number => |b| a == b,
else => false,
};
},
.Obj => |a| {
return switch (bBoxed) {
.Obj => |b| a == b,
else => false,
};
},
};
}
pub fn format(self: UnionValue, comptime fmt: []const u8, options: std.fmt.FormatOptions, out_stream: anytype) !void {
switch (self) {
.Number => |value| try out_stream.print("{d}", .{value}),
.Bool => |value| try out_stream.print("{}", .{value}),
.Nil => try out_stream.print("nil", .{}),
.Obj => |obj| try printObject(obj, out_stream),
}
}
};
// Shared between the two value representations
fn printObject(obj: *Obj, out_stream: anytype) !void {
switch (obj.objType) {
.String => try out_stream.print("{s}", .{obj.asString().bytes}),
.Function => {
const name = if (obj.asFunction().name) |str| str.bytes else "<script>";
try out_stream.print("<fn {s}>", .{name});
},
.NativeFunction => {
try out_stream.print("<native fn>", .{});
},
.Closure => {
const name = if (obj.asClosure().function.name) |str| str.bytes else "<script>";
try out_stream.print("<fn {s}>", .{name});
},
.Upvalue => {
try out_stream.print("upvalue", .{});
},
.Class => {
try out_stream.print("{s}", .{obj.asClass().name.bytes});
},
.Instance => {
try out_stream.print("{s} instance", .{obj.asInstance().class.name.bytes});
},
.BoundMethod => {
const name = if (obj.asBoundMethod().method.function.name) |str| str.bytes else "<script>";
try out_stream.print("<fn {s}>", .{name});
},
}
} | src/value.zig |
const std = @import("std");
pub const Tag = enum {
float,
ident,
int,
raw_str,
string,
uint,
kw_and,
kw_break,
kw_continue,
kw_do,
kw_else,
kw_if,
kw_or,
kw_return,
kw_select,
kw_while,
pd_false,
pd_nil,
pd_true,
pd_assert,
pd_atan2,
pd_capture,
pd_chars,
pd_col,
pd_contains,
pd_cos,
pd_each,
pd_endsWith,
pd_exp,
pd_filter,
pd_int,
pd_indexOf,
pd_join,
pd_keys,
pd_keysByValueAsc,
pd_keysByValueDesc,
pd_lastIndexOf,
pd_len,
pd_log,
pd_map,
pd_max,
pd_mean,
pd_median,
pd_memo,
pd_min,
pd_mode,
pd_next,
pd_print,
pd_pop,
pd_push,
pd_rand,
pd_reduce,
pd_replace,
pd_reset,
pd_reverse,
pd_sin,
pd_sortAsc,
pd_sortDesc,
pd_split,
pd_sqrt,
pd_startsWith,
pd_stdev,
pd_toLower,
pd_toUpper,
pd_unique,
pd_values,
pd_onInit,
pd_onFile,
pd_onRec,
pd_onExit,
at_cols,
at_file,
at_frnum,
at_head,
at_headers,
at_ics,
at_irs,
at_ocs,
at_ors,
at_rec,
at_rnum,
op_add_eq,
op_concat,
op_define,
op_div_eq,
op_elvis,
op_elvis_eq,
op_eq,
op_gte,
op_lte,
op_mod_eq,
op_mul_eq,
op_neg,
op_neq,
op_range_ex,
op_range_in,
op_repeat,
op_sub_eq,
op_redir_append,
op_redir_clobber,
op_match,
op_matcher,
op_nomatch,
punct_at,
punct_bang,
punct_colon,
punct_comma,
punct_dollar,
punct_dot,
punct_equals,
punct_fat_rarrow,
punct_gt,
punct_lbrace,
punct_lbracket,
punct_lparen,
punct_lt,
punct_minus,
punct_newline,
punct_percent,
punct_pipe,
punct_plus,
punct_question,
punct_rbrace,
punct_rbracket,
punct_rparen,
punct_semicolon,
punct_slash,
punct_star,
punct_tilde,
};
pub const predef = std.ComptimeStringMap(Tag, .{
.{ "and", .kw_and },
.{ "break", .kw_break },
.{ "continue", .kw_continue },
.{ "do", .kw_do },
.{ "else", .kw_else },
.{ "if", .kw_if },
.{ "or", .kw_or },
.{ "false", .pd_false },
.{ "nil", .pd_nil },
.{ "return", .kw_return },
.{ "select", .kw_select },
.{ "true", .pd_true },
.{ "while", .kw_while },
.{ "assert", .pd_assert },
.{ "atan2", .pd_atan2 },
.{ "capture", .pd_capture },
.{ "chars", .pd_chars },
.{ "col", .pd_col },
.{ "contains", .pd_contains },
.{ "cos", .pd_cos },
.{ "each", .pd_each },
.{ "endsWith", .pd_endsWith },
.{ "exp", .pd_exp },
.{ "filter", .pd_filter },
.{ "int", .pd_int },
.{ "indexOf", .pd_indexOf },
.{ "join", .pd_join },
.{ "keys", .pd_keys },
.{ "keysByValueAsc", .pd_keysByValueAsc },
.{ "keysByValueDesc", .pd_keysByValueDesc },
.{ "lastIndexOf", .pd_lastIndexOf },
.{ "len", .pd_len },
.{ "log", .pd_log },
.{ "map", .pd_map },
.{ "max", .pd_max },
.{ "mean", .pd_mean },
.{ "median", .pd_median },
.{ "memo", .pd_memo },
.{ "min", .pd_min },
.{ "mode", .pd_mode },
.{ "next", .pd_next },
.{ "print", .pd_print },
.{ "pop", .pd_pop },
.{ "push", .pd_push },
.{ "rand", .pd_rand },
.{ "reduce", .pd_reduce },
.{ "replace", .pd_replace },
.{ "reset", .pd_reset },
.{ "reverse", .pd_reverse },
.{ "sin", .pd_sin },
.{ "sortAsc", .pd_sortAsc },
.{ "sortDesc", .pd_sortDesc },
.{ "split", .pd_split },
.{ "sqrt", .pd_sqrt },
.{ "startsWith", .pd_startsWith },
.{ "stdev", .pd_stdev },
.{ "toLower", .pd_toLower },
.{ "toUpper", .pd_toUpper },
.{ "unique", .pd_unique },
.{ "values", .pd_values },
.{ "onInit", .pd_onInit },
.{ "onFile", .pd_onFile },
.{ "onRec", .pd_onRec },
.{ "onExit", .pd_onExit },
.{ "@cols", .at_cols },
.{ "@file", .at_file },
.{ "@frnum", .at_frnum },
.{ "@head", .at_head },
.{ "@headers", .at_headers },
.{ "@ics", .at_ics },
.{ "@irs", .at_irs },
.{ "@ocs", .at_ocs },
.{ "@ors", .at_ors },
.{ "@rec", .at_rec },
.{ "@rnum", .at_rnum },
});
len: u16,
offset: u16,
tag: Tag,
const Token = @This();
pub fn new(tag: Tag, offset: u16, len: usize) Token {
return Token{
.len = @intCast(u16, len),
.offset = offset,
.tag = tag,
};
}
pub fn is(self: Token, tag: Tag) bool {
return self.tag == tag;
} | src/Token.zig |
const expect = std.testing.expect;
const expectEqualSlices = std.testing.expectEqualSlices;
const std = @import("std");
const Allocator = std.mem.Allocator;
const Connect = @import("./packet/connect.zig").Connect;
const ConnAck = @import("./packet/connack.zig").ConnAck;
const Publish = @import("./packet/publish.zig").Publish;
const PubAck = @import("./packet/puback.zig").PubAck;
const PubRec = @import("./packet/pubrec.zig").PubRec;
const PubRel = @import("./packet/pubrel.zig").PubRel;
const PubComp = @import("./packet/pubcomp.zig").PubComp;
const Subscribe = @import("./packet/subscribe.zig").Subscribe;
const SubAck = @import("./packet/suback.zig").SubAck;
const Unsubscribe = @import("./packet/unsubscribe.zig").Unsubscribe;
const UnsubAck = @import("./packet/unsuback.zig").UnsubAck;
const PingReq = @import("./packet/pingreq.zig").PingReq;
const PingResp = @import("./packet/pingresp.zig").PingResp;
const Disconnect = @import("./packet/disconnect.zig").Disconnect;
pub const PacketType = enum(u4) {
connect = 1,
connack,
publish,
puback,
pubrec,
pubrel,
pubcomp,
subscribe,
suback,
unsubscribe,
unsuback,
pingreq,
pingresp,
disconnect,
};
pub const Packet = union(PacketType) {
connect: Connect,
connack: ConnAck,
publish: Publish,
puback: PubAck,
pubrec: PubRec,
pubrel: PubRel,
pubcomp: PubComp,
subscribe: Subscribe,
suback: SubAck,
unsubscribe: Unsubscribe,
unsuback: UnsubAck,
pingreq: PingReq,
pingresp: PingResp,
disconnect: Disconnect,
pub const FixedHeader = struct {
packet_type: PacketType,
flags: u4,
remaining_length: u32,
};
pub const ParseError = error{InvalidLength};
pub fn deinit(self: *Packet, allocator: *Allocator) void {
inline for (@typeInfo(PacketType).Enum.fields) |field| {
const packet_type_name = field.name;
const packet_type = @intToEnum(PacketType, field.value);
if (self.* == packet_type) {
@field(self, packet_type_name).deinit(allocator);
return;
}
}
unreachable;
}
pub fn parse(allocator: *Allocator, reader: anytype) !Packet {
const type_and_flags: u8 = try reader.readByte();
const parsed_packet_type = @intToEnum(PacketType, @intCast(u4, type_and_flags >> 4));
const flags = @intCast(u4, type_and_flags & 0b1111);
const remaining_length = try parseRemainingLength(reader);
const fixed_header = FixedHeader{
.packet_type = parsed_packet_type,
.flags = flags,
.remaining_length = remaining_length,
};
inline for (@typeInfo(PacketType).Enum.fields) |field| {
const packet_type_name = field.name;
const packet_type = @intToEnum(PacketType, field.value);
const packet_struct = comptime brk: inline for (@typeInfo(Packet).Union.fields) |union_field| {
if (std.mem.eql(u8, union_field.name, packet_type_name)) {
break :brk union_field.field_type;
}
};
if (parsed_packet_type == packet_type) {
const parsed = try packet_struct.parse(fixed_header, allocator, reader);
return @unionInit(Packet, packet_type_name, parsed);
}
}
unreachable;
}
fn parseRemainingLength(reader: anytype) !u32 {
var byte = try reader.readByte();
var multiplier: u32 = 1;
var value: u32 = 0;
// Decode variable remaining length
while (byte & 128 != 0) : (byte = try reader.readByte()) {
value += (byte & 127) * multiplier;
multiplier *= 128;
if (multiplier > 128 * 128 * 128) {
return error.InvalidLength;
}
}
value += (byte & 127) * multiplier;
return value;
}
fn serializeRemainingLength(remaining_length: u32, writer: anytype) !void {
var value: u32 = remaining_length;
while (value != 0) {
var byte: u8 = @intCast(u8, value % 128);
value /= 128;
if (value > 0) {
byte |= 128;
}
try writer.writeByte(byte);
}
}
pub fn serialize(self: *const Packet, writer: anytype) !void {
inline for (@typeInfo(PacketType).Enum.fields) |field| {
const packet_type_name = field.name;
const packet_type_value: u8 = field.value;
const packet_type = @intToEnum(PacketType, field.value);
if (self.* == packet_type) {
const inner_packet = @field(self, packet_type_name);
const type_and_flags: u8 = @shlExact(packet_type_value, 4) | inner_packet.fixedHeaderFlags();
try writer.writeByte(type_and_flags);
const remaining_length = inner_packet.serializedLength();
try serializeRemainingLength(remaining_length, writer);
try inner_packet.serialize(writer);
return;
}
}
unreachable;
}
};
test "minimal Connect packet parsing" {
const allocator = std.testing.allocator;
const buffer =
// Type and flags
[_]u8{0b00010000} ++
// Remaining length, 12
"\x0c" ++
// Protocol name length
"\x00\x04" ++
// Protocol name
"MQTT" ++
// Protocol version, 4 == 3.1.1
"\x04" ++
// Flags, empty
"\x00" ++
// Keepalive, 60
"\x00\x3c" ++
// Client id length, 0
"\x00\x00";
const stream = std.io.fixedBufferStream(buffer).reader();
var packet = try Packet.parse(allocator, stream);
defer packet.deinit(allocator);
const connect = packet.connect;
try expect(connect.clean_session == false);
try expect(connect.keepalive == 60);
try expect(connect.client_id.len == 0);
try expect(connect.will == null);
try expect(connect.username == null);
try expect(connect.password == null);
}
test "minimal Connect packet serialization roundtrip" {
const QoS = @import("../qos.zig").QoS;
const Will = @import("./packet/connect.zig").Will;
const connect = Connect{
.clean_session = true,
.keepalive = 60,
.client_id = "",
.will = Will{
.topic = "foo/bar",
.message = "bye",
.qos = QoS.qos1,
.retain = false,
},
.username = "user",
.password = "<PASSWORD>",
};
const packet = Packet{
.connect = connect,
};
var buffer = [_]u8{0} ** 100;
var stream = std.io.fixedBufferStream(&buffer);
var writer = stream.writer();
try packet.serialize(writer);
const written = try stream.getPos();
stream.reset();
const reader = stream.reader();
const allocator = std.testing.allocator;
var deser_packet = try Packet.parse(allocator, reader);
defer deser_packet.deinit(allocator);
var deser_connect = deser_packet.connect;
try expect(connect.clean_session == deser_connect.clean_session);
try expect(connect.keepalive == deser_connect.keepalive);
try expectEqualSlices(u8, connect.client_id, deser_connect.client_id);
try expectEqualSlices(u8, connect.will.?.topic, deser_connect.will.?.topic);
try expectEqualSlices(u8, connect.will.?.message, deser_connect.will.?.message);
try expect(connect.will.?.qos == deser_connect.will.?.qos);
try expect(connect.will.?.retain == deser_connect.will.?.retain);
try expectEqualSlices(u8, connect.username.?, deser_connect.username.?);
try expectEqualSlices(u8, connect.password.?, deser_connect.password.?);
}
test "parse remaining length > 127" {
const buffer =
// Remaining length, 212, encoded with the MQTT algorithm
"\xd4" ++
"\x01";
const stream = std.io.fixedBufferStream(buffer).reader();
var remainingLength = try Packet.parseRemainingLength(stream);
try expect(remainingLength == 212);
}
test "packet" {
_ = @import("./packet/connect.zig");
_ = @import("./packet/connack.zig");
} | src/mqtt4/packet.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/day12.txt");
// const data = @embedFile("../data/day12-tst1.txt");
// const data = @embedFile("../data/day12-tst2.txt");
// const data = @embedFile("../data/day12-tst3.txt");
pub fn main() !void {
var it = tokenize(u8, data, "\r\n");
var visited = StrMap(void).init(gpa);
var nodes = StrMap(List(Str)).init(gpa);
while (it.next()) |line| {
var links = tokenize(u8, line, "-");
var a = links.next().?;
var b = links.next().?;
if (!nodes.contains(a)) {
var name = gpa.dupe(u8, a) catch unreachable;
try nodes.put(name, List(Str).init(gpa));
}
if (!nodes.contains(b)) {
var name = gpa.dupe(u8, b) catch unreachable;
try nodes.put(name, List(Str).init(gpa));
}
var owned_a = nodes.getKey(a).?;
var owned_b = nodes.getKey(b).?;
nodes.getPtr(a).?.append(owned_b) catch unreachable;
nodes.getPtr(b).?.append(owned_a) catch unreachable;
}
var visited_smol_cave = false; // Make this true for part1
const count = visit("start", nodes, &visited, &visited_smol_cave);
print("{}\n", .{count});
var node_it = nodes.keyIterator();
while (node_it.next()) |node| {
gpa.free(node.*);
}
nodes.deinit();
}
var indent_level: u32 = 0;
fn printIndent() void {
var i: u32 = 0;
while (i < indent_level) : (i += 1) {
print(" ", .{});
}
}
fn visit(node: Str, nodes: StrMap(List(Str)), visited: *StrMap(void), visited_smol_cave: *bool) u32 {
if (getNodeType(node) == .end) {
return 1;
}
var count: u32 = 0;
var children = nodes.get(node).?;
for (children.items) |child| {
const node_type = getNodeType(child);
var first_small_cave = false;
if (node_type == .start) continue;
if (node_type == .small and visited.contains(child)) {
if (visited_smol_cave.*) {
continue;
} else {
visited_smol_cave.* = true;
first_small_cave = true;
}
}
visited.put(child, {}) catch unreachable;
count += visit(child, nodes, visited, visited_smol_cave);
if (first_small_cave) {
visited_smol_cave.* = false;
} else {
_ = visited.remove(child);
}
}
return count;
}
const NodeType = enum {
start,
end,
small,
big,
};
fn getNodeType(name: Str) NodeType {
if (std.mem.eql(u8, name, "start")) return NodeType.start;
if (std.mem.eql(u8, name, "end")) return NodeType.end;
if (name[0] >= 'a' and name[0] <= 'z') return NodeType.small;
return NodeType.big;
}
// 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/day12.zig |
const std = @import("std");
const RaxStack = @import("./stack.zig").RaxStack;
const RaxNode = @import("./node.zig").RaxNode;
const RaxIterator = @import("./iterator.zig").RaxIterator;
pub fn Rax(comptime V: type) type {
return struct {
allocator: *std.mem.Allocator,
head: *NodeT,
numElements: u64,
numNodes: u64,
const Self = @This();
pub const NodeT = comptime RaxNode(V);
pub const StackT = comptime RaxStack(NodeT, 32);
pub const IterT = comptime RaxIterator(Self, 128);
pub const ValueT = V;
pub fn init(allocator: *std.mem.Allocator) !Self {
return Self{
.allocator = allocator,
.head = try NodeT.initEmpty(allocator),
.numNodes = 1,
.numElements = 0,
};
}
pub fn deinit(self: *Self) void {
const deletedNodes = self.head.deinit(self.allocator, 0);
if (self.numNodes != deletedNodes) {
std.debug.warn("numnodes = {} deleted = {}", .{ self.numNodes, deletedNodes });
@panic("free didn't free!");
}
}
pub const OperationResult = union(enum) {
Nothing,
Found: V,
};
pub fn insert(self: *Self, key: []const u8, value: V) !OperationResult {
return insertImpl(self, key, value, false);
}
pub fn insertOverride(self: *Self, key: []const u8, value: V) !OperationResult {
return insertImpl(self, key, value, true);
}
// TODO: override is not comptime. Should it be?
fn insertImpl(self: *Self, key: []const u8, value: V, override: bool) !OperationResult {
var wk = self.lowWalk(key);
var i = wk.bytesMatched;
var currentNode = wk.stopNode;
var j = wk.splitPos;
// /* If i == len we walked following the whole string. If we are not
// * in the middle of a compressed node, the string is either already
// * inserted or this middle node is currently not a key, but can represent
// * our key. We have just to reallocate the node and make space for the
// * data pointer. */
if (i == key.len and
(currentNode.layout != .Compressed or wk.splitPos == 0))
{
if (currentNode.key) |oldValue| {
if (override) {
currentNode.key = value;
}
return OperationResult{ .Found = oldValue };
} else {
currentNode.key = value;
self.numElements += 1;
return .Nothing;
}
}
// Algo 1
if (currentNode.layout == .Compressed and i != key.len) {
var currentData = ¤tNode.layout.Compressed;
// We are breaking up the current node in two parts.
// We will need to create a branching node for the point of devergence,
// and other nodes to make space for the new suffixes (the old suffix
// from this node, and the new suffix for the remaining chars in key).
// We start by creating the suffix nodes (+ eventual extra emtpy nodes),
// and at the end of the procedure we create the branching node that they
// will have to be connected to.
// Create the node containing the current node's suffix (skipping j,
// the char that will be put in a branching node).
var oldSuffixNode = try self.createSuffixForOldElement(currentNode, j + 1);
// Create an empty node for the new suffix. It will be populated by
// the node downstream (the while loop).
var newSuffixNode = try NodeT.initEmpty(self.allocator);
// Create the branching node for the split-off point and connect
// the nodes we previously created to it.
var branchingNode: *NodeT = undefined;
var newSuffixSlot: usize = undefined;
{
var oldSuffixSlot: usize = undefined;
// We must maintain lexicographial ordering for the branches in
// the new branching node.
if (currentData.chars[j] < key[i]) {
oldSuffixSlot = 0;
newSuffixSlot = 1;
} else {
oldSuffixSlot = 1;
newSuffixSlot = 0;
}
var chars: [2]u8 = undefined;
chars[oldSuffixSlot] = currentData.chars[j];
chars[newSuffixSlot] = key[i];
var children: [2]*NodeT = undefined;
children[oldSuffixSlot] = oldSuffixNode;
children[newSuffixSlot] = newSuffixNode;
// If we are splitting right at the beginning, change the current node
// to be the branching node, otherwise allocate a new one.
if (j == 0) {
var branches = try self.allocator.alloc(NodeT.Branch, 2);
branches[oldSuffixSlot] = .{
.char = chars[oldSuffixSlot],
.child = children[oldSuffixSlot],
};
branches[newSuffixSlot] = .{
.char = chars[newSuffixSlot],
.child = children[newSuffixSlot],
};
branchingNode = currentNode;
branchingNode.layout = .{
.Branching = branches,
};
} else {
// Create the split node (the split node has a .Branching layout)
branchingNode = try NodeT.initBranchNode(2, self.allocator, chars, children);
self.numNodes += 1;
}
// The rest of the algorithm will add the actual new key suffix node.
// In this segment we only setup the branching part.
}
if (j > 0) {
// Trim the current node by removing the suffix + branching point and
// set nextPtr to the new branching node just created.
try self.trimCommonPrefixNode(currentNode, j, branchingNode);
}
// Move the 'currentNode' reference to the new empty node created for
// the newSuffix and let the next code to deal with it.
currentNode = branchingNode.layout.Branching[newSuffixSlot].child;
i += 1;
} else if (currentNode.layout == .Compressed and i == key.len) {
var currentData = ¤tNode.layout.Compressed;
// Child containing the current node's suffix.
var oldSuffixNode = try self.createSuffixForOldElement(currentNode, j);
try self.trimCommonPrefixNode(currentNode, j, oldSuffixNode);
currentNode = oldSuffixNode;
i = key.len;
}
while (i < key.len) {
const isEmpty = currentNode.size() == 0;
if (isEmpty and key.len - i > 1) {
var chunkSize = key.len - i;
// this should be maxsize of u29 in the
// real implementation.
if (chunkSize > std.math.maxInt(usize)) {
chunkSize = std.math.maxInt(usize);
}
// TODO: error handling procedure
try currentNode.makeCompressed(self.allocator, key[i..]);
self.numNodes += 1;
i += chunkSize;
currentNode = currentNode.layout.Compressed.next;
} else {
const emptyNode = try NodeT.initEmpty(self.allocator);
self.numNodes += 1;
errdefer {
_ = emptyNode.deinit(self.allocator, 0);
}
const oldBranches = currentNode.layout.Branching;
var newBranches = try self.allocator.alloc(NodeT.Branch, oldBranches.len + 1);
var greaterThan = newBranches.len - 1;
for (oldBranches) |b, x| {
if (b.char > key[x]) {
greaterThan = x;
break;
}
}
// TODO: break this up into 2 loops without ifs in them.
for (newBranches) |*b, idx| {
if (idx < greaterThan) {
b.* = oldBranches[idx];
}
if (idx == greaterThan) {
newBranches[idx] = .{
.char = key[i],
.child = emptyNode,
};
}
if (idx > greaterThan) {
b.* = oldBranches[idx - 1];
}
}
self.allocator.free(oldBranches);
currentNode.layout.Branching = newBranches;
i += 1;
currentNode = emptyNode;
}
}
if (currentNode.key == null) {
self.numElements += 1;
}
currentNode.key = value;
return .Nothing;
}
fn createSuffixForOldElement(self: *Self, currentNode: *NodeT, startPos: usize) !*NodeT {
var oldSuffixNode: *NodeT = undefined;
var currentData = ¤tNode.layout.Compressed;
// If there's a suffix that we broke off from the original node,
// we need to allocate a new compressed node for it.
const oldSuffixLen = currentData.chars.len - startPos;
if (oldSuffixLen > 0) { // At least 1 char in suffix.
if (oldSuffixLen == 1) {
// Single-char suffix means we create a branching child node
// for it and then attach the current child as it's child
// corresponding to the only present branch
oldSuffixNode = try NodeT.initBranchNode(
1,
self.allocator,
[1]u8{currentData.chars[startPos]},
[1]*NodeT{currentData.next},
);
self.numNodes += 1;
} else {
// Multiple chars in the suffix -> create compressed node.
oldSuffixNode = try NodeT.initCompressedNode(
self.allocator,
currentData.chars[startPos..],
currentData.next,
);
self.numNodes += 1;
}
} else {
// No suffix, we branched at the last char, so the child
// corresponding to this char is directly the old child (next)
oldSuffixNode = currentData.next;
}
return oldSuffixNode;
}
fn trimCommonPrefixNode(self: *Self, currentNode: *NodeT, j: usize, nextNode: *NodeT) !void {
var currentData = ¤tNode.layout.Compressed;
if (j == 1) {
const firstLetter = currentData.chars[0];
self.allocator.free(currentData.chars);
var branches = try self.allocator.alloc(NodeT.Branch, 1);
branches[0] = .{
.char = firstLetter,
.child = nextNode,
};
// Change the layout of the prefix node to Branching
currentNode.layout = .{ .Branching = branches };
} else {
currentData.chars = self.allocator.shrink(currentData.chars, j);
currentData.next = nextNode;
}
}
/// Removes a key from the tree. The return value will contain
/// the value corresponding to the removed key, if the key was found.
pub fn remove(self: *Self, key: []const u8) !OperationResult {
var treeStack: StackT = undefined;
treeStack.init();
defer treeStack.deinit(self.allocator);
const wr = try self.lowWalkStack(key, &treeStack);
var i = wr.bytesMatched;
var currentNode = wr.stopNode;
const splitPos = wr.splitPos;
// No match was found
{
const middleOfCompressedNode = currentNode.layout == .Compressed and splitPos != 0;
if (i != key.len or middleOfCompressedNode or currentNode.key == null) {
return .Nothing;
}
}
const result = OperationResult{ .Found = currentNode.key.? };
currentNode.key = null;
self.numElements -= 1;
var tryToCompress = false;
const size = currentNode.size();
if (size == 0) {
var child = currentNode;
while (currentNode != self.head) {
child = currentNode;
_ = child.deinit(self.allocator, 0);
self.numNodes -= 1;
currentNode = treeStack.pop();
const hasChildren = currentNode.layout == .Branching and currentNode.layout.Branching.len != 1;
if (currentNode.key != null or hasChildren) {
break;
}
}
// We now need to remove a reference to the last freed child
// from the parent node currently pointed to by currentNode.
// (Original code checked here if child is not null.)
currentNode.removeChild(self.allocator, child);
if (currentNode.size() == 1 and currentNode.key == null) {
tryToCompress = true;
}
} else if (size == 1) {
tryToCompress = true;
}
// TODO: no compression if oom
if (tryToCompress) {
var parent: *NodeT = undefined;
while (true) {
parent = treeStack.pop(); // this is where we might be popping null from it
const hasChildren = parent.layout == .Branching and parent.layout.Branching.len != 1;
if (parent.key != null or hasChildren) {
break;
}
currentNode = parent;
}
const startNode = currentNode;
var compressedSize = currentNode.size();
var nodes: u32 = 1;
// TODO: right now we repurpose currentNode even when
// it might make more sense to realloc another node that already
// is using more memory. Example:
// `-(b) [a] -> "nana" -> []=3
// would it be worht it to try and remember which is the biggest node
// we encountered previously when running down the tree and realloc that
// instead of currentNode unconditionally?
while (currentNode.size() != 0) {
currentNode = switch (currentNode.layout) {
.Compressed => |c| c.next,
.Branching => |b| b[b.len - 1].child, // TODO: does it have to be the last? why not the first?
};
const hasChildren = currentNode.layout == .Branching and currentNode.layout.Branching.len != 1;
if (currentNode.key != null or hasChildren) {
break;
}
if (compressedSize + currentNode.size() > std.math.maxInt(usize)) {
break;
}
nodes += 1;
compressedSize += currentNode.size();
}
// This is the last node we visited, which is the first
// node that will *NOT* be compressed.
const lastNode = currentNode;
if (nodes > 1) {
// Save startNode's child pointer because we need it
// and we're about to clobber the node's layout.
// Realloc chars in startNode to make space for
// all the extra chars coming from its children.
var startNodeCharCount: usize = undefined;
switch (startNode.layout) {
.Compressed => |*c| {
currentNode = c.next;
startNodeCharCount = c.chars.len;
c.chars = try self.allocator.realloc(c.chars, compressedSize);
c.next = lastNode;
},
.Branching => |b| {
const branch = b[b.len - 1];
startNodeCharCount = 1;
currentNode = branch.child; // TODO: does it have to be the last? why not the first?
self.allocator.free(b);
startNode.layout = .{
.Compressed = .{
.chars = try self.allocator.alloc(u8, compressedSize),
.next = lastNode,
},
};
startNode.layout.Compressed.chars[0] = branch.char;
},
}
// Run down the compressable path again,
// but this time we copy over chars & free nodes
// as we go.
const newChars = startNode.layout.Compressed.chars;
while (true) {
// Copy chars and move down
const oldNode = currentNode;
switch (currentNode.layout) {
.Compressed => |c| {
std.mem.copy(u8, newChars[startNodeCharCount..], c.chars);
startNodeCharCount += c.chars.len;
currentNode = c.next;
self.allocator.free(c.chars);
},
.Branching => |b| {
const branch = b[b.len - 1]; // TODO: does it have to be the last? why not the first?
newChars[startNodeCharCount] = branch.char;
startNodeCharCount += 1;
currentNode = branch.child;
self.allocator.free(b);
},
}
self.allocator.destroy(oldNode);
self.numNodes -= 1;
// We stop once we reach the previously identified lastNode.
if (currentNode == lastNode) {
break;
}
}
}
}
return result;
}
// TODO: should s be named key? Do we ever search
// for "partials"?
// TODO: is returning a struct better or worse than
// writing to pointers?
const WalkResult = struct {
bytesMatched: usize,
stopNode: *NodeT,
splitPos: usize, // In real impl it's u29
};
fn lowWalk(self: *Self, s: []const u8) WalkResult {
return self.lowWalkImlp(s, null) catch unreachable;
}
pub fn lowWalkStack(self: *Self, s: []const u8, treeStack: *StackT) !WalkResult {
return self.lowWalkImlp(s, treeStack);
}
// This function cannot fail if no treeStack is provided.
fn lowWalkImlp(self: *Self, s: []const u8, treeStack: ?*StackT) !WalkResult {
var node = self.head;
var i: usize = 0;
var j: usize = 0;
while (i < s.len) {
switch (node.layout) {
.Compressed => |data| {
if (data.chars.len == 0) break;
j = 0;
while (j < data.chars.len and i < s.len) {
if (data.chars[j] != s[i]) break;
j += 1;
i += 1;
}
if (j != data.chars.len) break;
},
.Branching => |branches| {
if (branches.len == 0) break;
// rax does a linear scan, so we do too.
while (j < branches.len and i < s.len) : (j += 1) {
if (branches[j].char == s[i]) break;
}
if (j == branches.len) break;
i += 1;
},
}
// If a stack was provided, push the visited
// node's pointer into it.
if (treeStack) |ts| try ts.push(self.allocator, node);
node = switch (node.layout) {
.Compressed => |c| c.next,
.Branching => |b| b[j].child,
};
j = 0;
}
return WalkResult{
.bytesMatched = i,
.stopNode = node,
.splitPos = j,
};
}
pub fn show(self: *Self) void {
recursiveShow(0, 0, self.head);
std.debug.warn("\n", .{});
}
fn recursiveShow(level: usize, lp: usize, node: *NodeT) void {
var lpad = lp;
const isCompressed = node.layout == .Compressed;
const start: u8 = if (isCompressed) '"' else '[';
const end: u8 = if (isCompressed) '"' else ']';
var numchars: usize = 2;
switch (node.layout) {
.Compressed => |compressed| {
std.debug.warn("{c}{}{c}", .{ start, compressed.chars, end });
numchars += compressed.chars.len;
},
.Branching => |branches| {
std.debug.warn("{c}", .{start});
for (branches) |b| {
std.debug.warn("{c}", .{b.char});
}
std.debug.warn("{c}", .{end});
numchars += branches.len;
},
}
if (node.key) |value| {
if (@TypeOf(value) != void) {
std.debug.warn("={}", .{value});
}
numchars += 4;
}
if (level > 0) {
lpad += switch (node.layout) {
.Compressed => @as(usize, 4),
.Branching => |b| switch (b.len) {
0 => @as(usize, 4),
1 => @as(usize, 4) + numchars,
else => @as(usize, 7),
},
};
}
switch (node.layout) {
.Compressed => |compressed| {
std.debug.warn(" -> ", .{});
recursiveShow(level + 1, lpad, compressed.next);
},
.Branching => |branches| {
for (branches) |*br, idx| {
if (branches.len > 1) {
std.debug.warn("\n", .{});
var i: usize = 0;
while (i < lpad) : (i += 1) std.debug.warn(" ", .{});
std.debug.warn(" `-({c}) ", .{br.char});
} else {
std.debug.warn(" -> ", .{});
}
recursiveShow(level + 1, lpad, br.child);
}
},
}
}
};
}
test "works" {
const MyRax = Rax(void);
var r = try MyRax.init(std.testing.allocator);
defer r.deinit();
}
test "try simple insert" {
const MyRax = Rax(void);
var r = try MyRax.init(std.testing.allocator);
defer r.deinit();
_ = try r.insert("banana", {});
} | src/simple/rax.zig |
const std = @import("std");
const warn = std.debug.warn;
const assert = std.debug.assert;
const Vector = @import("Vector.zig").Vector;
pub fn Matrix(comptime T: type, comptime S: u32) type {
return struct {
const Self = @This();
data: [S][S]T,
// Values in column-major layout
pub fn init(values: [S][S]T) Self {
comptime {
if (S < 2) {
@compileError("Matrices must be at least 2x2");
}
}
var a: Self = undefined;
var i: u32 = 0;
while (i < S) : (i += 1) {
var j: u32 = 0;
while (j < S) : (j += 1) {
a.data[j][i] = values[i][j];
}
}
return a;
}
pub fn loadFromSlice(self: Matrix(T, S), slice: []const T) !void {
if (slice.len != S * S) {
assert(false);
return error.InvalidSliceLength;
}
std.mem.copy(f32, @intToPtr([*c]f32, @ptrToInt(&self.data[0][0]))[0 .. S * S], slice);
}
pub fn setArray(self: Matrix(T, S), out: *([S][S]T)) void {
var i: u32 = 0;
while (i < S) : (i += 1) {
var j: u32 = 0;
while (j < S) : (j += 1) {
out.*[i][j] = self.data[i][j];
}
}
}
pub fn copy(self: Matrix(T, S)) Matrix(T, S) {
var new: Matrix(T, S) = undefined;
var i: u32 = 0;
while (i < S) : (i += 1) {
var j: u32 = 0;
while (j < S) : (j += 1) {
new.data[i][j] = self.data[i][j];
}
}
return new;
}
pub fn identity() Matrix(T, S) {
comptime var m: Matrix(T, S) = undefined;
comptime {
var i: u32 = 0;
while (i < S) : (i += 1) {
var j: u32 = 0;
while (j < S) : (j += 1) {
if (i == j) {
m.data[i][j] = 1;
} else {
m.data[i][j] = 0;
}
}
}
}
return m;
}
pub fn mul(self: Matrix(T, S), m: Matrix(T, S)) Matrix(T, S) {
var new: Matrix(T, S) = undefined;
var i: u32 = 0;
while (i < S) : (i += 1) {
var j: u32 = 0;
while (j < S) : (j += 1) {
var sum: T = 0;
var k: u32 = 0;
while (k < S) : (k += 1) {
sum += self.data[i][k] * m.data[k][j];
}
new.data[i][j] = sum;
}
}
return new;
}
pub fn translate(v: Vector(T, S - 1)) Matrix(T, S) {
comptime {
if (S != 3 and S != 4) {
@compileError("Translate is only for 3x3 matrices (2D) and 4x4 matrices (3D).");
}
}
var m: Matrix(T, S) = Matrix(T, S).identity();
if (S == 4) {
m.data[3][0] = v.x();
m.data[3][1] = v.y();
m.data[3][2] = v.z();
} else if (S == 3) {
m.data[2][0] = v.x();
m.data[2][1] = v.y();
}
return m;
}
pub fn scale(v: Vector(T, S)) Matrix(T, S) {
comptime {
if (S != 2 and S != 3 and S != 4) {
@compileError("Scale is only for 2x2 matrices (2D) 3x3 matrices (2D/3D) and 4x4 matrices (3D).");
}
}
var m: Matrix(T, S) = Matrix(T, S).identity();
if (S == 4) {
m.data[0][0] = v.x();
m.data[1][1] = v.y();
m.data[2][2] = v.z();
m.data[3][3] = v.w();
} else if (S == 3) {
m.data[0][0] = v.x();
m.data[1][1] = v.y();
m.data[2][2] = v.z();
} else if (S == 2) {
m.data[0][0] = v.x();
m.data[1][1] = v.y();
}
return m;
}
// https://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations
pub fn rotateX(angle: T) Matrix(T, S) {
comptime {
if (S != 3 and S != 4) {
@compileError("Rotation about an axis is only for 3x3 matrices and 4x4 matrices.");
}
}
var m: Matrix(T, S) = Matrix(T, S).identity();
const sinTheta = std.math.sin(angle);
const cosTheta = std.math.cos(angle);
m.data[1][1] = cosTheta;
m.data[1][2] = -sinTheta;
m.data[2][2] = cosTheta;
m.data[2][1] = sinTheta;
return m;
}
pub fn rotateY(angle: T) Matrix(T, S) {
comptime {
if (S != 3 and S != 4) {
@compileError("Rotation about an axis is only for 3x3 matrices and 4x4 matrices.");
}
}
var m: Matrix(T, S) = Matrix(T, S).identity();
const sinTheta = std.math.sin(angle);
const cosTheta = std.math.cos(angle);
m.data[0][0] = cosTheta;
m.data[2][0] = sinTheta;
m.data[0][2] = -sinTheta;
m.data[2][2] = cosTheta;
return m;
}
pub fn rotateZ(angle: T) Matrix(T, S) {
comptime {
if (S != 3 and S != 4) {
@compileError("Rotation about an axis is only for 3x3 matrices and 4x4 matrices.");
}
}
var m: Matrix(T, S) = Matrix(T, S).identity();
const sinTheta = std.math.sin(angle);
const cosTheta = std.math.cos(angle);
m.data[0][0] = cosTheta;
m.data[1][0] = -sinTheta;
m.data[0][1] = sinTheta;
m.data[1][1] = cosTheta;
return m;
}
pub fn transpose(self: Matrix(T, S)) Matrix(T, S) {
var new: Matrix(T, S) = undefined;
var i: u32 = 0;
while (i < S) : (i += 1) {
var j: u32 = 0;
while (j < S) : (j += 1) {
new.data[j][i] = self.data[i][j];
}
}
return new;
}
fn determinant_3x3(a: T, b: T, c: T, d: T, e: T, f: T, g: T, h: T, i: T) T {
return a * e * i + b * f * g + c * d * h - c * e * g - b * d * i - a * f * h;
}
pub fn determinant(self: Matrix(T, S)) T {
if (S == 2) {
return self.data[0][0] * self.data[1][1] - self.data[1][0] * self.data[0][1];
} else if (S == 3) {
const a = self.data[0][0];
const b = self.data[1][0];
const c = self.data[2][0];
const d = self.data[0][1];
const e = self.data[1][1];
const f = self.data[2][1];
const g = self.data[0][2];
const h = self.data[1][2];
const i = self.data[2][2];
return determinant_3x3(a, b, c, d, e, f, g, h, i);
} else if (S == 4) {
const a = self.data[0][0];
const b = self.data[1][0];
const c = self.data[2][0];
const d = self.data[3][0];
const e = self.data[0][1];
const f = self.data[1][1];
const g = self.data[2][1];
const h = self.data[3][1];
const i = self.data[0][2];
const j = self.data[1][2];
const k = self.data[2][2];
const l = self.data[3][2];
const m = self.data[0][3];
const n = self.data[1][3];
const o = self.data[2][3];
const p = self.data[3][3];
// return a * determinant_3x3(f, g, h, j, k, l, n, o, p) - b * determinant_3x3(e, g, h, i, k, l, m, o, p) + c * determinant_3x3(e, f, h, i, j, l, m, n, p) - d * determinant_3x3(e, f, g, i, j, k, m, n, o);
// return a * (f * k * p + g * l * n + h * j * o - h * k * n - g * j * p - f * l * o) - b * (e * k * p + g * l * m + h * i * o - h * k * m - g * i * p - e * l * o) + c * (e * j * p + f * l * m + h * i * n - h * j * m - f * i * p - e * l * n) - d * (e * j * o + f * k * m + g * i * n - g * j * m - f * i * o - e * k * n);
const ej_ = e * j;
const ek_ = e * k;
const el_ = e * l;
const fi_ = f * i;
const fk_ = f * k;
const fl_ = f * l;
const gi_ = g * i;
const gj_ = g * j;
const gl_ = g * l;
const hi_ = h * i;
const hj_ = h * j;
const hk_ = h * k;
return a * (fk_ * p + gl_ * n + hj_ * o - hk_ * n - gj_ * p - fl_ * o) - b * (ek_ * p + gl_ * m + hi_ * o - hk_ * m - gi_ * p - el_ * o) + c * (ej_ * p + fl_ * m + hi_ * n - hj_ * m - fi_ * p - el_ * n) - d * (ej_ * o + fk_ * m + gi_ * n - gj_ * m - fi_ * o - ek_ * n);
} else {
var i: u32 = 0;
var sign: T = 1;
var sum: T = 0;
while (i < S) : (i += 1) {
sum += sign * self.data[i][0] * self.subMatDet(i, 0);
sign *= -1;
}
return sum;
}
}
fn subMatDet(self: Matrix(T, S), i_skip: u32, j_skip: u32) T {
var m: Matrix(T, S - 1) = undefined;
var i: u32 = 0;
while (i < S) : (i += 1) {
var j: u32 = 0;
while (j < S) : (j += 1) {
if (i != i_skip and j != j_skip) {
var i_: u32 = i;
var j_: u32 = j;
if (i_ > i_skip) {
i_ -= 1;
}
if (j_ > j_skip) {
j_ -= 1;
}
m.data[i_][j_] = self.data[i][j];
}
}
}
return m.determinant();
}
pub fn inverse(self: Matrix(T, S)) !Matrix(T, S) {
if (S == 2) {
const det = self.determinant();
if (det == 0) {
return error.NoInverse;
}
const detRecip = 1.0 / det;
const a = self.data[0][0];
const b = self.data[1][0];
const c = self.data[0][1];
const d = self.data[1][1];
return Matrix(T, 2).init([2][2]T{
[2]f32{ detRecip * d, detRecip * -b },
[2]f32{ detRecip * -c, detRecip * a },
});
} else if (S == 3) {
const det = self.determinant();
if (det == 0) {
return error.NoInverse;
}
const detRecip = 1.0 / det;
const a = self.data[0][0];
const b = self.data[1][0];
const c = self.data[2][0];
const d = self.data[0][1];
const e = self.data[1][1];
const f = self.data[2][1];
const g = self.data[0][2];
const h = self.data[1][2];
const i = self.data[2][2];
const A_ = e * i - f * h;
const B_ = -(d * i - f * g);
const C_ = d * h - e * g;
const D_ = -(b * i - c * h);
const E_ = a * i - c * g;
const F_ = -(a * h - b * g);
const G_ = b * f - c * e;
const H_ = -(a * f - c * d);
const I_ = a * e - b * d;
return Matrix(f32, 3).init([3][3]f32{
[3]f32{ detRecip * A_, detRecip * D_, detRecip * G_ },
[3]f32{ detRecip * B_, detRecip * E_, detRecip * H_ },
[3]f32{ detRecip * C_, detRecip * F_, detRecip * I_ },
});
} else {
const det = self.determinant();
if (det == 0) {
return error.NoInverse;
}
const detRecip = 1.0 / det;
var result: Matrix(T, S) = undefined;
var i: u32 = 0;
var sign: T = 1;
while (i < S) : (i += 1) {
var j: u32 = 0;
while (j < S) : (j += 1) {
var co: T = self.subMatDet(i, j);
result.data[j][i] = sign * detRecip * co;
sign *= -1;
}
sign *= -1;
}
return result;
}
}
pub fn increaseDimension(self: Matrix(T, S)) Matrix(T, S + 1) {
var m: Matrix(T, S + 1) = undefined;
var i: u32 = 0;
while (i < S) : (i += 1) {
var j: u32 = 0;
while (j < S) : (j += 1) {
m.data[i][j] = self.data[i][j];
}
m.data[i][S] = 0;
}
var j: u32 = 0;
while (j < S) : (j += 1) {
m.data[S][j] = self.data[i][j];
}
m.data[S][S] = 1;
return m;
}
pub fn decreaseDimension(self: Matrix(T, S)) Matrix(T, S - 1) {
var m: Matrix(T, S - 1) = undefined;
var i: u32 = 0;
while (i < S - 1) : (i += 1) {
var j: u32 = 0;
while (j < S - 1) : (j += 1) {
m.data[i][j] = self.data[i][j];
}
}
return m;
}
pub fn dbg_print(self: Matrix(T, S)) void {
var i: u32 = 0;
while (i < S) : (i += 1) {
var j: u32 = 0;
while (j < S) : (j += 1) {
warn("{} ", .{self.data[j][i]});
}
warn("\n", .{});
}
}
// aspect_ratio = window_width / window_height
// fov is in radians
// Uses OpenGL coordinate system
pub fn perspectiveProjectionOpenGL(aspect_ratio: T, fovy: T, near_plane: T, far_plane: T) Matrix(T, 4) {
var m: Matrix(T, 4) = Matrix(T, 4).identity();
// Code borrowed from GLM
const tanHalfFovy = std.math.tan(fovy / 2.0);
m.data[0][0] = 1.0 / (aspect_ratio * tanHalfFovy);
m.data[1][1] = 1.0 / tanHalfFovy;
m.data[2][2] = -(far_plane + near_plane) / (far_plane - near_plane);
m.data[2][3] = -1.0;
m.data[3][2] = -(2.0 * far_plane * near_plane) / (far_plane - near_plane);
return m;
}
// OpenGL coordinate system but Z is in the range [0,1] instead of the default [-1,1]
pub fn perspectiveProjectionOpenGLInverseZ(aspect_ratio: T, fovy: T, near_plane: T, far_plane: T) Matrix(T, 4) {
var m: Matrix(T, 4) = perspectiveProjectionOpenGL(aspect_ratio, fovy, near_plane, far_plane);
m = m.mul(Matrix(f32, 4).scale(Vector(f32, 4).init([4]f32{ 1.0, 1.0, -0.5, 1.0 })));
m = m.mul(Matrix(f32, 4).translate(Vector(f32, 3).init([3]f32{ 0.0, 0.0, 0.5 })));
return m;
}
pub fn orthoProjectionOpenGL(left: f32, right: f32, bottom: f32, top: f32, near: f32, far: f32) Matrix(T, 4) {
var m: Matrix(T, 4) = Matrix(T, 4).identity();
// Code borrowed from GLM
m.data[0][0] = 2.0 / (right - left);
m.data[1][1] = 2.0 / (top - bottom);
m.data[2][2] = -2.0 / (far - near);
m.data[3][0] = -(right + left) / (right - left);
m.data[3][1] = -(top + bottom) / (top - bottom);
m.data[3][2] = -(far + near) / (far - near);
return m;
}
pub fn orthoProjectionOpenGLInverseZ(left: f32, right: f32, bottom: f32, top: f32, near: f32, far: f32) Matrix(T, 4) {
var m: Matrix(T, 4) = Matrix(T, 4).identity();
// Same as above code but z = -z*0.5 + 0.5 and near/far are swapped
m.data[0][0] = 2.0 / (right - left);
m.data[1][1] = 2.0 / (top - bottom);
m.data[2][2] = -1.0 / (near - far);
m.data[3][0] = -(right + left) / (right - left);
m.data[3][1] = -(top + bottom) / (top - bottom);
m.data[3][2] = (-0.5 * (far + near)) / (near - far) + 0.5;
return m;
}
pub fn position3D(self: Matrix(T, S)) Vector(T, 3) {
if (S == 3) {
return Vector(T, 3).init([3]f32{ self.data[2][0], self.data[2][1], self.data[2][2] });
} else if (S == 4) {
return Vector(T, 3).init([3]f32{ self.data[3][0], self.data[3][1], self.data[3][2] });
} else {
@compileError("Matrix.position3D is only for 3x3 and 4x4 matrices.");
}
}
pub fn position2D(self: Matrix(T, S)) Vector(T, S) {
if (S == 2) {
return Vector(T, 2).init([2]f32{ 0.0, 0.0 }).mulMat(self);
} else if (S == 3) {
return Vector(T, 3).init([3]f32{ 0.0, 0.0, 1.0 }).mulMat(self);
} else {
@compileError("Matrix.position2D is only for 2x2 and 3x3 matrices.");
}
}
pub fn equalTo(self: Matrix(T, S), b: Matrix(T, S)) bool {
var i: u32 = 0;
while (i < S) : (i += 1) {
var j: u32 = 0;
while (j < S) : (j += 1) {
if (self.data[i][j] != b.data[i][j]) {
return false;
}
}
}
return true;
}
};
}
test "Multiply matrix by identity" {
var m: Matrix(f32, 2) = Matrix(f32, 2).identity();
std.testing.expectEqual(m.data[0][0], 1.0);
std.testing.expectEqual(m.data[1][1], 1.0);
var m2: Matrix(f32, 2) = Matrix(f32, 2).init([2][2]f32{
[2]f32{ 1, 2 },
[2]f32{ 5, 6 },
});
var m3: Matrix(f32, 2) = m2.mul(m);
std.testing.expect(std.math.approxEq(f32, m3.data[0][0], 1.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, m3.data[0][1], 5.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, m3.data[1][0], 2.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, m3.data[1][1], 6.0, 0.00001));
}
test "Multiply vec2 by mat2" {
var m: Matrix(f32, 2) = Matrix(f32, 2).identity();
var v1: Vector(f32, 2) = Vector(f32, 2).init([2]f32{ 1.0, 2.0 });
var v2: Vector(f32, 2) = v1.mulMat(m);
std.testing.expect(std.math.approxEq(f32, v2.data[0], 1.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, v2.data[1], 2.0, 0.00001));
}
test "Multiply vec4 by mat4" {
var m: Matrix(f32, 4) = Matrix(f32, 4).identity();
m.data[3][0] = 1.0;
m.data[3][1] = 2.0;
m.data[3][2] = 3.0;
var v1: Vector(f32, 4) = Vector(f32, 4).init([4]f32{ 0.0, 0.0, 0.0, 1.0 });
var v2: Vector(f32, 4) = v1.mulMat(m);
std.testing.expect(std.math.approxEq(f32, v2.data[0], 1.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, v2.data[1], 2.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, v2.data[2], 3.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, v2.data[3], 1.0, 0.00001));
}
test "Translate vec2 by mat3" {
var m: Matrix(f32, 3) = Matrix(f32, 3).identity();
var v1: Vector(f32, 2) = Vector(f32, 2).init([2]f32{ 1.0, 2.0 });
m = m.mul(Matrix(f32, 3).translate(v1));
var v2: Vector(f32, 3) = Vector(f32, 3).init([3]f32{ 0.0, 0.0, 1.0 });
v2 = v2.mulMat(m);
std.testing.expect(std.math.approxEq(f32, v2.data[0], 1.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, v2.data[1], 2.0, 0.00001));
}
test "Rotate vec4 about x axis" {
// Rotate 45 degrees
var m: Matrix(f32, 4) = Matrix(f32, 4).identity().mul(Matrix(f32, 4).rotateX(0.7853981625));
var v1: Vector(f32, 4) = Vector(f32, 4).init([4]f32{ 0.0, 1.0, 0.0, 1.0 });
v1 = v1.mulMat(m);
std.testing.expect(std.math.approxEq(f32, v1.data[0], 0.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, v1.data[1], 0.7071067811865475, 0.00001));
std.testing.expect(std.math.approxEq(f32, v1.data[2], -0.7071067811865475, 0.00001));
std.testing.expect(std.math.approxEq(f32, v1.data[3], 1.0, 0.00001));
}
test "Rotate vec3 about y axis" {
// Rotate 45 degrees
var m: Matrix(f32, 3) = Matrix(f32, 3).identity().mul(Matrix(f32, 3).rotateY(0.7853981625));
var v1: Vector(f32, 3) = Vector(f32, 3).init([3]f32{ 1.0, 0.0, 0.0 });
v1 = v1.mulMat(m);
std.testing.expect(std.math.approxEq(f32, v1.data[0], 0.7071067811865475, 0.00001));
std.testing.expect(std.math.approxEq(f32, v1.data[1], 0.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, v1.data[2], -0.7071067811865475, 0.00001));
}
test "Rotate vec3 about z axis" {
// Rotate 45 degrees
var m: Matrix(f32, 3) = Matrix(f32, 3).identity().mul(Matrix(f32, 3).rotateZ(0.7853981625));
var v1: Vector(f32, 3) = Vector(f32, 3).init([3]f32{ 1.0, 0.0, 0.0 });
v1 = v1.mulMat(m);
std.testing.expect(std.math.approxEq(f32, v1.data[0], 0.7071067811865475, 0.00001));
std.testing.expect(std.math.approxEq(f32, v1.data[1], 0.7071067811865475, 0.00001));
std.testing.expect(std.math.approxEq(f32, v1.data[2], 0.0, 0.00001));
}
test "Transformation matrix" {
var m: Matrix(f32, 4) = Matrix(f32, 4).identity();
m = m.mul(Matrix(f32, 4).scale(Vector(f32, 4).init([4]f32{ 2.0, 2.0, 2.0, 1.0 })));
m = m.mul(Matrix(f32, 4).rotateY(0.7853981625));
m = m.mul(Matrix(f32, 4).translate(Vector(f32, 3).init([3]f32{ 0.0, 5.0, 0.0 })));
var v1: Vector(f32, 4) = Vector(f32, 4).init([4]f32{ 0.0, 0.0, 0.0, 1.0 });
v1 = v1.mulMat(m);
std.testing.expect(std.math.approxEq(f32, v1.data[0], 0.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, v1.data[1], 5.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, v1.data[2], 0.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, v1.data[3], 1.0, 0.00001));
var v2: Vector(f32, 4) = Vector(f32, 4).init([4]f32{ 1.0, 0.0, 0.0, 1.0 });
v2 = v2.mulMat(m);
std.testing.expect(std.math.approxEq(f32, v2.data[0], 1.414213562373095, 0.00001));
std.testing.expect(std.math.approxEq(f32, v2.data[1], 5.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, v2.data[2], -1.414213562373095, 0.00001));
std.testing.expect(std.math.approxEq(f32, v2.data[3], 1.0, 0.00001));
}
test "Determinant" {
var m: Matrix(f32, 2) = Matrix(f32, 2).init([2][2]f32{
[2]f32{ 1, 2 },
[2]f32{ 3, 4 },
});
std.testing.expect(std.math.approxEq(f32, m.determinant(), -2.0, 0.00001));
var m2: Matrix(f32, 3) = Matrix(f32, 3).init([3][3]f32{
[3]f32{ 2, 8, 5 },
[3]f32{ 8, 6, 4 },
[3]f32{ 5, 3, 6 },
});
std.testing.expect(std.math.approxEq(f32, m2.determinant(), -206.0, 0.00001));
var m3: Matrix(f32, 4) = Matrix(f32, 4).init([4][4]f32{
[4]f32{ 9, 5, 9, 7 },
[4]f32{ 9, 8, 3, 6 },
[4]f32{ 4, 8, 5, 2 },
[4]f32{ 4, 3, 8, 8 },
});
std.testing.expect(std.math.approxEq(f32, m3.determinant(), 1623.0, 0.00001));
var m4: Matrix(f32, 5) = Matrix(f32, 5).init([5][5]f32{
[5]f32{ 0, 6, -2, -1, 5 },
[5]f32{ 0, 0, 0, -9, -7 },
[5]f32{ 0, 0, 15, 35, 0 },
[5]f32{ 0, 0, -1, -11, -2 },
[5]f32{ 1, -2, -2, 3, -2 },
});
std.testing.expect(std.math.approxEq(f32, m4.determinant(), 3840.0, 0.00001));
}
test "Inverse" {
var m: Matrix(f32, 2) = Matrix(f32, 2).init([2][2]f32{
[2]f32{ 1, 2 },
[2]f32{ 3, 4 },
});
const m_ = try m.inverse();
std.testing.expect(std.math.approxEq(f32, m_.data[0][0], -2.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, m_.data[0][1], 3.0 / 2.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, m_.data[1][0], 1.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, m_.data[1][1], -1.0 / 2.0, 0.00001));
const m__ = try m_.inverse();
std.testing.expect(m__.equalTo(m));
var m2: Matrix(f32, 3) = Matrix(f32, 3).init([3][3]f32{
[3]f32{ 2, 8, 5 },
[3]f32{ 8, 6, 4 },
[3]f32{ 5, 3, 6 },
});
const m2_ = try m2.inverse();
std.testing.expect(std.math.approxEq(f32, m2_.data[0][0], -12.0 / 103.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, m2_.data[0][1], 14.0 / 103.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, m2_.data[0][2], 3.0 / 103.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, m2_.data[1][0], 33.0 / 206.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, m2_.data[1][1], 13.0 / 206.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, m2_.data[1][2], -17.0 / 103.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, m2_.data[2][0], -1.0 / 103.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, m2_.data[2][1], -16.0 / 103.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, m2_.data[2][2], 26.0 / 103.0, 0.00001));
var m3: Matrix(f32, 4) = Matrix(f32, 4).init([4][4]f32{
[4]f32{ 1, 2, 1, 1 },
[4]f32{ 2, 2, 1, 1 },
[4]f32{ 1, 2, 2, 1 },
[4]f32{ 1, 1, 1, 2 },
});
const m3_ = try m3.inverse();
std.testing.expect(std.math.approxEq(f32, m3_.data[0][0], -1.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, m3_.data[0][1], 4.0 / 3.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, m3_.data[0][2], -1.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, m3_.data[0][3], 1.0 / 3.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, m3_.data[1][0], 1.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, m3_.data[1][1], -1.0 / 3.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, m3_.data[1][2], 0.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, m3_.data[1][3], -1.0 / 3.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, m3_.data[2][0], 0.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, m3_.data[2][1], -1.0 / 3.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, m3_.data[2][2], 1.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, m3_.data[2][3], -1.0 / 3.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, m3_.data[3][0], 0.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, m3_.data[3][1], -1.0 / 3.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, m3_.data[3][2], 0.0, 0.00001));
std.testing.expect(std.math.approxEq(f32, m3_.data[3][3], 2.0 / 3.0, 0.00001));
var m4: Matrix(f32, 4) = Matrix(f32, 4).translate(Vector(f32, 3).init([3]f32{ 1.5, 0, 0 }));
std.testing.expect(std.math.approxEq(f32, m4.data[3][0], 1.5, 0.00001));
const m4_ = try m4.inverse();
std.testing.expect(std.math.approxEq(f32, m4_.data[3][0], -1.5, 0.00001));
} | src/Mathematics/Matrix.zig |
const std = @import("std");
const sqlite = @import("sqlite");
const Search = @import("Search.zig");
const Printable = @import("Printable.zig");
const utils = @import("utils.zig");
const db_file_name = "codes.db";
var database: sqlite.SQLite = undefined;
pub fn checkDbExists() !bool {
//Checks if program has access to the db file/if it exists
if (std.fs.cwd().access(db_file_name, .{ .read = true, .write = true })) {
return true;
} else |err| return if (err == error.FileNotFound) false else err;
}
pub fn openDb() !void {
database = try sqlite.SQLite.open(db_file_name);
}
pub fn closeDb() void {
database.close() catch unreachable;
}
pub fn createTable() !void {
var ans = database.exec(
\\ CREATE TABLE chars (
\\ id INTEGER PRIMARY KEY AUTOINCREMENT,
\\ name TEXT NOT NULL,
\\ utf8 BLOB NOT NULL,
\\ user_notes TEXT,
\\ standard_notes TEXT,
\\ times_used INTEGER DEFAULT 0
\\ );
);
while (ans.next()) |row_item| {
switch (row_item) {
.Error => |e| {
std.debug.warn("sqlite3 errmsg: {s}\n", .{database.errmsg()});
return e;
},
else => continue,
}
}
}
pub fn parseFileAndFillDb(file: std.fs.File) !void {
var reader = file.reader();
var buffer: [1024]u8 = undefined;
const insert = (try database.prepare("INSERT INTO chars(utf8, name) VALUES (?, ?);", null)).?;
//Read all lines
while (try reader.readUntilDelimiterOrEof(buffer[0..], '\n')) |line| {
if (line.len == 0 or line[0] == '@' or line[0] == '#')
continue;
var data = line;
var name = line;
_ = blk: {
for (line) |c, i| {
if (c == '#') {
if (i + 2 >= line.len)
return error.IllFormedCodeFile;
data = line[0..i];
name = line[(i + 2)..];
break :blk;
}
}
return error.IllFormedCodeFile;
};
var utf8: [16]u8 = undefined;
var codepoint_iterator = std.mem.tokenize(u8, data, " ");
var i: usize = 0;
while (codepoint_iterator.next()) |code| {
if (std.mem.eql(u8, ";", code))
break;
i += try std.unicode.utf8Encode(try std.fmt.parseInt(u21, code, 16), utf8[i..]);
}
if (i == 0)
return error.IllFormedCodeFile;
try insert.bindBlob(1, utf8[0..i]);
try insert.bindText(2, name);
_ = try insert.step();
try insert.reset();
}
try insert.finalize();
}
var query: ?[:0]const u8 = null;
var page: usize = 0;
var user_query: ?[]const u8 = null;
var result_ids: [8]c_int = undefined;
var result_count: usize = 0;
pub fn setSearch(allocator: *std.mem.Allocator, words: []u8) !void {
deallocSearch(allocator);
page = 0;
user_query = try allocator.dupe(u8, words);
errdefer deallocSearch(allocator);
}
fn prepareQuery(allocator: *std.mem.Allocator) !void {
if (user_query == null)
return error.noSearch;
deallocQuery(allocator);
const search = Search{ .user_query = user_query.?, .page = page, .request_type = .Characters };
query = try std.fmt.allocPrintZ(allocator, "{.8}", .{search});
if (Search.has_error)
return error.UnsafeQuery;
}
pub fn deallocQuery(allocator: *std.mem.Allocator) void {
if (query) |s|
allocator.free(s);
query = null;
}
pub fn deallocSearch(allocator: *std.mem.Allocator) void {
if (user_query) |s|
allocator.free(s);
user_query = null;
}
pub fn runQuery(allocator: *std.mem.Allocator) !void {
const stdout = std.io.getStdOut().writer();
try prepareQuery(allocator);
var page_count: i32 = 0;
if (page == 0) {
const search = Search{ .user_query = user_query.?, .page = 0, .request_type = .Count };
std.debug.assert(!Search.has_error);
const count_query = try std.fmt.allocPrintZ(allocator, "{.0}", .{search});
defer allocator.free(count_query);
var rows = database.exec(count_query);
while (rows.next()) |row_item| {
const row = switch (row_item) {
// Ignore when statements are completed
.Done => continue,
.Row => |r| r,
.Error => |e| {
std.debug.warn("sqlite3 errmsg: {s}\n", .{database.errmsg()});
return e;
},
};
const count = row.columnInt(0);
page_count = @divFloor(count, 8) + 1;
if (count == 0) {
try stdout.print(" - Query prepared, got no results 😕 -\n", .{});
} else try stdout.print(" - Query prepared 🔍, got {} result(s)! ({} page(s) 📃) -\n", .{ count, page_count });
}
}
var rows = database.exec(query.?);
var selector: usize = 0;
while (rows.next()) |row_item| {
const row = switch (row_item) {
// Ignore when statements are completed
.Done => continue,
.Row => |r| r,
.Error => |e| {
std.debug.warn("sqlite3 errmsg: {s}\n", .{database.errmsg()});
return e;
},
};
const utf8 = row.columnBlob(0);
const name = row.columnText(1);
const used = row.columnInt(2);
const id = row.columnInt(3);
if (selector == 0)
try stdout.print(" (Page {})\n", .{page + 1});
const printable = Printable{ .utf8 = utf8, .id = id };
const circled_digit = utils.circledDigit(@truncate(u3, selector));
if (used != 0) {
try stdout.print(" {s}- {} : {s} (used {} times)\n", .{ circled_digit, printable, name, used });
} else {
try stdout.print(" {s}- {} : {s} (never used)\n", .{ circled_digit, printable, name });
}
std.debug.assert(selector < 8);
result_ids[selector] = id;
selector += 1;
}
result_count = selector;
if (selector == 0) {
if (page != 0) {
std.debug.warn("No more results!\n", .{});
page = 0;
} else std.debug.warn("Nothing found.\n", .{});
} else {
page += 1;
try stdout.writeAll("Type number to copy symbol");
if (page == 1 and page_count > 1)
try stdout.writeAll(", enter to go to next page");
try stdout.writeAll(".\n");
}
}
pub fn select(allocator: *std.mem.Allocator, index: u3) !void {
const stderr = std.io.getStdErr().writer();
const stdout = std.io.getStdOut().writer();
if (index < result_count) {
const id = result_ids[index];
var found = false;
var ans = try database.execBind("UPDATE chars SET times_used = times_used + 1 WHERE id == ?;", .{id});
while (ans.next()) |t| {
_ = switch (t) {
.Error => |e| {
std.debug.warn("sqlite3 errmsg: {s}\n", .{database.errmsg()});
return e;
},
else => continue,
};
}
var utf8: []const u8 = undefined;
ans = try database.execBind("SELECT utf8 FROM chars WHERE id == ?;", .{id});
while (ans.next()) |t| {
const row = switch (t) {
.Error => |e| {
std.debug.warn("sqlite3 errmsg: {s}\n", .{database.errmsg()});
return e;
},
.Row => |r| r,
.Done => continue,
};
std.debug.assert(!found);
found = true;
utf8 = try allocator.dupe(u8, row.columnText(0));
}
if (@import("clipboard.zig").putInClipboard(allocator, utf8)) {
const printable = Printable{ .utf8 = utf8, .id = id };
try stdout.print("'{s}' copied to clipboard!\n", .{printable});
} else |err| {
if (err == error.ClipboardNotAvailable) {
try stderr.writeAll("Clipboard copy not available on this platform :/\n");
} else return err;
}
allocator.free(utf8);
} else return error.doesNotExist;
}
pub const testing = struct { //Namespace for testing functions
pub fn printAll() !void {
var rows = database.exec("SELECT utf8, name, id FROM chars;");
while (rows.next()) |row_item| {
const row = switch (row_item) {
// Ignore when statements are completed
.Done => continue,
.Row => |r| r,
.Error => |e| {
std.debug.warn("sqlite3 errmsg: {s}\n", .{database.errmsg()});
return e;
},
};
const utf8 = row.columnBlob(0);
const name = row.columnText(1);
const id = row.columnInt(2);
const printable = Printable{ .utf8 = utf8, .id = id };
std.debug.warn("{s}: {s} ({}) id: {}\n", .{ name, printable, std.fmt.fmtSliceHexUpper(utf8), id });
}
}
}; | src/db.zig |
const std = @import("std");
const Builder = std.build.Builder;
fn root() []const u8 {
return std.fs.path.dirname(@src().file) orelse ".";
}
fn pathJoinRoot(comptime components: []const []const u8) []const u8 {
var ret = root();
inline for (components) |component|
ret = ret ++ std.fs.path.sep_str ++ component;
return ret;
}
const srcs = blk: {
@setEvalBranchQuota(4000);
var ret = &.{
pathJoinRoot(&.{ "c", "library", "certs.c" }),
pathJoinRoot(&.{ "c", "library", "pkcs11.c" }),
pathJoinRoot(&.{ "c", "library", "x509.c" }),
pathJoinRoot(&.{ "c", "library", "x509_create.c" }),
pathJoinRoot(&.{ "c", "library", "x509_crl.c" }),
pathJoinRoot(&.{ "c", "library", "x509_crt.c" }),
pathJoinRoot(&.{ "c", "library", "x509_csr.c" }),
pathJoinRoot(&.{ "c", "library", "x509write_crt.c" }),
pathJoinRoot(&.{ "c", "library", "x509write_csr.c" }),
pathJoinRoot(&.{ "c", "library", "debug.c" }),
pathJoinRoot(&.{ "c", "library", "net_sockets.c" }),
pathJoinRoot(&.{ "c", "library", "ssl_cache.c" }),
pathJoinRoot(&.{ "c", "library", "ssl_ciphersuites.c" }),
pathJoinRoot(&.{ "c", "library", "ssl_cli.c" }),
pathJoinRoot(&.{ "c", "library", "ssl_cookie.c" }),
pathJoinRoot(&.{ "c", "library", "ssl_msg.c" }),
pathJoinRoot(&.{ "c", "library", "ssl_srv.c" }),
pathJoinRoot(&.{ "c", "library", "ssl_ticket.c" }),
pathJoinRoot(&.{ "c", "library", "ssl_tls13_keys.c" }),
pathJoinRoot(&.{ "c", "library", "ssl_tls.c" }),
pathJoinRoot(&.{ "c", "library", "aes.c" }),
pathJoinRoot(&.{ "c", "library", "aesni.c" }),
pathJoinRoot(&.{ "c", "library", "arc4.c" }),
pathJoinRoot(&.{ "c", "library", "aria.c" }),
pathJoinRoot(&.{ "c", "library", "asn1parse.c" }),
pathJoinRoot(&.{ "c", "library", "asn1write.c" }),
pathJoinRoot(&.{ "c", "library", "base64.c" }),
pathJoinRoot(&.{ "c", "library", "bignum.c" }),
pathJoinRoot(&.{ "c", "library", "blowfish.c" }),
pathJoinRoot(&.{ "c", "library", "camellia.c" }),
pathJoinRoot(&.{ "c", "library", "ccm.c" }),
pathJoinRoot(&.{ "c", "library", "chacha20.c" }),
pathJoinRoot(&.{ "c", "library", "chachapoly.c" }),
pathJoinRoot(&.{ "c", "library", "cipher.c" }),
pathJoinRoot(&.{ "c", "library", "cipher_wrap.c" }),
pathJoinRoot(&.{ "c", "library", "cmac.c" }),
pathJoinRoot(&.{ "c", "library", "ctr_drbg.c" }),
pathJoinRoot(&.{ "c", "library", "des.c" }),
pathJoinRoot(&.{ "c", "library", "dhm.c" }),
pathJoinRoot(&.{ "c", "library", "ecdh.c" }),
pathJoinRoot(&.{ "c", "library", "ecdsa.c" }),
pathJoinRoot(&.{ "c", "library", "ecjpake.c" }),
pathJoinRoot(&.{ "c", "library", "ecp.c" }),
pathJoinRoot(&.{ "c", "library", "ecp_curves.c" }),
pathJoinRoot(&.{ "c", "library", "entropy.c" }),
pathJoinRoot(&.{ "c", "library", "entropy_poll.c" }),
pathJoinRoot(&.{ "c", "library", "error.c" }),
pathJoinRoot(&.{ "c", "library", "gcm.c" }),
pathJoinRoot(&.{ "c", "library", "havege.c" }),
pathJoinRoot(&.{ "c", "library", "hkdf.c" }),
pathJoinRoot(&.{ "c", "library", "hmac_drbg.c" }),
pathJoinRoot(&.{ "c", "library", "md2.c" }),
pathJoinRoot(&.{ "c", "library", "md4.c" }),
pathJoinRoot(&.{ "c", "library", "md5.c" }),
pathJoinRoot(&.{ "c", "library", "md.c" }),
pathJoinRoot(&.{ "c", "library", "memory_buffer_alloc.c" }),
pathJoinRoot(&.{ "c", "library", "mps_reader.c" }),
pathJoinRoot(&.{ "c", "library", "mps_trace.c" }),
pathJoinRoot(&.{ "c", "library", "nist_kw.c" }),
pathJoinRoot(&.{ "c", "library", "oid.c" }),
pathJoinRoot(&.{ "c", "library", "padlock.c" }),
pathJoinRoot(&.{ "c", "library", "pem.c" }),
pathJoinRoot(&.{ "c", "library", "pk.c" }),
pathJoinRoot(&.{ "c", "library", "pkcs12.c" }),
pathJoinRoot(&.{ "c", "library", "pkcs5.c" }),
pathJoinRoot(&.{ "c", "library", "pkparse.c" }),
pathJoinRoot(&.{ "c", "library", "pk_wrap.c" }),
pathJoinRoot(&.{ "c", "library", "pkwrite.c" }),
pathJoinRoot(&.{ "c", "library", "platform.c" }),
pathJoinRoot(&.{ "c", "library", "platform_util.c" }),
pathJoinRoot(&.{ "c", "library", "poly1305.c" }),
pathJoinRoot(&.{ "c", "library", "psa_crypto_aead.c" }),
pathJoinRoot(&.{ "c", "library", "psa_crypto.c" }),
pathJoinRoot(&.{ "c", "library", "psa_crypto_cipher.c" }),
pathJoinRoot(&.{ "c", "library", "psa_crypto_client.c" }),
pathJoinRoot(&.{ "c", "library", "psa_crypto_driver_wrappers.c" }),
pathJoinRoot(&.{ "c", "library", "psa_crypto_ecp.c" }),
pathJoinRoot(&.{ "c", "library", "psa_crypto_hash.c" }),
pathJoinRoot(&.{ "c", "library", "psa_crypto_mac.c" }),
pathJoinRoot(&.{ "c", "library", "psa_crypto_rsa.c" }),
pathJoinRoot(&.{ "c", "library", "psa_crypto_se.c" }),
pathJoinRoot(&.{ "c", "library", "psa_crypto_slot_management.c" }),
pathJoinRoot(&.{ "c", "library", "psa_crypto_storage.c" }),
pathJoinRoot(&.{ "c", "library", "psa_its_file.c" }),
pathJoinRoot(&.{ "c", "library", "ripemd160.c" }),
pathJoinRoot(&.{ "c", "library", "rsa.c" }),
pathJoinRoot(&.{ "c", "library", "rsa_internal.c" }),
pathJoinRoot(&.{ "c", "library", "sha1.c" }),
pathJoinRoot(&.{ "c", "library", "sha256.c" }),
pathJoinRoot(&.{ "c", "library", "sha512.c" }),
pathJoinRoot(&.{ "c", "library", "threading.c" }),
pathJoinRoot(&.{ "c", "library", "timing.c" }),
pathJoinRoot(&.{ "c", "library", "version.c" }),
pathJoinRoot(&.{ "c", "library", "version_features.c" }),
pathJoinRoot(&.{ "c", "library", "xtea.c" }),
};
break :blk ret;
};
pub const include_dir = pathJoinRoot(&.{ "c", "include" });
const library_include = pathJoinRoot(&.{ "c", "library" });
pub fn link(artifact: *std.build.LibExeObjStep) void {
artifact.addIncludeDir(include_dir);
artifact.addIncludeDir(library_include);
artifact.addCSourceFiles(srcs, &.{"-Os"});
if (artifact.target.isWindows())
artifact.linkSystemLibrary("ws2_32");
artifact.linkLibC();
} | libs/mbedtls/mbedtls.zig |
const builtin = @import("builtin");
const std = @import("../std.zig");
const event = std.event;
const assert = std.debug.assert;
const testing = std.testing;
const os = std.os;
const mem = std.mem;
const windows = os.windows;
const Loop = event.Loop;
const fd_t = os.fd_t;
const File = std.fs.File;
pub const RequestNode = std.atomic.Queue(Request).Node;
pub const Request = struct {
msg: Msg,
finish: Finish,
pub const Finish = union(enum) {
TickNode: Loop.NextTickNode,
DeallocCloseOperation: *CloseOperation,
NoAction,
};
pub const Msg = union(enum) {
WriteV: WriteV,
PWriteV: PWriteV,
PReadV: PReadV,
Open: Open,
Close: Close,
WriteFile: WriteFile,
End, // special - means the fs thread should exit
pub const WriteV = struct {
fd: fd_t,
iov: []const os.iovec_const,
result: Error!void,
pub const Error = os.WriteError;
};
pub const PWriteV = struct {
fd: fd_t,
iov: []const os.iovec_const,
offset: usize,
result: Error!void,
pub const Error = os.WriteError;
};
pub const PReadV = struct {
fd: fd_t,
iov: []const os.iovec,
offset: usize,
result: Error!usize,
pub const Error = os.ReadError;
};
pub const Open = struct {
/// must be null terminated. TODO https://github.com/ziglang/zig/issues/265
path: []const u8,
flags: u32,
mode: File.Mode,
result: Error!fd_t,
pub const Error = File.OpenError;
};
pub const WriteFile = struct {
/// must be null terminated. TODO https://github.com/ziglang/zig/issues/265
path: []const u8,
contents: []const u8,
mode: File.Mode,
result: Error!void,
pub const Error = File.OpenError || File.WriteError;
};
pub const Close = struct {
fd: fd_t,
};
};
};
pub const PWriteVError = error{OutOfMemory} || File.WriteError;
/// data - just the inner references - must live until pwritev frame completes.
pub fn pwritev(loop: *Loop, fd: fd_t, data: []const []const u8, offset: usize) PWriteVError!void {
switch (builtin.os) {
.macosx,
.linux,
.freebsd,
.netbsd,
=> {
const iovecs = try loop.allocator.alloc(os.iovec_const, data.len);
defer loop.allocator.free(iovecs);
for (data) |buf, i| {
iovecs[i] = os.iovec_const{
.iov_base = buf.ptr,
.iov_len = buf.len,
};
}
return pwritevPosix(loop, fd, iovecs, offset);
},
.windows => {
const data_copy = try std.mem.dupe(loop.allocator, []const u8, data);
defer loop.allocator.free(data_copy);
return pwritevWindows(loop, fd, data, offset);
},
else => @compileError("Unsupported OS"),
}
}
/// data must outlive the returned frame
pub fn pwritevWindows(loop: *Loop, fd: fd_t, data: []const []const u8, offset: usize) os.WindowsWriteError!void {
if (data.len == 0) return;
if (data.len == 1) return pwriteWindows(loop, fd, data[0], offset);
// TODO do these in parallel
var off = offset;
for (data) |buf| {
try pwriteWindows(loop, fd, buf, off);
off += buf.len;
}
}
pub fn pwriteWindows(loop: *Loop, fd: fd_t, data: []const u8, offset: u64) os.WindowsWriteError!void {
var resume_node = Loop.ResumeNode.Basic{
.base = Loop.ResumeNode{
.id = Loop.ResumeNode.Id.Basic,
.handle = @frame(),
.overlapped = windows.OVERLAPPED{
.Internal = 0,
.InternalHigh = 0,
.Offset = @truncate(u32, offset),
.OffsetHigh = @truncate(u32, offset >> 32),
.hEvent = null,
},
},
};
// TODO only call create io completion port once per fd
_ = windows.CreateIoCompletionPort(fd, loop.os_data.io_port, undefined, undefined);
loop.beginOneEvent();
errdefer loop.finishOneEvent();
errdefer {
_ = windows.kernel32.CancelIoEx(fd, &resume_node.base.overlapped);
}
suspend {
_ = windows.kernel32.WriteFile(fd, data.ptr, @intCast(windows.DWORD, data.len), null, &resume_node.base.overlapped);
}
var bytes_transferred: windows.DWORD = undefined;
if (windows.kernel32.GetOverlappedResult(fd, &resume_node.base.overlapped, &bytes_transferred, windows.FALSE) == 0) {
switch (windows.kernel32.GetLastError()) {
windows.ERROR.IO_PENDING => unreachable,
windows.ERROR.INVALID_USER_BUFFER => return error.SystemResources,
windows.ERROR.NOT_ENOUGH_MEMORY => return error.SystemResources,
windows.ERROR.OPERATION_ABORTED => return error.OperationAborted,
windows.ERROR.NOT_ENOUGH_QUOTA => return error.SystemResources,
windows.ERROR.BROKEN_PIPE => return error.BrokenPipe,
else => |err| return windows.unexpectedError(err),
}
}
}
/// iovecs must live until pwritev frame completes.
pub fn pwritevPosix(
loop: *Loop,
fd: fd_t,
iovecs: []const os.iovec_const,
offset: usize,
) os.WriteError!void {
var req_node = RequestNode{
.prev = null,
.next = null,
.data = Request{
.msg = Request.Msg{
.PWriteV = Request.Msg.PWriteV{
.fd = fd,
.iov = iovecs,
.offset = offset,
.result = undefined,
},
},
.finish = Request.Finish{
.TickNode = Loop.NextTickNode{
.prev = null,
.next = null,
.data = @frame(),
},
},
},
};
errdefer loop.posixFsCancel(&req_node);
suspend {
loop.posixFsRequest(&req_node);
}
return req_node.data.msg.PWriteV.result;
}
/// iovecs must live until pwritev frame completes.
pub fn writevPosix(
loop: *Loop,
fd: fd_t,
iovecs: []const os.iovec_const,
) os.WriteError!void {
var req_node = RequestNode{
.prev = null,
.next = null,
.data = Request{
.msg = Request.Msg{
.WriteV = Request.Msg.WriteV{
.fd = fd,
.iov = iovecs,
.result = undefined,
},
},
.finish = Request.Finish{
.TickNode = Loop.NextTickNode{
.prev = null,
.next = null,
.data = @frame(),
},
},
},
};
suspend {
loop.posixFsRequest(&req_node);
}
return req_node.data.msg.WriteV.result;
}
pub const PReadVError = error{OutOfMemory} || File.ReadError;
/// data - just the inner references - must live until preadv frame completes.
pub fn preadv(loop: *Loop, fd: fd_t, data: []const []u8, offset: usize) PReadVError!usize {
assert(data.len != 0);
switch (builtin.os) {
.macosx,
.linux,
.freebsd,
.netbsd,
=> {
const iovecs = try loop.allocator.alloc(os.iovec, data.len);
defer loop.allocator.free(iovecs);
for (data) |buf, i| {
iovecs[i] = os.iovec{
.iov_base = buf.ptr,
.iov_len = buf.len,
};
}
return preadvPosix(loop, fd, iovecs, offset);
},
.windows => {
const data_copy = try std.mem.dupe(loop.allocator, []u8, data);
defer loop.allocator.free(data_copy);
return preadvWindows(loop, fd, data_copy, offset);
},
else => @compileError("Unsupported OS"),
}
}
/// data must outlive the returned frame
pub fn preadvWindows(loop: *Loop, fd: fd_t, data: []const []u8, offset: u64) !usize {
assert(data.len != 0);
if (data.len == 1) return preadWindows(loop, fd, data[0], offset);
// TODO do these in parallel?
var off: usize = 0;
var iov_i: usize = 0;
var inner_off: usize = 0;
while (true) {
const v = data[iov_i];
const amt_read = try preadWindows(loop, fd, v[inner_off .. v.len - inner_off], offset + off);
off += amt_read;
inner_off += amt_read;
if (inner_off == v.len) {
iov_i += 1;
inner_off = 0;
if (iov_i == data.len) {
return off;
}
}
if (amt_read == 0) return off; // EOF
}
}
pub fn preadWindows(loop: *Loop, fd: fd_t, data: []u8, offset: u64) !usize {
var resume_node = Loop.ResumeNode.Basic{
.base = Loop.ResumeNode{
.id = Loop.ResumeNode.Id.Basic,
.handle = @frame(),
.overlapped = windows.OVERLAPPED{
.Internal = 0,
.InternalHigh = 0,
.Offset = @truncate(u32, offset),
.OffsetHigh = @truncate(u32, offset >> 32),
.hEvent = null,
},
},
};
// TODO only call create io completion port once per fd
_ = windows.CreateIoCompletionPort(fd, loop.os_data.io_port, undefined, undefined) catch undefined;
loop.beginOneEvent();
errdefer loop.finishOneEvent();
errdefer {
_ = windows.kernel32.CancelIoEx(fd, &resume_node.base.overlapped);
}
suspend {
_ = windows.kernel32.ReadFile(fd, data.ptr, @intCast(windows.DWORD, data.len), null, &resume_node.base.overlapped);
}
var bytes_transferred: windows.DWORD = undefined;
if (windows.kernel32.GetOverlappedResult(fd, &resume_node.base.overlapped, &bytes_transferred, windows.FALSE) == 0) {
switch (windows.kernel32.GetLastError()) {
windows.ERROR.IO_PENDING => unreachable,
windows.ERROR.OPERATION_ABORTED => return error.OperationAborted,
windows.ERROR.BROKEN_PIPE => return error.BrokenPipe,
windows.ERROR.HANDLE_EOF => return usize(bytes_transferred),
else => |err| return windows.unexpectedError(err),
}
}
return usize(bytes_transferred);
}
/// iovecs must live until preadv frame completes
pub fn preadvPosix(
loop: *Loop,
fd: fd_t,
iovecs: []const os.iovec,
offset: usize,
) os.ReadError!usize {
var req_node = RequestNode{
.prev = null,
.next = null,
.data = Request{
.msg = Request.Msg{
.PReadV = Request.Msg.PReadV{
.fd = fd,
.iov = iovecs,
.offset = offset,
.result = undefined,
},
},
.finish = Request.Finish{
.TickNode = Loop.NextTickNode{
.prev = null,
.next = null,
.data = @frame(),
},
},
},
};
errdefer loop.posixFsCancel(&req_node);
suspend {
loop.posixFsRequest(&req_node);
}
return req_node.data.msg.PReadV.result;
}
pub fn openPosix(
loop: *Loop,
path: []const u8,
flags: u32,
mode: File.Mode,
) File.OpenError!fd_t {
const path_c = try std.os.toPosixPath(path);
var req_node = RequestNode{
.prev = null,
.next = null,
.data = Request{
.msg = Request.Msg{
.Open = Request.Msg.Open{
.path = path_c[0..path.len],
.flags = flags,
.mode = mode,
.result = undefined,
},
},
.finish = Request.Finish{
.TickNode = Loop.NextTickNode{
.prev = null,
.next = null,
.data = @frame(),
},
},
},
};
errdefer loop.posixFsCancel(&req_node);
suspend {
loop.posixFsRequest(&req_node);
}
return req_node.data.msg.Open.result;
}
pub fn openRead(loop: *Loop, path: []const u8) File.OpenError!fd_t {
switch (builtin.os) {
.macosx, .linux, .freebsd, .netbsd => {
const flags = os.O_LARGEFILE | os.O_RDONLY | os.O_CLOEXEC;
return openPosix(loop, path, flags, File.default_mode);
},
.windows => return windows.CreateFile(
path,
windows.GENERIC_READ,
windows.FILE_SHARE_READ,
null,
windows.OPEN_EXISTING,
windows.FILE_ATTRIBUTE_NORMAL | windows.FILE_FLAG_OVERLAPPED,
null,
),
else => @compileError("Unsupported OS"),
}
}
/// Creates if does not exist. Truncates the file if it exists.
/// Uses the default mode.
pub fn openWrite(loop: *Loop, path: []const u8) File.OpenError!fd_t {
return openWriteMode(loop, path, File.default_mode);
}
/// Creates if does not exist. Truncates the file if it exists.
pub fn openWriteMode(loop: *Loop, path: []const u8, mode: File.Mode) File.OpenError!fd_t {
switch (builtin.os) {
.macosx,
.linux,
.freebsd,
.netbsd,
=> {
const flags = os.O_LARGEFILE | os.O_WRONLY | os.O_CREAT | os.O_CLOEXEC | os.O_TRUNC;
return openPosix(loop, path, flags, File.default_mode);
},
.windows => return windows.CreateFile(
path,
windows.GENERIC_WRITE,
windows.FILE_SHARE_WRITE | windows.FILE_SHARE_READ | windows.FILE_SHARE_DELETE,
null,
windows.CREATE_ALWAYS,
windows.FILE_ATTRIBUTE_NORMAL | windows.FILE_FLAG_OVERLAPPED,
null,
),
else => @compileError("Unsupported OS"),
}
}
/// Creates if does not exist. Does not truncate.
pub fn openReadWrite(
loop: *Loop,
path: []const u8,
mode: File.Mode,
) File.OpenError!fd_t {
switch (builtin.os) {
.macosx, .linux, .freebsd, .netbsd => {
const flags = os.O_LARGEFILE | os.O_RDWR | os.O_CREAT | os.O_CLOEXEC;
return openPosix(loop, path, flags, mode);
},
.windows => return windows.CreateFile(
path,
windows.GENERIC_WRITE | windows.GENERIC_READ,
windows.FILE_SHARE_WRITE | windows.FILE_SHARE_READ | windows.FILE_SHARE_DELETE,
null,
windows.OPEN_ALWAYS,
windows.FILE_ATTRIBUTE_NORMAL | windows.FILE_FLAG_OVERLAPPED,
null,
),
else => @compileError("Unsupported OS"),
}
}
/// This abstraction helps to close file handles in defer expressions
/// without the possibility of failure and without the use of suspend points.
/// Start a `CloseOperation` before opening a file, so that you can defer
/// `CloseOperation.finish`.
/// If you call `setHandle` then finishing will close the fd; otherwise finishing
/// will deallocate the `CloseOperation`.
pub const CloseOperation = struct {
loop: *Loop,
os_data: OsData,
const OsData = switch (builtin.os) {
.linux, .macosx, .freebsd, .netbsd => OsDataPosix,
.windows => struct {
handle: ?fd_t,
},
else => @compileError("Unsupported OS"),
};
const OsDataPosix = struct {
have_fd: bool,
close_req_node: RequestNode,
};
pub fn start(loop: *Loop) (error{OutOfMemory}!*CloseOperation) {
const self = try loop.allocator.create(CloseOperation);
self.* = CloseOperation{
.loop = loop,
.os_data = switch (builtin.os) {
.linux, .macosx, .freebsd, .netbsd => initOsDataPosix(self),
.windows => OsData{ .handle = null },
else => @compileError("Unsupported OS"),
},
};
return self;
}
fn initOsDataPosix(self: *CloseOperation) OsData {
return OsData{
.have_fd = false,
.close_req_node = RequestNode{
.prev = null,
.next = null,
.data = Request{
.msg = Request.Msg{
.Close = Request.Msg.Close{ .fd = undefined },
},
.finish = Request.Finish{ .DeallocCloseOperation = self },
},
},
};
}
/// Defer this after creating.
pub fn finish(self: *CloseOperation) void {
switch (builtin.os) {
.linux,
.macosx,
.freebsd,
.netbsd,
=> {
if (self.os_data.have_fd) {
self.loop.posixFsRequest(&self.os_data.close_req_node);
} else {
self.loop.allocator.destroy(self);
}
},
.windows => {
if (self.os_data.handle) |handle| {
os.close(handle);
}
self.loop.allocator.destroy(self);
},
else => @compileError("Unsupported OS"),
}
}
pub fn setHandle(self: *CloseOperation, handle: fd_t) void {
switch (builtin.os) {
.linux,
.macosx,
.freebsd,
.netbsd,
=> {
self.os_data.close_req_node.data.msg.Close.fd = handle;
self.os_data.have_fd = true;
},
.windows => {
self.os_data.handle = handle;
},
else => @compileError("Unsupported OS"),
}
}
/// Undo a `setHandle`.
pub fn clearHandle(self: *CloseOperation) void {
switch (builtin.os) {
.linux,
.macosx,
.freebsd,
.netbsd,
=> {
self.os_data.have_fd = false;
},
.windows => {
self.os_data.handle = null;
},
else => @compileError("Unsupported OS"),
}
}
pub fn getHandle(self: *CloseOperation) fd_t {
switch (builtin.os) {
.linux,
.macosx,
.freebsd,
.netbsd,
=> {
assert(self.os_data.have_fd);
return self.os_data.close_req_node.data.msg.Close.fd;
},
.windows => {
return self.os_data.handle.?;
},
else => @compileError("Unsupported OS"),
}
}
};
/// contents must remain alive until writeFile completes.
/// TODO make this atomic or provide writeFileAtomic and rename this one to writeFileTruncate
pub fn writeFile(loop: *Loop, path: []const u8, contents: []const u8) !void {
return writeFileMode(loop, path, contents, File.default_mode);
}
/// contents must remain alive until writeFile completes.
pub fn writeFileMode(loop: *Loop, path: []const u8, contents: []const u8, mode: File.Mode) !void {
switch (builtin.os) {
.linux,
.macosx,
.freebsd,
.netbsd,
=> return writeFileModeThread(loop, path, contents, mode),
.windows => return writeFileWindows(loop, path, contents),
else => @compileError("Unsupported OS"),
}
}
fn writeFileWindows(loop: *Loop, path: []const u8, contents: []const u8) !void {
const handle = try windows.CreateFile(
path,
windows.GENERIC_WRITE,
windows.FILE_SHARE_WRITE | windows.FILE_SHARE_READ | windows.FILE_SHARE_DELETE,
null,
windows.CREATE_ALWAYS,
windows.FILE_ATTRIBUTE_NORMAL | windows.FILE_FLAG_OVERLAPPED,
null,
);
defer os.close(handle);
try pwriteWindows(loop, handle, contents, 0);
}
fn writeFileModeThread(loop: *Loop, path: []const u8, contents: []const u8, mode: File.Mode) !void {
const path_with_null = try std.cstr.addNullByte(loop.allocator, path);
defer loop.allocator.free(path_with_null);
var req_node = RequestNode{
.prev = null,
.next = null,
.data = Request{
.msg = Request.Msg{
.WriteFile = Request.Msg.WriteFile{
.path = path_with_null[0..path.len],
.contents = contents,
.mode = mode,
.result = undefined,
},
},
.finish = Request.Finish{
.TickNode = Loop.NextTickNode{
.prev = null,
.next = null,
.data = @frame(),
},
},
},
};
errdefer loop.posixFsCancel(&req_node);
suspend {
loop.posixFsRequest(&req_node);
}
return req_node.data.msg.WriteFile.result;
}
/// The frame resumes when the last data has been confirmed written, but before the file handle
/// is closed.
/// Caller owns returned memory.
pub fn readFile(loop: *Loop, file_path: []const u8, max_size: usize) ![]u8 {
var close_op = try CloseOperation.start(loop);
defer close_op.finish();
const fd = try openRead(loop, file_path);
close_op.setHandle(fd);
var list = std.ArrayList(u8).init(loop.allocator);
defer list.deinit();
while (true) {
try list.ensureCapacity(list.len + mem.page_size);
const buf = list.items[list.len..];
const buf_array = [_][]u8{buf};
const amt = try preadv(loop, fd, buf_array, list.len);
list.len += amt;
if (list.len > max_size) {
return error.FileTooBig;
}
if (amt < buf.len) {
return list.toOwnedSlice();
}
}
}
pub const WatchEventId = enum {
CloseWrite,
Delete,
};
//pub const WatchEventError = error{
// UserResourceLimitReached,
// SystemResources,
// AccessDenied,
// Unexpected, // TODO remove this possibility
//};
//
//pub fn Watch(comptime V: type) type {
// return struct {
// channel: *event.Channel(Event.Error!Event),
// os_data: OsData,
//
// const OsData = switch (builtin.os) {
// .macosx, .freebsd, .netbsd => struct {
// file_table: FileTable,
// table_lock: event.Lock,
//
// const FileTable = std.AutoHashMap([]const u8, *Put);
// const Put = struct {
// putter: anyframe,
// value_ptr: *V,
// };
// },
//
// .linux => LinuxOsData,
// .windows => WindowsOsData,
//
// else => @compileError("Unsupported OS"),
// };
//
// const WindowsOsData = struct {
// table_lock: event.Lock,
// dir_table: DirTable,
// all_putters: std.atomic.Queue(anyframe),
// ref_count: std.atomic.Int(usize),
//
// const DirTable = std.AutoHashMap([]const u8, *Dir);
// const FileTable = std.AutoHashMap([]const u16, V);
//
// const Dir = struct {
// putter: anyframe,
// file_table: FileTable,
// table_lock: event.Lock,
// };
// };
//
// const LinuxOsData = struct {
// putter: anyframe,
// inotify_fd: i32,
// wd_table: WdTable,
// table_lock: event.Lock,
//
// const WdTable = std.AutoHashMap(i32, Dir);
// const FileTable = std.AutoHashMap([]const u8, V);
//
// const Dir = struct {
// dirname: []const u8,
// file_table: FileTable,
// };
// };
//
// const FileToHandle = std.AutoHashMap([]const u8, anyframe);
//
// const Self = @This();
//
// pub const Event = struct {
// id: Id,
// data: V,
//
// pub const Id = WatchEventId;
// pub const Error = WatchEventError;
// };
//
// pub fn create(loop: *Loop, event_buf_count: usize) !*Self {
// const channel = try event.Channel(Self.Event.Error!Self.Event).create(loop, event_buf_count);
// errdefer channel.destroy();
//
// switch (builtin.os) {
// .linux => {
// const inotify_fd = try os.inotify_init1(os.linux.IN_NONBLOCK | os.linux.IN_CLOEXEC);
// errdefer os.close(inotify_fd);
//
// var result: *Self = undefined;
// _ = try async<loop.allocator> linuxEventPutter(inotify_fd, channel, &result);
// return result;
// },
//
// .windows => {
// const self = try loop.allocator.create(Self);
// errdefer loop.allocator.destroy(self);
// self.* = Self{
// .channel = channel,
// .os_data = OsData{
// .table_lock = event.Lock.init(loop),
// .dir_table = OsData.DirTable.init(loop.allocator),
// .ref_count = std.atomic.Int(usize).init(1),
// .all_putters = std.atomic.Queue(anyframe).init(),
// },
// };
// return self;
// },
//
// .macosx, .freebsd, .netbsd => {
// const self = try loop.allocator.create(Self);
// errdefer loop.allocator.destroy(self);
//
// self.* = Self{
// .channel = channel,
// .os_data = OsData{
// .table_lock = event.Lock.init(loop),
// .file_table = OsData.FileTable.init(loop.allocator),
// },
// };
// return self;
// },
// else => @compileError("Unsupported OS"),
// }
// }
//
// /// All addFile calls and removeFile calls must have completed.
// pub fn destroy(self: *Self) void {
// switch (builtin.os) {
// .macosx, .freebsd, .netbsd => {
// // TODO we need to cancel the frames before destroying the lock
// self.os_data.table_lock.deinit();
// var it = self.os_data.file_table.iterator();
// while (it.next()) |entry| {
// cancel entry.value.putter;
// self.channel.loop.allocator.free(entry.key);
// }
// self.channel.destroy();
// },
// .linux => cancel self.os_data.putter,
// .windows => {
// while (self.os_data.all_putters.get()) |putter_node| {
// cancel putter_node.data;
// }
// self.deref();
// },
// else => @compileError("Unsupported OS"),
// }
// }
//
// fn ref(self: *Self) void {
// _ = self.os_data.ref_count.incr();
// }
//
// fn deref(self: *Self) void {
// if (self.os_data.ref_count.decr() == 1) {
// const allocator = self.channel.loop.allocator;
// self.os_data.table_lock.deinit();
// var it = self.os_data.dir_table.iterator();
// while (it.next()) |entry| {
// allocator.free(entry.key);
// allocator.destroy(entry.value);
// }
// self.os_data.dir_table.deinit();
// self.channel.destroy();
// allocator.destroy(self);
// }
// }
//
// pub async fn addFile(self: *Self, file_path: []const u8, value: V) !?V {
// switch (builtin.os) {
// .macosx, .freebsd, .netbsd => return await (async addFileKEvent(self, file_path, value) catch unreachable),
// .linux => return await (async addFileLinux(self, file_path, value) catch unreachable),
// .windows => return await (async addFileWindows(self, file_path, value) catch unreachable),
// else => @compileError("Unsupported OS"),
// }
// }
//
// async fn addFileKEvent(self: *Self, file_path: []const u8, value: V) !?V {
// const resolved_path = try std.fs.path.resolve(self.channel.loop.allocator, [_][]const u8{file_path});
// var resolved_path_consumed = false;
// defer if (!resolved_path_consumed) self.channel.loop.allocator.free(resolved_path);
//
// var close_op = try CloseOperation.start(self.channel.loop);
// var close_op_consumed = false;
// defer if (!close_op_consumed) close_op.finish();
//
// const flags = if (os.darwin.is_the_target) os.O_SYMLINK | os.O_EVTONLY else 0;
// const mode = 0;
// const fd = try await (async openPosix(self.channel.loop, resolved_path, flags, mode) catch unreachable);
// close_op.setHandle(fd);
//
// var put_data: *OsData.Put = undefined;
// const putter = try async self.kqPutEvents(close_op, value, &put_data);
// close_op_consumed = true;
// errdefer cancel putter;
//
// const result = blk: {
// const held = await (async self.os_data.table_lock.acquire() catch unreachable);
// defer held.release();
//
// const gop = try self.os_data.file_table.getOrPut(resolved_path);
// if (gop.found_existing) {
// const prev_value = gop.kv.value.value_ptr.*;
// cancel gop.kv.value.putter;
// gop.kv.value = put_data;
// break :blk prev_value;
// } else {
// resolved_path_consumed = true;
// gop.kv.value = put_data;
// break :blk null;
// }
// };
//
// return result;
// }
//
// async fn kqPutEvents(self: *Self, close_op: *CloseOperation, value: V, out_put: **OsData.Put) void {
// var value_copy = value;
// var put = OsData.Put{
// .putter = @frame(),
// .value_ptr = &value_copy,
// };
// out_put.* = &put;
// self.channel.loop.beginOneEvent();
//
// defer {
// close_op.finish();
// self.channel.loop.finishOneEvent();
// }
//
// while (true) {
// if (await (async self.channel.loop.bsdWaitKev(
// @intCast(usize, close_op.getHandle()),
// os.EVFILT_VNODE,
// os.NOTE_WRITE | os.NOTE_DELETE,
// ) catch unreachable)) |kev| {
// // TODO handle EV_ERROR
// if (kev.fflags & os.NOTE_DELETE != 0) {
// await (async self.channel.put(Self.Event{
// .id = Event.Id.Delete,
// .data = value_copy,
// }) catch unreachable);
// } else if (kev.fflags & os.NOTE_WRITE != 0) {
// await (async self.channel.put(Self.Event{
// .id = Event.Id.CloseWrite,
// .data = value_copy,
// }) catch unreachable);
// }
// } else |err| switch (err) {
// error.EventNotFound => unreachable,
// error.ProcessNotFound => unreachable,
// error.Overflow => unreachable,
// error.AccessDenied, error.SystemResources => |casted_err| {
// await (async self.channel.put(casted_err) catch unreachable);
// },
// }
// }
// }
//
// async fn addFileLinux(self: *Self, file_path: []const u8, value: V) !?V {
// const value_copy = value;
//
// const dirname = std.fs.path.dirname(file_path) orelse ".";
// const dirname_with_null = try std.cstr.addNullByte(self.channel.loop.allocator, dirname);
// var dirname_with_null_consumed = false;
// defer if (!dirname_with_null_consumed) self.channel.loop.allocator.free(dirname_with_null);
//
// const basename = std.fs.path.basename(file_path);
// const basename_with_null = try std.cstr.addNullByte(self.channel.loop.allocator, basename);
// var basename_with_null_consumed = false;
// defer if (!basename_with_null_consumed) self.channel.loop.allocator.free(basename_with_null);
//
// const wd = try os.inotify_add_watchC(
// self.os_data.inotify_fd,
// dirname_with_null.ptr,
// os.linux.IN_CLOSE_WRITE | os.linux.IN_ONLYDIR | os.linux.IN_EXCL_UNLINK,
// );
// // wd is either a newly created watch or an existing one.
//
// const held = await (async self.os_data.table_lock.acquire() catch unreachable);
// defer held.release();
//
// const gop = try self.os_data.wd_table.getOrPut(wd);
// if (!gop.found_existing) {
// gop.kv.value = OsData.Dir{
// .dirname = dirname_with_null,
// .file_table = OsData.FileTable.init(self.channel.loop.allocator),
// };
// dirname_with_null_consumed = true;
// }
// const dir = &gop.kv.value;
//
// const file_table_gop = try dir.file_table.getOrPut(basename_with_null);
// if (file_table_gop.found_existing) {
// const prev_value = file_table_gop.kv.value;
// file_table_gop.kv.value = value_copy;
// return prev_value;
// } else {
// file_table_gop.kv.value = value_copy;
// basename_with_null_consumed = true;
// return null;
// }
// }
//
// async fn addFileWindows(self: *Self, file_path: []const u8, value: V) !?V {
// const value_copy = value;
// // TODO we might need to convert dirname and basename to canonical file paths ("short"?)
//
// const dirname = try std.mem.dupe(self.channel.loop.allocator, u8, std.fs.path.dirname(file_path) orelse ".");
// var dirname_consumed = false;
// defer if (!dirname_consumed) self.channel.loop.allocator.free(dirname);
//
// const dirname_utf16le = try std.unicode.utf8ToUtf16LeWithNull(self.channel.loop.allocator, dirname);
// defer self.channel.loop.allocator.free(dirname_utf16le);
//
// // TODO https://github.com/ziglang/zig/issues/265
// const basename = std.fs.path.basename(file_path);
// const basename_utf16le_null = try std.unicode.utf8ToUtf16LeWithNull(self.channel.loop.allocator, basename);
// var basename_utf16le_null_consumed = false;
// defer if (!basename_utf16le_null_consumed) self.channel.loop.allocator.free(basename_utf16le_null);
// const basename_utf16le_no_null = basename_utf16le_null[0 .. basename_utf16le_null.len - 1];
//
// const dir_handle = try windows.CreateFileW(
// dirname_utf16le.ptr,
// windows.FILE_LIST_DIRECTORY,
// windows.FILE_SHARE_READ | windows.FILE_SHARE_DELETE | windows.FILE_SHARE_WRITE,
// null,
// windows.OPEN_EXISTING,
// windows.FILE_FLAG_BACKUP_SEMANTICS | windows.FILE_FLAG_OVERLAPPED,
// null,
// );
// var dir_handle_consumed = false;
// defer if (!dir_handle_consumed) windows.CloseHandle(dir_handle);
//
// const held = await (async self.os_data.table_lock.acquire() catch unreachable);
// defer held.release();
//
// const gop = try self.os_data.dir_table.getOrPut(dirname);
// if (gop.found_existing) {
// const dir = gop.kv.value;
// const held_dir_lock = await (async dir.table_lock.acquire() catch unreachable);
// defer held_dir_lock.release();
//
// const file_gop = try dir.file_table.getOrPut(basename_utf16le_no_null);
// if (file_gop.found_existing) {
// const prev_value = file_gop.kv.value;
// file_gop.kv.value = value_copy;
// return prev_value;
// } else {
// file_gop.kv.value = value_copy;
// basename_utf16le_null_consumed = true;
// return null;
// }
// } else {
// errdefer _ = self.os_data.dir_table.remove(dirname);
// const dir = try self.channel.loop.allocator.create(OsData.Dir);
// errdefer self.channel.loop.allocator.destroy(dir);
//
// dir.* = OsData.Dir{
// .file_table = OsData.FileTable.init(self.channel.loop.allocator),
// .table_lock = event.Lock.init(self.channel.loop),
// .putter = undefined,
// };
// gop.kv.value = dir;
// assert((try dir.file_table.put(basename_utf16le_no_null, value_copy)) == null);
// basename_utf16le_null_consumed = true;
//
// dir.putter = try async self.windowsDirReader(dir_handle, dir);
// dir_handle_consumed = true;
//
// dirname_consumed = true;
//
// return null;
// }
// }
//
// async fn windowsDirReader(self: *Self, dir_handle: windows.HANDLE, dir: *OsData.Dir) void {
// self.ref();
// defer self.deref();
//
// defer os.close(dir_handle);
//
// var putter_node = std.atomic.Queue(anyframe).Node{
// .data = @frame(),
// .prev = null,
// .next = null,
// };
// self.os_data.all_putters.put(&putter_node);
// defer _ = self.os_data.all_putters.remove(&putter_node);
//
// var resume_node = Loop.ResumeNode.Basic{
// .base = Loop.ResumeNode{
// .id = Loop.ResumeNode.Id.Basic,
// .handle = @frame(),
// .overlapped = windows.OVERLAPPED{
// .Internal = 0,
// .InternalHigh = 0,
// .Offset = 0,
// .OffsetHigh = 0,
// .hEvent = null,
// },
// },
// };
// var event_buf: [4096]u8 align(@alignOf(windows.FILE_NOTIFY_INFORMATION)) = undefined;
//
// // TODO handle this error not in the channel but in the setup
// _ = windows.CreateIoCompletionPort(
// dir_handle,
// self.channel.loop.os_data.io_port,
// undefined,
// undefined,
// ) catch |err| {
// await (async self.channel.put(err) catch unreachable);
// return;
// };
//
// while (true) {
// {
// // TODO only 1 beginOneEvent for the whole function
// self.channel.loop.beginOneEvent();
// errdefer self.channel.loop.finishOneEvent();
// errdefer {
// _ = windows.kernel32.CancelIoEx(dir_handle, &resume_node.base.overlapped);
// }
// suspend {
// _ = windows.kernel32.ReadDirectoryChangesW(
// dir_handle,
// &event_buf,
// @intCast(windows.DWORD, event_buf.len),
// windows.FALSE, // watch subtree
// windows.FILE_NOTIFY_CHANGE_FILE_NAME | windows.FILE_NOTIFY_CHANGE_DIR_NAME |
// windows.FILE_NOTIFY_CHANGE_ATTRIBUTES | windows.FILE_NOTIFY_CHANGE_SIZE |
// windows.FILE_NOTIFY_CHANGE_LAST_WRITE | windows.FILE_NOTIFY_CHANGE_LAST_ACCESS |
// windows.FILE_NOTIFY_CHANGE_CREATION | windows.FILE_NOTIFY_CHANGE_SECURITY,
// null, // number of bytes transferred (unused for async)
// &resume_node.base.overlapped,
// null, // completion routine - unused because we use IOCP
// );
// }
// }
// var bytes_transferred: windows.DWORD = undefined;
// if (windows.kernel32.GetOverlappedResult(dir_handle, &resume_node.base.overlapped, &bytes_transferred, windows.FALSE) == 0) {
// const err = switch (windows.kernel32.GetLastError()) {
// else => |err| windows.unexpectedError(err),
// };
// await (async self.channel.put(err) catch unreachable);
// } else {
// // can't use @bytesToSlice because of the special variable length name field
// var ptr = event_buf[0..].ptr;
// const end_ptr = ptr + bytes_transferred;
// var ev: *windows.FILE_NOTIFY_INFORMATION = undefined;
// while (@ptrToInt(ptr) < @ptrToInt(end_ptr)) : (ptr += ev.NextEntryOffset) {
// ev = @ptrCast(*windows.FILE_NOTIFY_INFORMATION, ptr);
// const emit = switch (ev.Action) {
// windows.FILE_ACTION_REMOVED => WatchEventId.Delete,
// windows.FILE_ACTION_MODIFIED => WatchEventId.CloseWrite,
// else => null,
// };
// if (emit) |id| {
// const basename_utf16le = ([*]u16)(&ev.FileName)[0 .. ev.FileNameLength / 2];
// const user_value = blk: {
// const held = await (async dir.table_lock.acquire() catch unreachable);
// defer held.release();
//
// if (dir.file_table.get(basename_utf16le)) |entry| {
// break :blk entry.value;
// } else {
// break :blk null;
// }
// };
// if (user_value) |v| {
// await (async self.channel.put(Event{
// .id = id,
// .data = v,
// }) catch unreachable);
// }
// }
// if (ev.NextEntryOffset == 0) break;
// }
// }
// }
// }
//
// pub async fn removeFile(self: *Self, file_path: []const u8) ?V {
// @panic("TODO");
// }
//
// async fn linuxEventPutter(inotify_fd: i32, channel: *event.Channel(Event.Error!Event), out_watch: **Self) void {
// const loop = channel.loop;
//
// var watch = Self{
// .channel = channel,
// .os_data = OsData{
// .putter = @frame(),
// .inotify_fd = inotify_fd,
// .wd_table = OsData.WdTable.init(loop.allocator),
// .table_lock = event.Lock.init(loop),
// },
// };
// out_watch.* = &watch;
//
// loop.beginOneEvent();
//
// defer {
// watch.os_data.table_lock.deinit();
// var wd_it = watch.os_data.wd_table.iterator();
// while (wd_it.next()) |wd_entry| {
// var file_it = wd_entry.value.file_table.iterator();
// while (file_it.next()) |file_entry| {
// loop.allocator.free(file_entry.key);
// }
// loop.allocator.free(wd_entry.value.dirname);
// }
// loop.finishOneEvent();
// os.close(inotify_fd);
// channel.destroy();
// }
//
// var event_buf: [4096]u8 align(@alignOf(os.linux.inotify_event)) = undefined;
//
// while (true) {
// const rc = os.linux.read(inotify_fd, &event_buf, event_buf.len);
// const errno = os.linux.getErrno(rc);
// switch (errno) {
// 0 => {
// // can't use @bytesToSlice because of the special variable length name field
// var ptr = event_buf[0..].ptr;
// const end_ptr = ptr + event_buf.len;
// var ev: *os.linux.inotify_event = undefined;
// while (@ptrToInt(ptr) < @ptrToInt(end_ptr)) : (ptr += @sizeOf(os.linux.inotify_event) + ev.len) {
// ev = @ptrCast(*os.linux.inotify_event, ptr);
// if (ev.mask & os.linux.IN_CLOSE_WRITE == os.linux.IN_CLOSE_WRITE) {
// const basename_ptr = ptr + @sizeOf(os.linux.inotify_event);
// const basename_with_null = basename_ptr[0 .. std.mem.len(u8, basename_ptr) + 1];
// const user_value = blk: {
// const held = await (async watch.os_data.table_lock.acquire() catch unreachable);
// defer held.release();
//
// const dir = &watch.os_data.wd_table.get(ev.wd).?.value;
// if (dir.file_table.get(basename_with_null)) |entry| {
// break :blk entry.value;
// } else {
// break :blk null;
// }
// };
// if (user_value) |v| {
// await (async channel.put(Event{
// .id = WatchEventId.CloseWrite,
// .data = v,
// }) catch unreachable);
// }
// }
// }
// },
// os.linux.EINTR => continue,
// os.linux.EINVAL => unreachable,
// os.linux.EFAULT => unreachable,
// os.linux.EAGAIN => {
// (await (async loop.linuxWaitFd(
// inotify_fd,
// os.linux.EPOLLET | os.linux.EPOLLIN,
// ) catch unreachable)) catch |err| {
// const transformed_err = switch (err) {
// error.FileDescriptorAlreadyPresentInSet => unreachable,
// error.OperationCausesCircularLoop => unreachable,
// error.FileDescriptorNotRegistered => unreachable,
// error.FileDescriptorIncompatibleWithEpoll => unreachable,
// error.Unexpected => unreachable,
// else => |e| e,
// };
// await (async channel.put(transformed_err) catch unreachable);
// };
// },
// else => unreachable,
// }
// }
// }
// };
//}
const test_tmp_dir = "std_event_fs_test";
// TODO this test is disabled until the async function rewrite is finished.
//test "write a file, watch it, write it again" {
// return error.SkipZigTest;
// const allocator = std.heap.direct_allocator;
//
// // TODO move this into event loop too
// try os.makePath(allocator, test_tmp_dir);
// defer os.deleteTree(allocator, test_tmp_dir) catch {};
//
// var loop: Loop = undefined;
// try loop.initMultiThreaded(allocator);
// defer loop.deinit();
//
// var result: anyerror!void = error.ResultNeverWritten;
// const handle = try async<allocator> testFsWatchCantFail(&loop, &result);
// defer cancel handle;
//
// loop.run();
// return result;
//}
fn testFsWatchCantFail(loop: *Loop, result: *(anyerror!void)) void {
result.* = testFsWatch(loop);
}
fn testFsWatch(loop: *Loop) !void {
const file_path = try std.fs.path.join(loop.allocator, [][]const u8{ test_tmp_dir, "file.txt" });
defer loop.allocator.free(file_path);
const contents =
\\line 1
\\line 2
;
const line2_offset = 7;
// first just write then read the file
try writeFile(loop, file_path, contents);
const read_contents = try readFile(loop, file_path, 1024 * 1024);
testing.expectEqualSlices(u8, contents, read_contents);
// now watch the file
var watch = try Watch(void).create(loop, 0);
defer watch.destroy();
testing.expect((try watch.addFile(file_path, {})) == null);
const ev = async watch.channel.get();
var ev_consumed = false;
defer if (!ev_consumed) await ev;
// overwrite line 2
const fd = try await openReadWrite(loop, file_path, File.default_mode);
{
defer os.close(fd);
try pwritev(loop, fd, []const []const u8{"lorem ipsum"}, line2_offset);
}
ev_consumed = true;
switch ((try await ev).id) {
WatchEventId.CloseWrite => {},
WatchEventId.Delete => @panic("wrong event"),
}
const contents_updated = try readFile(loop, file_path, 1024 * 1024);
testing.expectEqualSlices(u8,
\\line 1
\\lorem ipsum
, contents_updated);
// TODO test deleting the file and then re-adding it. we should get events for both
}
pub const OutStream = struct {
fd: fd_t,
stream: Stream,
loop: *Loop,
offset: usize,
pub const Error = File.WriteError;
pub const Stream = event.io.OutStream(Error);
pub fn init(loop: *Loop, fd: fd_t, offset: usize) OutStream {
return OutStream{
.fd = fd,
.loop = loop,
.offset = offset,
.stream = Stream{ .writeFn = writeFn },
};
}
fn writeFn(out_stream: *Stream, bytes: []const u8) Error!void {
const self = @fieldParentPtr(OutStream, "stream", out_stream);
const offset = self.offset;
self.offset += bytes.len;
return pwritev(self.loop, self.fd, [][]const u8{bytes}, offset);
}
};
pub const InStream = struct {
fd: fd_t,
stream: Stream,
loop: *Loop,
offset: usize,
pub const Error = PReadVError; // TODO make this not have OutOfMemory
pub const Stream = event.io.InStream(Error);
pub fn init(loop: *Loop, fd: fd_t, offset: usize) InStream {
return InStream{
.fd = fd,
.loop = loop,
.offset = offset,
.stream = Stream{ .readFn = readFn },
};
}
fn readFn(in_stream: *Stream, bytes: []u8) Error!usize {
const self = @fieldParentPtr(InStream, "stream", in_stream);
const amt = try preadv(self.loop, self.fd, [][]u8{bytes}, self.offset);
self.offset += amt;
return amt;
}
}; | std/event/fs.zig |
const tests = @import("tests.zig");
pub fn addCases(cases: *tests.CompareOutputContext) void {
cases.addRuntimeSafety("@floatToInt cannot fit - negative to unsigned",
\\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
\\ @import("std").os.exit(126);
\\}
\\pub fn main() void {
\\ baz(bar(-1.1));
\\}
\\fn bar(a: f32) u8 {
\\ return @floatToInt(u8, a);
\\}
\\fn baz(a: u8) void { }
);
cases.addRuntimeSafety("@floatToInt cannot fit - negative out of range",
\\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
\\ @import("std").os.exit(126);
\\}
\\pub fn main() void {
\\ baz(bar(-129.1));
\\}
\\fn bar(a: f32) i8 {
\\ return @floatToInt(i8, a);
\\}
\\fn baz(a: i8) void { }
);
cases.addRuntimeSafety("@floatToInt cannot fit - positive out of range",
\\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
\\ @import("std").os.exit(126);
\\}
\\pub fn main() void {
\\ baz(bar(256.2));
\\}
\\fn bar(a: f32) u8 {
\\ return @floatToInt(u8, a);
\\}
\\fn baz(a: u8) void { }
);
cases.addRuntimeSafety("calling panic",
\\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
\\ @import("std").os.exit(126);
\\}
\\pub fn main() void {
\\ @panic("oh no");
\\}
);
cases.addRuntimeSafety("out of bounds slice access",
\\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
\\ @import("std").os.exit(126);
\\}
\\pub fn main() void {
\\ const a = []i32{1, 2, 3, 4};
\\ baz(bar(a));
\\}
\\fn bar(a: []const i32) i32 {
\\ return a[4];
\\}
\\fn baz(a: i32) void { }
);
cases.addRuntimeSafety("integer addition overflow",
\\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
\\ @import("std").os.exit(126);
\\}
\\pub fn main() !void {
\\ const x = add(65530, 10);
\\ if (x == 0) return error.Whatever;
\\}
\\fn add(a: u16, b: u16) u16 {
\\ return a + b;
\\}
);
cases.addRuntimeSafety("integer subtraction overflow",
\\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
\\ @import("std").os.exit(126);
\\}
\\pub fn main() !void {
\\ const x = sub(10, 20);
\\ if (x == 0) return error.Whatever;
\\}
\\fn sub(a: u16, b: u16) u16 {
\\ return a - b;
\\}
);
cases.addRuntimeSafety("integer multiplication overflow",
\\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
\\ @import("std").os.exit(126);
\\}
\\pub fn main() !void {
\\ const x = mul(300, 6000);
\\ if (x == 0) return error.Whatever;
\\}
\\fn mul(a: u16, b: u16) u16 {
\\ return a * b;
\\}
);
cases.addRuntimeSafety("integer negation overflow",
\\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
\\ @import("std").os.exit(126);
\\}
\\pub fn main() !void {
\\ const x = neg(-32768);
\\ if (x == 32767) return error.Whatever;
\\}
\\fn neg(a: i16) i16 {
\\ return -a;
\\}
);
cases.addRuntimeSafety("signed integer division overflow",
\\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
\\ @import("std").os.exit(126);
\\}
\\pub fn main() !void {
\\ const x = div(-32768, -1);
\\ if (x == 32767) return error.Whatever;
\\}
\\fn div(a: i16, b: i16) i16 {
\\ return @divTrunc(a, b);
\\}
);
cases.addRuntimeSafety("signed shift left overflow",
\\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
\\ @import("std").os.exit(126);
\\}
\\pub fn main() !void {
\\ const x = shl(-16385, 1);
\\ if (x == 0) return error.Whatever;
\\}
\\fn shl(a: i16, b: u4) i16 {
\\ return @shlExact(a, b);
\\}
);
cases.addRuntimeSafety("unsigned shift left overflow",
\\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
\\ @import("std").os.exit(126);
\\}
\\pub fn main() !void {
\\ const x = shl(0b0010111111111111, 3);
\\ if (x == 0) return error.Whatever;
\\}
\\fn shl(a: u16, b: u4) u16 {
\\ return @shlExact(a, b);
\\}
);
cases.addRuntimeSafety("signed shift right overflow",
\\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
\\ @import("std").os.exit(126);
\\}
\\pub fn main() !void {
\\ const x = shr(-16385, 1);
\\ if (x == 0) return error.Whatever;
\\}
\\fn shr(a: i16, b: u4) i16 {
\\ return @shrExact(a, b);
\\}
);
cases.addRuntimeSafety("unsigned shift right overflow",
\\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
\\ @import("std").os.exit(126);
\\}
\\pub fn main() !void {
\\ const x = shr(0b0010111111111111, 3);
\\ if (x == 0) return error.Whatever;
\\}
\\fn shr(a: u16, b: u4) u16 {
\\ return @shrExact(a, b);
\\}
);
cases.addRuntimeSafety("integer division by zero",
\\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
\\ @import("std").os.exit(126);
\\}
\\pub fn main() void {
\\ const x = div0(999, 0);
\\}
\\fn div0(a: i32, b: i32) i32 {
\\ return @divTrunc(a, b);
\\}
);
cases.addRuntimeSafety("exact division failure",
\\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
\\ @import("std").os.exit(126);
\\}
\\pub fn main() !void {
\\ const x = divExact(10, 3);
\\ if (x == 0) return error.Whatever;
\\}
\\fn divExact(a: i32, b: i32) i32 {
\\ return @divExact(a, b);
\\}
);
cases.addRuntimeSafety("cast []u8 to bigger slice of wrong size",
\\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
\\ @import("std").os.exit(126);
\\}
\\pub fn main() !void {
\\ const x = widenSlice([]u8{1, 2, 3, 4, 5});
\\ if (x.len == 0) return error.Whatever;
\\}
\\fn widenSlice(slice: []align(1) const u8) []align(1) const i32 {
\\ return @bytesToSlice(i32, slice);
\\}
);
cases.addRuntimeSafety("value does not fit in shortening cast",
\\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
\\ @import("std").os.exit(126);
\\}
\\pub fn main() !void {
\\ const x = shorten_cast(200);
\\ if (x == 0) return error.Whatever;
\\}
\\fn shorten_cast(x: i32) i8 {
\\ return @intCast(i8, x);
\\}
);
cases.addRuntimeSafety("signed integer not fitting in cast to unsigned integer",
\\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
\\ @import("std").os.exit(126);
\\}
\\pub fn main() !void {
\\ const x = unsigned_cast(-10);
\\ if (x == 0) return error.Whatever;
\\}
\\fn unsigned_cast(x: i32) u32 {
\\ return @intCast(u32, x);
\\}
);
cases.addRuntimeSafety("unwrap error",
\\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
\\ if (@import("std").mem.eql(u8, message, "attempt to unwrap error: Whatever")) {
\\ @import("std").os.exit(126); // good
\\ }
\\ @import("std").os.exit(0); // test failed
\\}
\\pub fn main() void {
\\ bar() catch unreachable;
\\}
\\fn bar() !void {
\\ return error.Whatever;
\\}
);
cases.addRuntimeSafety("cast integer to global error and no code matches",
\\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
\\ @import("std").os.exit(126);
\\}
\\pub fn main() void {
\\ _ = bar(9999);
\\}
\\fn bar(x: u16) error {
\\ return @intToError(x);
\\}
);
cases.addRuntimeSafety("@errSetCast error not present in destination",
\\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
\\ @import("std").os.exit(126);
\\}
\\const Set1 = error{A, B};
\\const Set2 = error{A, C};
\\pub fn main() void {
\\ _ = foo(Set1.B);
\\}
\\fn foo(set1: Set1) Set2 {
\\ return @errSetCast(Set2, set1);
\\}
);
cases.addRuntimeSafety("@alignCast misaligned",
\\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
\\ @import("std").os.exit(126);
\\}
\\pub fn main() !void {
\\ var array align(4) = []u32{0x11111111, 0x11111111};
\\ const bytes = @sliceToBytes(array[0..]);
\\ if (foo(bytes) != 0x11111111) return error.Wrong;
\\}
\\fn foo(bytes: []u8) u32 {
\\ const slice4 = bytes[1..5];
\\ const int_slice = @bytesToSlice(u32, @alignCast(4, slice4));
\\ return int_slice[0];
\\}
);
cases.addRuntimeSafety("bad union field access",
\\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
\\ @import("std").os.exit(126);
\\}
\\
\\const Foo = union {
\\ float: f32,
\\ int: u32,
\\};
\\
\\pub fn main() void {
\\ var f = Foo { .int = 42 };
\\ bar(&f);
\\}
\\
\\fn bar(f: *Foo) void {
\\ f.float = 12.34;
\\}
);
// This case makes sure that the code compiles and runs. There is not actually a special
// runtime safety check having to do specifically with error return traces across suspend points.
cases.addRuntimeSafety("error return trace across suspend points",
\\const std = @import("std");
\\
\\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
\\ std.os.exit(126);
\\}
\\
\\pub fn main() void {
\\ const p = nonFailing();
\\ resume p;
\\ const p2 = async<std.debug.global_allocator> printTrace(p) catch unreachable;
\\ cancel p2;
\\}
\\
\\fn nonFailing() promise->error!void {
\\ return async<std.debug.global_allocator> failing() catch unreachable;
\\}
\\
\\async fn failing() error!void {
\\ suspend;
\\ return error.Fail;
\\}
\\
\\async fn printTrace(p: promise->error!void) void {
\\ (await p) catch unreachable;
\\}
);
} | test/runtime_safety.zig |
const std = @import("std");
const offsets = @import("offsets.zig");
const DocumentStore = @import("document_store.zig");
const analysis = @import("analysis.zig");
const ast = std.zig.ast;
pub const TokenType = enum(u32) {
type,
parameter,
variable,
tagField,
field,
errorTag,
function,
keyword,
comment,
string,
number,
operator,
builtin,
label,
keywordLiteral,
};
pub const TokenModifiers = packed struct {
namespace: bool = false,
@"struct": bool = false,
@"enum": bool = false,
@"union": bool = false,
@"opaque": bool = false,
definition: bool = false,
@"async": bool = false,
documentation: bool = false,
generic: bool = false,
fn toInt(self: TokenModifiers) u32 {
var res: u32 = 0;
inline for (std.meta.fields(TokenModifiers)) |field, i| {
if (@field(self, field.name)) {
res |= 1 << i;
}
}
return res;
}
inline fn set(self: *TokenModifiers, comptime field: []const u8) void {
@field(self, field) = true;
}
};
const Builder = struct {
handle: *DocumentStore.Handle,
current_token: ?ast.TokenIndex,
arr: std.ArrayList(u32),
encoding: offsets.Encoding,
fn init(allocator: *std.mem.Allocator, handle: *DocumentStore.Handle, encoding: offsets.Encoding) Builder {
return Builder{
.handle = handle,
.current_token = null,
.arr = std.ArrayList(u32).init(allocator),
.encoding = encoding,
};
}
fn add(self: *Builder, token: ast.TokenIndex, token_type: TokenType, token_modifiers: TokenModifiers) !void {
const start_idx = if (self.current_token) |current_token|
self.handle.tree.token_locs[current_token].start
else
0;
if (start_idx > self.handle.tree.token_locs[token].start)
return;
const delta_loc = offsets.tokenRelativeLocation(self.handle.tree, start_idx, token, self.encoding) catch return;
try self.arr.appendSlice(&[_]u32{
@truncate(u32, delta_loc.line),
@truncate(u32, delta_loc.column),
@truncate(u32, offsets.tokenLength(self.handle.tree, token, self.encoding)),
@enumToInt(token_type),
token_modifiers.toInt(),
});
self.current_token = token;
}
fn toOwnedSlice(self: *Builder) []u32 {
return self.arr.toOwnedSlice();
}
};
inline fn writeToken(builder: *Builder, token_idx: ?ast.TokenIndex, tok_type: TokenType) !void {
return try writeTokenMod(builder, token_idx, tok_type, .{});
}
inline fn writeTokenMod(builder: *Builder, token_idx: ?ast.TokenIndex, tok_type: TokenType, tok_mod: TokenModifiers) !void {
if (token_idx) |ti| {
try builder.add(ti, tok_type, tok_mod);
}
}
fn writeDocComments(builder: *Builder, tree: *ast.Tree, doc: *ast.Node.DocComment) !void {
var tok_idx = doc.first_line;
while (tree.token_ids[tok_idx] == .DocComment or
tree.token_ids[tok_idx] == .ContainerDocComment or
tree.token_ids[tok_idx] == .LineComment) : (tok_idx += 1)
{
var tok_mod = TokenModifiers{};
if (tree.token_ids[tok_idx] == .DocComment or tree.token_ids[tok_idx] == .ContainerDocComment)
tok_mod.set("documentation");
try builder.add(tok_idx, .comment, tok_mod);
}
}
fn fieldTokenType(container_decl: *ast.Node.ContainerDecl, handle: *DocumentStore.Handle) ?TokenType {
if (container_decl.kind_token > handle.tree.token_ids.len) return null;
return @as(?TokenType, switch (handle.tree.token_ids[container_decl.kind_token]) {
.Keyword_struct => .field,
.Keyword_union, .Keyword_enum => .tagField,
else => null,
});
}
/// This is used to highlight gaps between AST nodes.
/// These gaps can be just gaps between statements/declarations with comments inside them
/// Or malformed code.
const GapHighlighter = struct {
builder: *Builder,
current_idx: ast.TokenIndex,
// TODO More highlighting here
fn handleTok(self: *GapHighlighter, tok: ast.TokenIndex) !void {
const tok_id = self.builder.handle.tree.token_ids[tok];
if (tok_id == .LineComment) {
try writeToken(self.builder, tok, .comment);
} else if (tok_id == .ContainerDocComment or tok_id == .DocComment) {
try writeTokenMod(self.builder, tok, .comment, .{ .documentation = true });
} else if (@enumToInt(tok_id) >= @enumToInt(std.zig.Token.Id.Keyword_align) and
@enumToInt(tok_id) <= @enumToInt(std.zig.Token.Id.Keyword_while))
{
const tok_type: TokenType = switch (tok_id) {
.Keyword_true,
.Keyword_false,
.Keyword_null,
.Keyword_undefined,
.Keyword_unreachable,
=> .keywordLiteral,
else => .keyword,
};
try writeToken(self.builder, tok, tok_type);
} else if (@enumToInt(tok_id) >= @enumToInt(std.zig.Token.Id.Bang) and
@enumToInt(tok_id) <= @enumToInt(std.zig.Token.Id.Tilde) and
tok_id != .Period and tok_id != .Comma and tok_id != .RParen and
tok_id != .LParen and tok_id != .RBrace and tok_id != .LBrace and
tok_id != .Semicolon and tok_id != .Colon)
{
try writeToken(self.builder, tok, .operator);
} else if (tok_id == .IntegerLiteral or tok_id == .FloatLiteral) {
try writeToken(self.builder, tok, .number);
} else if (tok_id == .StringLiteral or tok_id == .MultilineStringLiteralLine or tok_id == .CharLiteral) {
try writeToken(self.builder, tok, .string);
}
}
fn init(builder: *Builder, start: ast.TokenIndex) GapHighlighter {
return .{ .builder = builder, .current_idx = start };
}
fn next(self: *GapHighlighter, node: *ast.Node) !void {
if (self.current_idx > 0 and self.builder.handle.tree.token_ids[self.current_idx - 1] == .ContainerDocComment) {
try self.handleTok(self.current_idx - 1);
}
var i = self.current_idx;
while (i < node.firstToken()) : (i += 1) {
try self.handleTok(i);
}
self.current_idx = node.lastToken() + 1;
}
fn end(self: *GapHighlighter, last: ast.TokenIndex) !void {
var i = self.current_idx;
while (i < last) : (i += 1) {
try self.handleTok(i);
}
}
};
fn colorIdentifierBasedOnType(builder: *Builder, type_node: analysis.TypeWithHandle, target_tok: ast.TokenIndex, tok_mod: TokenModifiers) !void {
if (type_node.type.is_type_val) {
var new_tok_mod = tok_mod;
if (type_node.isNamespace())
new_tok_mod.set("namespace")
else if (type_node.isStructType())
new_tok_mod.set("struct")
else if (type_node.isEnumType())
new_tok_mod.set("enum")
else if (type_node.isUnionType())
new_tok_mod.set("union")
else if (type_node.isOpaqueType())
new_tok_mod.set("opaque");
try writeTokenMod(builder, target_tok, .type, new_tok_mod);
} else if (type_node.isTypeFunc()) {
try writeTokenMod(builder, target_tok, .type, tok_mod);
} else if (type_node.isFunc()) {
var new_tok_mod = tok_mod;
if (type_node.isGenericFunc()) {
new_tok_mod.set("generic");
}
try writeTokenMod(builder, target_tok, .function, new_tok_mod);
} else {
try writeTokenMod(builder, target_tok, .variable, tok_mod);
}
}
fn writeContainerField(
builder: *Builder,
arena: *std.heap.ArenaAllocator,
store: *DocumentStore,
container_field: *ast.Node.ContainerField,
field_token_type: ?TokenType,
child_frame: anytype,
) !void {
if (container_field.doc_comments) |docs| try writeDocComments(builder, builder.handle.tree, docs);
try writeToken(builder, container_field.comptime_token, .keyword);
if (field_token_type) |tok_type| try writeToken(builder, container_field.name_token, tok_type);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, container_field.type_expr });
if (container_field.align_expr) |n| {
try writeToken(builder, n.firstToken() - 2, .keyword);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, n });
}
if (container_field.value_expr) |value_expr| block: {
const eq_tok: ast.TokenIndex = if (container_field.type_expr) |type_expr|
type_expr.lastToken() + 1
else if (container_field.align_expr) |align_expr|
align_expr.lastToken() + 1
else
break :block; // Check this, I believe it is correct.
try writeToken(builder, eq_tok, .operator);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, value_expr });
}
}
// TODO This is very slow and does a lot of extra work, improve in the future.
fn writeNodeTokens(builder: *Builder, arena: *std.heap.ArenaAllocator, store: *DocumentStore, maybe_node: ?*ast.Node) error{OutOfMemory}!void {
if (maybe_node == null) return;
const node = maybe_node.?;
const handle = builder.handle;
const FrameSize = @sizeOf(@Frame(writeNodeTokens));
var child_frame = try arena.child_allocator.alignedAlloc(u8, std.Target.stack_align, FrameSize);
defer arena.child_allocator.free(child_frame);
switch (node.tag) {
.Root, .Block, .LabeledBlock => {
const first_tok = if (node.castTag(.LabeledBlock)) |block_node| block: {
try writeToken(builder, block_node.label, .label);
break :block block_node.lbrace + 1;
} else if (node.castTag(.Block)) |block_node|
block_node.lbrace + 1
else
0;
var gap_highlighter = GapHighlighter.init(builder, first_tok);
var child_idx: usize = 0;
while (node.iterate(child_idx)) |child| : (child_idx += 1) {
try gap_highlighter.next(child);
if (child.cast(ast.Node.ContainerField)) |container_field| {
try writeContainerField(builder, arena, store, container_field, .field, child_frame);
} else {
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, child });
}
}
if (node.tag == .Root) {
try gap_highlighter.end(handle.tree.token_ids.len - 1);
} else {
try gap_highlighter.end(node.lastToken());
}
},
.VarDecl => {
const var_decl = node.cast(ast.Node.VarDecl).?;
if (var_decl.getDocComments()) |doc| try writeDocComments(builder, handle.tree, doc);
try writeToken(builder, var_decl.getVisibToken(), .keyword);
try writeToken(builder, var_decl.getExternExportToken(), .keyword);
try writeToken(builder, var_decl.getThreadLocalToken(), .keyword);
try writeToken(builder, var_decl.getComptimeToken(), .keyword);
try writeToken(builder, var_decl.mut_token, .keyword);
if (try analysis.resolveTypeOfNode(store, arena, .{ .node = node, .handle = handle })) |decl_type| {
try colorIdentifierBasedOnType(builder, decl_type, var_decl.name_token, .{ .definition = true });
} else {
try writeTokenMod(builder, var_decl.name_token, .variable, .{ .definition = true });
}
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, var_decl.getTypeNode() });
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, var_decl.getAlignNode() });
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, var_decl.getSectionNode() });
try writeToken(builder, var_decl.getEqToken(), .operator);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, var_decl.getInitNode() });
},
.Use => {
const use = node.cast(ast.Node.Use).?;
if (use.doc_comments) |docs| try writeDocComments(builder, builder.handle.tree, docs);
try writeToken(builder, use.visib_token, .keyword);
try writeToken(builder, use.use_token, .keyword);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, use.expr });
},
.ErrorSetDecl => {
const error_set = node.cast(ast.Node.ErrorSetDecl).?;
try writeToken(builder, error_set.error_token, .keyword);
for (error_set.declsConst()) |decl|
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, decl });
},
.ContainerDecl => {
const container_decl = node.cast(ast.Node.ContainerDecl).?;
try writeToken(builder, container_decl.layout_token, .keyword);
try writeToken(builder, container_decl.kind_token, .keyword);
switch (container_decl.init_arg_expr) {
.None => {},
.Enum => |enum_expr| if (enum_expr) |expr|
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, expr })
else
try writeToken(builder, container_decl.kind_token + 2, .keyword),
.Type => |type_node| try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, type_node }),
}
var gap_highlighter = GapHighlighter.init(builder, container_decl.lbrace_token + 1);
const field_token_type = fieldTokenType(container_decl, handle);
for (container_decl.fieldsAndDeclsConst()) |child| {
try gap_highlighter.next(child);
if (child.cast(ast.Node.ContainerField)) |container_field| {
try writeContainerField(builder, arena, store, container_field, field_token_type, child_frame);
} else {
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, child });
}
}
try gap_highlighter.end(node.lastToken());
},
.ErrorTag => {
const error_tag = node.cast(ast.Node.ErrorTag).?;
if (error_tag.doc_comments) |docs| try writeDocComments(builder, handle.tree, docs);
try writeToken(builder, error_tag.firstToken(), .errorTag);
},
.Identifier => {
if (analysis.isTypeIdent(handle.tree, node.firstToken())) {
return try writeToken(builder, node.firstToken(), .type);
}
if (try analysis.lookupSymbolGlobal(store, arena, handle, handle.tree.getNodeSource(node), handle.tree.token_locs[node.firstToken()].start)) |child| {
if (child.decl.* == .param_decl) {
return try writeToken(builder, node.firstToken(), .parameter);
}
var bound_type_params = analysis.BoundTypeParams.init(&arena.allocator);
if (try child.resolveType(store, arena, &bound_type_params)) |decl_type| {
try colorIdentifierBasedOnType(builder, decl_type, node.firstToken(), .{});
} else {
try writeTokenMod(builder, node.firstToken(), .variable, .{});
}
}
},
.FnProto => {
const fn_proto = node.cast(ast.Node.FnProto).?;
if (fn_proto.getDocComments()) |docs| try writeDocComments(builder, handle.tree, docs);
try writeToken(builder, fn_proto.getVisibToken(), .keyword);
try writeToken(builder, fn_proto.getExternExportInlineToken(), .keyword);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, fn_proto.getLibName() });
try writeToken(builder, fn_proto.fn_token, .keyword);
const func_name_tok_type: TokenType = if (analysis.isTypeFunction(handle.tree, fn_proto))
.type
else
.function;
const tok_mod = if (analysis.isGenericFunction(handle.tree, fn_proto))
TokenModifiers{ .generic = true }
else
TokenModifiers{};
try writeTokenMod(builder, fn_proto.getNameToken(), func_name_tok_type, tok_mod);
for (fn_proto.paramsConst()) |param_decl| {
if (param_decl.doc_comments) |docs| try writeDocComments(builder, handle.tree, docs);
try writeToken(builder, param_decl.noalias_token, .keyword);
try writeToken(builder, param_decl.comptime_token, .keyword);
try writeTokenMod(builder, param_decl.name_token, .parameter, .{ .definition = true });
switch (param_decl.param_type) {
.any_type => |var_node| try writeToken(builder, var_node.firstToken(), .type),
.type_expr => |type_expr| try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, type_expr }),
}
}
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, fn_proto.getAlignExpr() });
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, fn_proto.getSectionExpr() });
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, fn_proto.getCallconvExpr() });
switch (fn_proto.return_type) {
.Explicit => |type_expr| try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, type_expr }),
.InferErrorSet => |type_expr| {
try writeToken(builder, type_expr.firstToken() - 1, .operator);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, type_expr });
},
.Invalid => {},
}
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, fn_proto.getBodyNode() });
},
.AnyFrameType => {
const any_frame_type = node.cast(ast.Node.AnyFrameType).?;
try writeToken(builder, any_frame_type.anyframe_token, .type);
if (any_frame_type.result) |any_frame_result| {
try writeToken(builder, any_frame_result.arrow_token, .type);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, any_frame_result.return_type });
}
},
.Defer => {
const defer_node = node.cast(ast.Node.Defer).?;
try writeToken(builder, defer_node.defer_token, .keyword);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, defer_node.payload });
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, defer_node.expr });
},
.Comptime => {
const comptime_node = node.cast(ast.Node.Comptime).?;
if (comptime_node.doc_comments) |docs| try writeDocComments(builder, handle.tree, docs);
try writeToken(builder, comptime_node.comptime_token, .keyword);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, comptime_node.expr });
},
.Nosuspend => {
const nosuspend_node = node.cast(ast.Node.Nosuspend).?;
try writeToken(builder, nosuspend_node.nosuspend_token, .keyword);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, nosuspend_node.expr });
},
.Payload => {
const payload = node.cast(ast.Node.Payload).?;
try writeToken(builder, payload.lpipe, .operator);
try writeToken(builder, payload.error_symbol.firstToken(), .variable);
try writeToken(builder, payload.rpipe, .operator);
},
.PointerPayload => {
const payload = node.cast(ast.Node.PointerPayload).?;
try writeToken(builder, payload.lpipe, .operator);
try writeToken(builder, payload.ptr_token, .operator);
try writeToken(builder, payload.value_symbol.firstToken(), .variable);
try writeToken(builder, payload.rpipe, .operator);
},
.PointerIndexPayload => {
const payload = node.cast(ast.Node.PointerIndexPayload).?;
try writeToken(builder, payload.lpipe, .operator);
try writeToken(builder, payload.ptr_token, .operator);
try writeToken(builder, payload.value_symbol.firstToken(), .variable);
if (payload.index_symbol) |index_symbol| try writeToken(builder, index_symbol.firstToken(), .variable);
try writeToken(builder, payload.rpipe, .operator);
},
.Else => {
const else_node = node.cast(ast.Node.Else).?;
try writeToken(builder, else_node.else_token, .keyword);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, else_node.payload });
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, else_node.body });
},
.Switch => {
const switch_node = node.cast(ast.Node.Switch).?;
try writeToken(builder, switch_node.switch_token, .keyword);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, switch_node.expr });
var gap_highlighter = GapHighlighter.init(builder, switch_node.expr.lastToken() + 3);
for (switch_node.casesConst()) |case_node| {
try gap_highlighter.next(case_node);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, case_node });
}
try gap_highlighter.end(node.lastToken());
},
.SwitchCase => {
const switch_case = node.cast(ast.Node.SwitchCase).?;
for (switch_case.itemsConst()) |item_node| try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, item_node });
try writeToken(builder, switch_case.arrow_token, .operator);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, switch_case.payload });
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, switch_case.expr });
},
.SwitchElse => {
const switch_else = node.cast(ast.Node.SwitchElse).?;
try writeToken(builder, switch_else.token, .keyword);
},
.While => {
const while_node = node.cast(ast.Node.While).?;
try writeToken(builder, while_node.label, .label);
try writeToken(builder, while_node.inline_token, .keyword);
try writeToken(builder, while_node.while_token, .keyword);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, while_node.condition });
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, while_node.payload });
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, while_node.continue_expr });
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, while_node.body });
if (while_node.@"else") |else_node|
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, &else_node.base });
},
.For => {
const for_node = node.cast(ast.Node.For).?;
try writeToken(builder, for_node.label, .label);
try writeToken(builder, for_node.inline_token, .keyword);
try writeToken(builder, for_node.for_token, .keyword);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, for_node.array_expr });
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, for_node.payload });
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, for_node.body });
if (for_node.@"else") |else_node|
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, &else_node.base });
},
.If => {
const if_node = node.cast(ast.Node.If).?;
try writeToken(builder, if_node.if_token, .keyword);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, if_node.condition });
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, if_node.payload });
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, if_node.body });
if (if_node.@"else") |else_node|
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, &else_node.base });
},
.ArrayInitializer => {
const array_initializer = node.cast(ast.Node.ArrayInitializer).?;
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, array_initializer.lhs });
for (array_initializer.listConst()) |elem| try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, elem });
},
.ArrayInitializerDot => {
const array_initializer = node.cast(ast.Node.ArrayInitializerDot).?;
for (array_initializer.listConst()) |elem| try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, elem });
},
.StructInitializer => {
const struct_initializer = node.cast(ast.Node.StructInitializer).?;
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, struct_initializer.lhs });
const field_token_type = if (try analysis.resolveTypeOfNode(store, arena, .{ .node = struct_initializer.lhs, .handle = handle })) |struct_type| switch (struct_type.type.data) {
.other => |type_node| if (type_node.cast(ast.Node.ContainerDecl)) |container_decl|
fieldTokenType(container_decl, handle)
else
null,
else => null,
} else null;
var gap_highlighter = GapHighlighter.init(builder, struct_initializer.lhs.lastToken() + 1);
for (struct_initializer.listConst()) |field_init_node| {
try gap_highlighter.next(field_init_node);
std.debug.assert(field_init_node.tag == .FieldInitializer);
const field_init = field_init_node.cast(ast.Node.FieldInitializer).?;
if (field_token_type) |tok_type| {
try writeToken(builder, field_init.period_token, tok_type);
try writeToken(builder, field_init.name_token, tok_type);
}
try writeToken(builder, field_init.name_token + 1, .operator);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, field_init.expr });
}
try gap_highlighter.end(struct_initializer.rtoken);
},
.StructInitializerDot => {
const struct_initializer = node.castTag(.StructInitializerDot).?;
var gap_highlighter = GapHighlighter.init(builder, struct_initializer.dot + 1);
for (struct_initializer.listConst()) |field_init_node| {
try gap_highlighter.next(field_init_node);
std.debug.assert(field_init_node.tag == .FieldInitializer);
const field_init = field_init_node.castTag(.FieldInitializer).?;
try writeToken(builder, field_init.period_token, .field);
try writeToken(builder, field_init.name_token, .field);
try writeToken(builder, field_init.name_token + 1, .operator);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, field_init.expr });
}
try gap_highlighter.end(struct_initializer.rtoken);
},
.Call => {
const call = node.cast(ast.Node.Call).?;
try writeToken(builder, call.async_token, .keyword);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, call.lhs });
if (builder.current_token) |curr_tok| {
if (curr_tok != call.lhs.lastToken() and handle.tree.token_ids[call.lhs.lastToken()] == .Identifier) {
try writeToken(builder, call.lhs.lastToken(), .function);
}
}
for (call.paramsConst()) |param| try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, param });
},
.Slice => {
const slice = node.castTag(.Slice).?;
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, slice.lhs });
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, slice.start });
try writeToken(builder, slice.start.lastToken() + 1, .operator);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, slice.end });
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, slice.sentinel });
},
.ArrayAccess => {
const arr_acc = node.castTag(.ArrayAccess).?;
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, arr_acc.lhs });
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, arr_acc.index_expr });
},
.Deref, .UnwrapOptional => {
const suffix = node.cast(ast.Node.SimpleSuffixOp).?;
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, suffix.lhs });
try writeToken(builder, suffix.rtoken, .operator);
},
.GroupedExpression => {
const grouped_expr = node.cast(ast.Node.GroupedExpression).?;
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, grouped_expr.expr });
},
.Return, .Break, .Continue => {
const cfe = node.cast(ast.Node.ControlFlowExpression).?;
try writeToken(builder, cfe.ltoken, .keyword);
switch (node.tag) {
.Break => if (cfe.getLabel()) |n| try writeToken(builder, n, .label),
.Continue => if (cfe.getLabel()) |n| try writeToken(builder, n, .label),
else => {},
}
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, cfe.getRHS() });
},
.Suspend => {
const suspend_node = node.cast(ast.Node.Suspend).?;
try writeToken(builder, suspend_node.suspend_token, .keyword);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, suspend_node.body });
},
.IntegerLiteral => {
try writeToken(builder, node.firstToken(), .number);
},
.EnumLiteral => {
const enum_literal = node.cast(ast.Node.EnumLiteral).?;
try writeToken(builder, enum_literal.dot, .tagField);
try writeToken(builder, enum_literal.name, .tagField);
},
.FloatLiteral => {
try writeToken(builder, node.firstToken(), .number);
},
.BuiltinCall => {
const builtin_call = node.cast(ast.Node.BuiltinCall).?;
try writeToken(builder, builtin_call.builtin_token, .builtin);
for (builtin_call.paramsConst()) |param|
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, param });
},
.StringLiteral, .CharLiteral => {
try writeToken(builder, node.firstToken(), .string);
},
.MultilineStringLiteral => {
const multi_line = node.cast(ast.Node.MultilineStringLiteral).?;
for (multi_line.linesConst()) |line| try writeToken(builder, line, .string);
},
.BoolLiteral, .NullLiteral, .UndefinedLiteral, .Unreachable => {
try writeToken(builder, node.firstToken(), .keywordLiteral);
},
.ErrorType => {
try writeToken(builder, node.firstToken(), .keyword);
},
.Asm => {
const asm_expr = node.cast(ast.Node.Asm).?;
try writeToken(builder, asm_expr.asm_token, .keyword);
try writeToken(builder, asm_expr.volatile_token, .keyword);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, asm_expr.template });
// TODO Inputs, outputs.
},
.AnyType => {
try writeToken(builder, node.firstToken(), .type);
},
.TestDecl => {
const test_decl = node.cast(ast.Node.TestDecl).?;
if (test_decl.doc_comments) |doc| try writeDocComments(builder, handle.tree, doc);
try writeToken(builder, test_decl.test_token, .keyword);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, test_decl.name });
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, test_decl.body_node });
},
.Catch => {
const catch_expr = node.cast(ast.Node.Catch).?;
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, catch_expr.lhs });
try writeToken(builder, catch_expr.op_token, .keyword);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, catch_expr.rhs });
},
.Add, .AddWrap, .ArrayCat, .ArrayMult, .Assign, .AssignBitAnd, .AssignBitOr, .AssignBitShiftLeft, .AssignBitShiftRight, .AssignBitXor, .AssignDiv, .AssignSub, .AssignSubWrap, .AssignMod, .AssignAdd, .AssignAddWrap, .AssignMul, .AssignMulWrap, .BangEqual, .BitAnd, .BitOr, .BitShiftLeft, .BitShiftRight, .BitXor, .BoolAnd, .BoolOr, .Div, .EqualEqual, .ErrorUnion, .GreaterOrEqual, .GreaterThan, .LessOrEqual, .LessThan, .MergeErrorSets, .Mod, .Mul, .MulWrap, .Period, .Range, .Sub, .SubWrap, .OrElse => {
const infix_op = node.cast(ast.Node.SimpleInfixOp).?;
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, infix_op.lhs });
if (node.tag != .Period) {
const token_type: TokenType = switch (node.tag) {
.BoolAnd, .BoolOr, .OrElse => .keyword,
else => .operator,
};
try writeToken(builder, infix_op.op_token, token_type);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, infix_op.rhs });
}
switch (node.tag) {
.Period => {
const rhs_str = handle.tree.tokenSlice(infix_op.rhs.firstToken());
// TODO This is basically exactly the same as what is done in analysis.resolveTypeOfNode, with the added
// writeToken code.
// Maybe we can hook into it insead? Also applies to Identifier and VarDecl
var bound_type_params = analysis.BoundTypeParams.init(&arena.allocator);
const lhs_type = try analysis.resolveFieldAccessLhsType(
store,
arena,
(try analysis.resolveTypeOfNodeInternal(store, arena, .{
.node = infix_op.lhs,
.handle = handle,
}, &bound_type_params)) orelse return,
&bound_type_params,
);
const left_type_node = switch (lhs_type.type.data) {
.other => |n| n,
else => return,
};
if (try analysis.lookupSymbolContainer(store, arena, .{ .node = left_type_node, .handle = lhs_type.handle }, rhs_str, !lhs_type.type.is_type_val)) |decl_type| {
switch (decl_type.decl.*) {
.ast_node => |decl_node| {
if (decl_node.tag == .ContainerField) {
const tok_type: ?TokenType = if (left_type_node.cast(ast.Node.ContainerDecl)) |container_decl|
fieldTokenType(container_decl, lhs_type.handle)
else if (left_type_node.tag == .Root)
TokenType.field
else
null;
if (tok_type) |tt| try writeToken(builder, infix_op.rhs.firstToken(), tt);
return;
} else if (decl_node.tag == .ErrorTag) {
try writeToken(builder, infix_op.rhs.firstToken(), .errorTag);
}
},
else => {},
}
if (try decl_type.resolveType(store, arena, &bound_type_params)) |resolved_type| {
try colorIdentifierBasedOnType(builder, resolved_type, infix_op.rhs.firstToken(), .{});
}
}
},
else => {},
}
},
.SliceType => {
const slice_type = node.castTag(.SliceType).?;
const ptr_info = slice_type.ptr_info;
if (ptr_info.align_info) |align_info| {
try writeToken(builder, slice_type.op_token + 2, .keyword);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, align_info.node });
}
try writeToken(builder, ptr_info.const_token, .keyword);
try writeToken(builder, ptr_info.volatile_token, .keyword);
try writeToken(builder, ptr_info.allowzero_token, .keyword);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, slice_type.rhs });
},
.PtrType => {
const pointer_type = node.castTag(.PtrType).?;
const tok_ids = builder.handle.tree.token_ids;
const ptr_info = switch (tok_ids[pointer_type.op_token]) {
.AsteriskAsterisk => pointer_type.rhs.castTag(.PtrType).?.ptr_info,
else => pointer_type.ptr_info,
};
const rhs = switch (tok_ids[pointer_type.op_token]) {
.AsteriskAsterisk => pointer_type.rhs.castTag(.PtrType).?.rhs,
else => pointer_type.rhs,
};
const off = switch (tok_ids[pointer_type.op_token]) {
.Asterisk, .AsteriskAsterisk => blk: {
try writeToken(builder, pointer_type.op_token, .operator);
break :blk pointer_type.op_token + 1;
},
.LBracket => blk: {
try writeToken(builder, pointer_type.op_token + 1, .operator);
const is_c_ptr = tok_ids[pointer_type.op_token + 2] == .Identifier;
if (is_c_ptr) {
try writeToken(builder, pointer_type.op_token + 2, .operator);
}
if (ptr_info.sentinel) |sentinel| {
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, sentinel });
break :blk sentinel.lastToken() + 2;
}
break :blk pointer_type.op_token + 3 + @boolToInt(is_c_ptr);
},
else => 0,
};
if (ptr_info.align_info) |align_info| {
try writeToken(builder, off, .keyword);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, align_info.node });
}
try writeToken(builder, ptr_info.const_token, .keyword);
try writeToken(builder, ptr_info.volatile_token, .keyword);
try writeToken(builder, ptr_info.allowzero_token, .keyword);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, rhs });
},
.ArrayType => {
const array_type = node.castTag(.ArrayType).?;
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, array_type.len_expr });
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, array_type.rhs });
},
.ArrayTypeSentinel => {
const array_type = node.castTag(.ArrayTypeSentinel).?;
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, array_type.len_expr });
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, array_type.sentinel });
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, array_type.rhs });
},
.AddressOf, .Await, .BitNot, .BoolNot, .OptionalType, .Negation, .NegationWrap, .Resume, .Try => {
const prefix_op = node.cast(ast.Node.SimplePrefixOp).?;
const tok_type: TokenType = switch (node.tag) {
.Try, .Await, .Resume => .keyword,
else => .operator,
};
try writeToken(builder, prefix_op.op_token, tok_type);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, prefix_op.rhs });
},
else => {},
}
}
// TODO Range version, edit version.
pub fn writeAllSemanticTokens(arena: *std.heap.ArenaAllocator, store: *DocumentStore, handle: *DocumentStore.Handle, encoding: offsets.Encoding) ![]u32 {
var builder = Builder.init(arena.child_allocator, handle, encoding);
try writeNodeTokens(&builder, arena, store, &handle.tree.root_node.base);
return builder.toOwnedSlice();
} | src/semantic_tokens.zig |
const Trie = @This();
const std = @import("std");
const mem = std.mem;
const leb = std.leb;
const log = std.log.scoped(.macho);
const macho = std.macho;
const testing = std.testing;
const assert = std.debug.assert;
const Allocator = mem.Allocator;
pub const Node = struct {
base: *Trie,
/// Terminal info associated with this node.
/// If this node is not a terminal node, info is null.
terminal_info: ?struct {
/// Export flags associated with this exported symbol.
export_flags: u64,
/// VM address offset wrt to the section this symbol is defined against.
vmaddr_offset: u64,
} = null,
/// Offset of this node in the trie output byte stream.
trie_offset: ?u64 = null,
/// List of all edges originating from this node.
edges: std.ArrayListUnmanaged(Edge) = .{},
node_dirty: bool = true,
/// Edge connecting to nodes in the trie.
pub const Edge = struct {
from: *Node,
to: *Node,
label: []u8,
fn deinit(self: *Edge, allocator: *Allocator) void {
self.to.deinit(allocator);
allocator.destroy(self.to);
allocator.free(self.label);
self.from = undefined;
self.to = undefined;
self.label = undefined;
}
};
fn deinit(self: *Node, allocator: *Allocator) void {
for (self.edges.items) |*edge| {
edge.deinit(allocator);
}
self.edges.deinit(allocator);
}
/// Inserts a new node starting from `self`.
fn put(self: *Node, allocator: *Allocator, label: []const u8) !*Node {
// Check for match with edges from this node.
for (self.edges.items) |*edge| {
const match = mem.indexOfDiff(u8, edge.label, label) orelse return edge.to;
if (match == 0) continue;
if (match == edge.label.len) return edge.to.put(allocator, label[match..]);
// Found a match, need to splice up nodes.
// From: A -> B
// To: A -> C -> B
const mid = try allocator.create(Node);
mid.* = .{ .base = self.base };
var to_label = try allocator.dupe(u8, edge.label[match..]);
allocator.free(edge.label);
const to_node = edge.to;
edge.to = mid;
edge.label = try allocator.dupe(u8, label[0..match]);
self.base.node_count += 1;
try mid.edges.append(allocator, .{
.from = mid,
.to = to_node,
.label = to_label,
});
return if (match == label.len) to_node else mid.put(allocator, label[match..]);
}
// Add a new node.
const node = try allocator.create(Node);
node.* = .{ .base = self.base };
self.base.node_count += 1;
try self.edges.append(allocator, .{
.from = self,
.to = node,
.label = try allocator.dupe(u8, label),
});
return node;
}
/// Recursively parses the node from the input byte stream.
fn read(self: *Node, allocator: *Allocator, reader: anytype) Trie.ReadError!usize {
self.node_dirty = true;
const trie_offset = try reader.context.getPos();
self.trie_offset = trie_offset;
var nread: usize = 0;
const node_size = try leb.readULEB128(u64, reader);
if (node_size > 0) {
const export_flags = try leb.readULEB128(u64, reader);
// TODO Parse special flags.
assert(export_flags & macho.EXPORT_SYMBOL_FLAGS_REEXPORT == 0 and
export_flags & macho.EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER == 0);
const vmaddr_offset = try leb.readULEB128(u64, reader);
self.terminal_info = .{
.export_flags = export_flags,
.vmaddr_offset = vmaddr_offset,
};
}
const nedges = try reader.readByte();
self.base.node_count += nedges;
nread += (try reader.context.getPos()) - trie_offset;
var i: usize = 0;
while (i < nedges) : (i += 1) {
const edge_start_pos = try reader.context.getPos();
const label = blk: {
var label_buf = std.ArrayList(u8).init(allocator);
while (true) {
const next = try reader.readByte();
if (next == @as(u8, 0))
break;
try label_buf.append(next);
}
break :blk label_buf.toOwnedSlice();
};
const seek_to = try leb.readULEB128(u64, reader);
const return_pos = try reader.context.getPos();
nread += return_pos - edge_start_pos;
try reader.context.seekTo(seek_to);
const node = try allocator.create(Node);
node.* = .{ .base = self.base };
nread += try node.read(allocator, reader);
try self.edges.append(allocator, .{
.from = self,
.to = node,
.label = label,
});
try reader.context.seekTo(return_pos);
}
return nread;
}
/// Writes this node to a byte stream.
/// The children of this node *are* not written to the byte stream
/// recursively. To write all nodes to a byte stream in sequence,
/// iterate over `Trie.ordered_nodes` and call this method on each node.
/// This is one of the requirements of the MachO.
/// Panics if `finalize` was not called before calling this method.
fn write(self: Node, writer: anytype) !void {
assert(!self.node_dirty);
if (self.terminal_info) |info| {
// Terminal node info: encode export flags and vmaddr offset of this symbol.
var info_buf: [@sizeOf(u64) * 2]u8 = undefined;
var info_stream = std.io.fixedBufferStream(&info_buf);
// TODO Implement for special flags.
assert(info.export_flags & macho.EXPORT_SYMBOL_FLAGS_REEXPORT == 0 and
info.export_flags & macho.EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER == 0);
try leb.writeULEB128(info_stream.writer(), info.export_flags);
try leb.writeULEB128(info_stream.writer(), info.vmaddr_offset);
// Encode the size of the terminal node info.
var size_buf: [@sizeOf(u64)]u8 = undefined;
var size_stream = std.io.fixedBufferStream(&size_buf);
try leb.writeULEB128(size_stream.writer(), info_stream.pos);
// Now, write them to the output stream.
try writer.writeAll(size_buf[0..size_stream.pos]);
try writer.writeAll(info_buf[0..info_stream.pos]);
} else {
// Non-terminal node is delimited by 0 byte.
try writer.writeByte(0);
}
// Write number of edges (max legal number of edges is 256).
try writer.writeByte(@intCast(u8, self.edges.items.len));
for (self.edges.items) |edge| {
// Write edge label and offset to next node in trie.
try writer.writeAll(edge.label);
try writer.writeByte(0);
try leb.writeULEB128(writer, edge.to.trie_offset.?);
}
}
const FinalizeResult = struct {
/// Current size of this node in bytes.
node_size: u64,
/// True if the trie offset of this node in the output byte stream
/// would need updating; false otherwise.
updated: bool,
};
/// Updates offset of this node in the output byte stream.
fn finalize(self: *Node, offset_in_trie: u64) !FinalizeResult {
var stream = std.io.countingWriter(std.io.null_writer);
var writer = stream.writer();
var node_size: u64 = 0;
if (self.terminal_info) |info| {
try leb.writeULEB128(writer, info.export_flags);
try leb.writeULEB128(writer, info.vmaddr_offset);
try leb.writeULEB128(writer, stream.bytes_written);
} else {
node_size += 1; // 0x0 for non-terminal nodes
}
node_size += 1; // 1 byte for edge count
for (self.edges.items) |edge| {
const next_node_offset = edge.to.trie_offset orelse 0;
node_size += edge.label.len + 1;
try leb.writeULEB128(writer, next_node_offset);
}
const trie_offset = self.trie_offset orelse 0;
const updated = offset_in_trie != trie_offset;
self.trie_offset = offset_in_trie;
self.node_dirty = false;
node_size += stream.bytes_written;
return FinalizeResult{ .node_size = node_size, .updated = updated };
}
};
/// The root node of the trie.
root: ?*Node = null,
/// If you want to access nodes ordered in DFS fashion,
/// you should call `finalize` first since the nodes
/// in this container are not guaranteed to not be stale
/// if more insertions took place after the last `finalize`
/// call.
ordered_nodes: std.ArrayListUnmanaged(*Node) = .{},
/// The size of the trie in bytes.
/// This value may be outdated if there were additional
/// insertions performed after `finalize` was called.
/// Call `finalize` before accessing this value to ensure
/// it is up-to-date.
size: u64 = 0,
/// Number of nodes currently in the trie.
node_count: usize = 0,
trie_dirty: bool = true,
/// Export symbol that is to be placed in the trie.
pub const ExportSymbol = struct {
/// Name of the symbol.
name: []const u8,
/// Offset of this symbol's virtual memory address from the beginning
/// of the __TEXT segment.
vmaddr_offset: u64,
/// Export flags of this exported symbol.
export_flags: u64,
};
/// Insert a symbol into the trie, updating the prefixes in the process.
/// This operation may change the layout of the trie by splicing edges in
/// certain circumstances.
pub fn put(self: *Trie, allocator: *Allocator, symbol: ExportSymbol) !void {
try self.createRoot(allocator);
const node = try self.root.?.put(allocator, symbol.name);
node.terminal_info = .{
.vmaddr_offset = symbol.vmaddr_offset,
.export_flags = symbol.export_flags,
};
self.trie_dirty = true;
}
/// Finalizes this trie for writing to a byte stream.
/// This step performs multiple passes through the trie ensuring
/// there are no gaps after every `Node` is ULEB128 encoded.
/// Call this method before trying to `write` the trie to a byte stream.
pub fn finalize(self: *Trie, allocator: *Allocator) !void {
if (!self.trie_dirty) return;
self.ordered_nodes.shrinkRetainingCapacity(0);
try self.ordered_nodes.ensureTotalCapacity(allocator, self.node_count);
var fifo = std.fifo.LinearFifo(*Node, .Dynamic).init(allocator);
defer fifo.deinit();
try fifo.writeItem(self.root.?);
while (fifo.readItem()) |next| {
for (next.edges.items) |*edge| {
try fifo.writeItem(edge.to);
}
self.ordered_nodes.appendAssumeCapacity(next);
}
var more: bool = true;
while (more) {
self.size = 0;
more = false;
for (self.ordered_nodes.items) |node| {
const res = try node.finalize(self.size);
self.size += res.node_size;
if (res.updated) more = true;
}
}
self.trie_dirty = false;
}
const ReadError = error{
OutOfMemory,
EndOfStream,
Overflow,
};
/// Parse the trie from a byte stream.
pub fn read(self: *Trie, allocator: *Allocator, reader: anytype) ReadError!usize {
try self.createRoot(allocator);
return self.root.?.read(allocator, reader);
}
/// Write the trie to a byte stream.
/// Panics if the trie was not finalized using `finalize` before calling this method.
pub fn write(self: Trie, writer: anytype) !u64 {
assert(!self.trie_dirty);
var counting_writer = std.io.countingWriter(writer);
for (self.ordered_nodes.items) |node| {
try node.write(counting_writer.writer());
}
return counting_writer.bytes_written;
}
pub fn deinit(self: *Trie, allocator: *Allocator) void {
if (self.root) |root| {
root.deinit(allocator);
allocator.destroy(root);
}
self.ordered_nodes.deinit(allocator);
}
fn createRoot(self: *Trie, allocator: *Allocator) !void {
if (self.root == null) {
const root = try allocator.create(Node);
root.* = .{ .base = self };
self.root = root;
self.node_count += 1;
}
}
test "Trie node count" {
var gpa = testing.allocator;
var trie: Trie = .{};
defer trie.deinit(gpa);
try testing.expectEqual(trie.node_count, 0);
try testing.expect(trie.root == null);
try trie.put(gpa, .{
.name = "_main",
.vmaddr_offset = 0,
.export_flags = 0,
});
try testing.expectEqual(trie.node_count, 2);
// Inserting the same node shouldn't update the trie.
try trie.put(gpa, .{
.name = "_main",
.vmaddr_offset = 0,
.export_flags = 0,
});
try testing.expectEqual(trie.node_count, 2);
try trie.put(gpa, .{
.name = "__mh_execute_header",
.vmaddr_offset = 0x1000,
.export_flags = 0,
});
try testing.expectEqual(trie.node_count, 4);
// Inserting the same node shouldn't update the trie.
try trie.put(gpa, .{
.name = "__mh_execute_header",
.vmaddr_offset = 0x1000,
.export_flags = 0,
});
try testing.expectEqual(trie.node_count, 4);
try trie.put(gpa, .{
.name = "_main",
.vmaddr_offset = 0,
.export_flags = 0,
});
try testing.expectEqual(trie.node_count, 4);
}
test "Trie basic" {
var gpa = testing.allocator;
var trie: Trie = .{};
defer trie.deinit(gpa);
// root --- _st ---> node
try trie.put(gpa, .{
.name = "_st",
.vmaddr_offset = 0,
.export_flags = 0,
});
try testing.expect(trie.root.?.edges.items.len == 1);
try testing.expect(mem.eql(u8, trie.root.?.edges.items[0].label, "_st"));
{
// root --- _st ---> node --- art ---> node
try trie.put(gpa, .{
.name = "_start",
.vmaddr_offset = 0,
.export_flags = 0,
});
try testing.expect(trie.root.?.edges.items.len == 1);
const nextEdge = &trie.root.?.edges.items[0];
try testing.expect(mem.eql(u8, nextEdge.label, "_st"));
try testing.expect(nextEdge.to.edges.items.len == 1);
try testing.expect(mem.eql(u8, nextEdge.to.edges.items[0].label, "art"));
}
{
// root --- _ ---> node --- st ---> node --- art ---> node
// |
// | --- main ---> node
try trie.put(gpa, .{
.name = "_main",
.vmaddr_offset = 0,
.export_flags = 0,
});
try testing.expect(trie.root.?.edges.items.len == 1);
const nextEdge = &trie.root.?.edges.items[0];
try testing.expect(mem.eql(u8, nextEdge.label, "_"));
try testing.expect(nextEdge.to.edges.items.len == 2);
try testing.expect(mem.eql(u8, nextEdge.to.edges.items[0].label, "st"));
try testing.expect(mem.eql(u8, nextEdge.to.edges.items[1].label, "main"));
const nextNextEdge = &nextEdge.to.edges.items[0];
try testing.expect(mem.eql(u8, nextNextEdge.to.edges.items[0].label, "art"));
}
}
test "write Trie to a byte stream" {
var gpa = testing.allocator;
var trie: Trie = .{};
defer trie.deinit(gpa);
try trie.put(gpa, .{
.name = "__mh_execute_header",
.vmaddr_offset = 0,
.export_flags = 0,
});
try trie.put(gpa, .{
.name = "_main",
.vmaddr_offset = 0x1000,
.export_flags = 0,
});
try trie.finalize(gpa);
try trie.finalize(gpa); // Finalizing mulitple times is a nop subsequently unless we add new nodes.
const exp_buffer = [_]u8{
0x0, 0x1, // node root
0x5f, 0x0, 0x5, // edge '_'
0x0, 0x2, // non-terminal node
0x5f, 0x6d, 0x68, 0x5f, 0x65, 0x78, 0x65, 0x63, 0x75, 0x74, // edge '_mh_execute_header'
0x65, 0x5f, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x0, 0x21, // edge '_mh_execute_header'
0x6d, 0x61, 0x69, 0x6e, 0x0, 0x25, // edge 'main'
0x2, 0x0, 0x0, 0x0, // terminal node
0x3, 0x0, 0x80, 0x20, 0x0, // terminal node
};
var buffer = try gpa.alloc(u8, trie.size);
defer gpa.free(buffer);
var stream = std.io.fixedBufferStream(buffer);
{
const nwritten = try trie.write(stream.writer());
try testing.expect(nwritten == trie.size);
try testing.expect(mem.eql(u8, buffer, &exp_buffer));
}
{
// Writing finalized trie again should yield the same result.
try stream.seekTo(0);
const nwritten = try trie.write(stream.writer());
try testing.expect(nwritten == trie.size);
try testing.expect(mem.eql(u8, buffer, &exp_buffer));
}
}
test "parse Trie from byte stream" {
var gpa = testing.allocator;
const in_buffer = [_]u8{
0x0, 0x1, // node root
0x5f, 0x0, 0x5, // edge '_'
0x0, 0x2, // non-terminal node
0x5f, 0x6d, 0x68, 0x5f, 0x65, 0x78, 0x65, 0x63, 0x75, 0x74, // edge '_mh_execute_header'
0x65, 0x5f, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x0, 0x21, // edge '_mh_execute_header'
0x6d, 0x61, 0x69, 0x6e, 0x0, 0x25, // edge 'main'
0x2, 0x0, 0x0, 0x0, // terminal node
0x3, 0x0, 0x80, 0x20, 0x0, // terminal node
};
var in_stream = std.io.fixedBufferStream(&in_buffer);
var trie: Trie = .{};
defer trie.deinit(gpa);
const nread = try trie.read(gpa, in_stream.reader());
try testing.expect(nread == in_buffer.len);
try trie.finalize(gpa);
var out_buffer = try gpa.alloc(u8, trie.size);
defer gpa.free(out_buffer);
var out_stream = std.io.fixedBufferStream(out_buffer);
const nwritten = try trie.write(out_stream.writer());
try testing.expect(nwritten == trie.size);
try testing.expect(mem.eql(u8, &in_buffer, out_buffer));
} | src/MachO/Trie.zig |
const std = @import("../../std.zig");
const assert = std.debug.assert;
const maxInt = std.math.maxInt;
// See: https://opensource.apple.com/source/xnu/xnu-6153.141.1/bsd/sys/_types.h.auto.html
// TODO: audit mode_t/pid_t, should likely be u16/i32
pub const fd_t = c_int;
pub const pid_t = c_int;
pub const mode_t = c_uint;
pub const uid_t = u32;
pub const gid_t = u32;
pub const in_port_t = u16;
pub const sa_family_t = u8;
pub const socklen_t = u32;
pub const sockaddr = extern struct {
len: u8,
family: sa_family_t,
data: [14]u8,
};
pub const sockaddr_in = extern struct {
len: u8 = @sizeOf(sockaddr_in),
family: sa_family_t = AF_INET,
port: in_port_t,
addr: u32,
zero: [8]u8 = [8]u8{ 0, 0, 0, 0, 0, 0, 0, 0 },
};
pub const sockaddr_in6 = extern struct {
len: u8 = @sizeOf(sockaddr_in6),
family: sa_family_t = AF_INET6,
port: in_port_t,
flowinfo: u32,
addr: [16]u8,
scope_id: u32,
};
/// UNIX domain socket
pub const sockaddr_un = extern struct {
len: u8 = @sizeOf(sockaddr_un),
family: sa_family_t = AF_UNIX,
path: [104]u8,
};
pub const timeval = extern struct {
tv_sec: c_long,
tv_usec: i32,
};
pub const timezone = extern struct {
tz_minuteswest: i32,
tz_dsttime: i32,
};
pub const mach_timebase_info_data = extern struct {
numer: u32,
denom: u32,
};
pub const off_t = i64;
pub const ino_t = u64;
pub const Flock = extern struct {
l_start: off_t,
l_len: off_t,
l_pid: pid_t,
l_type: i16,
l_whence: i16,
};
pub const libc_stat = extern struct {
dev: i32,
mode: u16,
nlink: u16,
ino: ino_t,
uid: uid_t,
gid: gid_t,
rdev: i32,
atimesec: isize,
atimensec: isize,
mtimesec: isize,
mtimensec: isize,
ctimesec: isize,
ctimensec: isize,
birthtimesec: isize,
birthtimensec: isize,
size: off_t,
blocks: i64,
blksize: i32,
flags: u32,
gen: u32,
lspare: i32,
qspare: [2]i64,
pub fn atime(self: @This()) timespec {
return timespec{
.tv_sec = self.atimesec,
.tv_nsec = self.atimensec,
};
}
pub fn mtime(self: @This()) timespec {
return timespec{
.tv_sec = self.mtimesec,
.tv_nsec = self.mtimensec,
};
}
pub fn ctime(self: @This()) timespec {
return timespec{
.tv_sec = self.ctimesec,
.tv_nsec = self.ctimensec,
};
}
};
pub const timespec = extern struct {
tv_sec: isize,
tv_nsec: isize,
};
pub const sigset_t = u32;
pub const empty_sigset: sigset_t = 0;
pub const SIG_ERR = @intToPtr(?Sigaction.sigaction_fn, maxInt(usize));
pub const SIG_DFL = @intToPtr(?Sigaction.sigaction_fn, 0);
pub const SIG_IGN = @intToPtr(?Sigaction.sigaction_fn, 1);
pub const SIG_HOLD = @intToPtr(?Sigaction.sigaction_fn, 5);
pub const siginfo_t = extern struct {
signo: c_int,
errno: c_int,
code: c_int,
pid: pid_t,
uid: uid_t,
status: c_int,
addr: *c_void,
value: extern union {
int: c_int,
ptr: *c_void,
},
si_band: c_long,
_pad: [7]c_ulong,
};
/// Renamed from `sigaction` to `Sigaction` to avoid conflict with function name.
pub const Sigaction = extern struct {
pub const handler_fn = fn (c_int) callconv(.C) void;
pub const sigaction_fn = fn (c_int, *const siginfo_t, ?*const c_void) callconv(.C) void;
handler: extern union {
handler: ?handler_fn,
sigaction: ?sigaction_fn,
},
mask: sigset_t,
flags: c_uint,
};
pub const dirent = extern struct {
d_ino: usize,
d_seekoff: usize,
d_reclen: u16,
d_namlen: u16,
d_type: u8,
d_name: u8, // field address is address of first byte of name
pub fn reclen(self: dirent) u16 {
return self.d_reclen;
}
};
/// Renamed from `kevent` to `Kevent` to avoid conflict with function name.
pub const Kevent = extern struct {
ident: usize,
filter: i16,
flags: u16,
fflags: u32,
data: isize,
udata: usize,
};
// sys/types.h on macos uses #pragma pack(4) so these checks are
// to make sure the struct is laid out the same. These values were
// produced from C code using the offsetof macro.
comptime {
assert(@byteOffsetOf(Kevent, "ident") == 0);
assert(@byteOffsetOf(Kevent, "filter") == 8);
assert(@byteOffsetOf(Kevent, "flags") == 10);
assert(@byteOffsetOf(Kevent, "fflags") == 12);
assert(@byteOffsetOf(Kevent, "data") == 16);
assert(@byteOffsetOf(Kevent, "udata") == 24);
}
pub const kevent64_s = extern struct {
ident: u64,
filter: i16,
flags: u16,
fflags: u32,
data: i64,
udata: u64,
ext: [2]u64,
};
// sys/types.h on macos uses #pragma pack() so these checks are
// to make sure the struct is laid out the same. These values were
// produced from C code using the offsetof macro.
comptime {
assert(@byteOffsetOf(kevent64_s, "ident") == 0);
assert(@byteOffsetOf(kevent64_s, "filter") == 8);
assert(@byteOffsetOf(kevent64_s, "flags") == 10);
assert(@byteOffsetOf(kevent64_s, "fflags") == 12);
assert(@byteOffsetOf(kevent64_s, "data") == 16);
assert(@byteOffsetOf(kevent64_s, "udata") == 24);
assert(@byteOffsetOf(kevent64_s, "ext") == 32);
}
pub const mach_port_t = c_uint;
pub const clock_serv_t = mach_port_t;
pub const clock_res_t = c_int;
pub const mach_port_name_t = natural_t;
pub const natural_t = c_uint;
pub const mach_timespec_t = extern struct {
tv_sec: c_uint,
tv_nsec: clock_res_t,
};
pub const kern_return_t = c_int;
pub const host_t = mach_port_t;
pub const CALENDAR_CLOCK = 1;
pub const PATH_MAX = 1024;
pub const STDIN_FILENO = 0;
pub const STDOUT_FILENO = 1;
pub const STDERR_FILENO = 2;
/// [MC2] no permissions
pub const PROT_NONE = 0x00;
/// [MC2] pages can be read
pub const PROT_READ = 0x01;
/// [MC2] pages can be written
pub const PROT_WRITE = 0x02;
/// [MC2] pages can be executed
pub const PROT_EXEC = 0x04;
/// allocated from memory, swap space
pub const MAP_ANONYMOUS = 0x1000;
/// map from file (default)
pub const MAP_FILE = 0x0000;
/// interpret addr exactly
pub const MAP_FIXED = 0x0010;
/// region may contain semaphores
pub const MAP_HASSEMAPHORE = 0x0200;
/// changes are private
pub const MAP_PRIVATE = 0x0002;
/// share changes
pub const MAP_SHARED = 0x0001;
/// don't cache pages for this mapping
pub const MAP_NOCACHE = 0x0400;
/// don't reserve needed swap area
pub const MAP_NORESERVE = 0x0040;
pub const MAP_FAILED = @intToPtr(*c_void, maxInt(usize));
/// [XSI] no hang in wait/no child to reap
pub const WNOHANG = 0x00000001;
/// [XSI] notify on stop, untraced child
pub const WUNTRACED = 0x00000002;
/// take signal on signal stack
pub const SA_ONSTACK = 0x0001;
/// restart system on signal return
pub const SA_RESTART = 0x0002;
/// reset to SIG_DFL when taking signal
pub const SA_RESETHAND = 0x0004;
/// do not generate SIGCHLD on child stop
pub const SA_NOCLDSTOP = 0x0008;
/// don't mask the signal we're delivering
pub const SA_NODEFER = 0x0010;
/// don't keep zombies around
pub const SA_NOCLDWAIT = 0x0020;
/// signal handler with SA_SIGINFO args
pub const SA_SIGINFO = 0x0040;
/// do not bounce off kernel's sigtramp
pub const SA_USERTRAMP = 0x0100;
/// signal handler with SA_SIGINFO args with 64bit regs information
pub const SA_64REGSET = 0x0200;
pub const O_PATH = 0x0000;
pub const F_OK = 0;
pub const X_OK = 1;
pub const W_OK = 2;
pub const R_OK = 4;
/// open for reading only
pub const O_RDONLY = 0x0000;
/// open for writing only
pub const O_WRONLY = 0x0001;
/// open for reading and writing
pub const O_RDWR = 0x0002;
/// do not block on open or for data to become available
pub const O_NONBLOCK = 0x0004;
/// append on each write
pub const O_APPEND = 0x0008;
/// create file if it does not exist
pub const O_CREAT = 0x0200;
/// truncate size to 0
pub const O_TRUNC = 0x0400;
/// error if O_CREAT and the file exists
pub const O_EXCL = 0x0800;
/// atomically obtain a shared lock
pub const O_SHLOCK = 0x0010;
/// atomically obtain an exclusive lock
pub const O_EXLOCK = 0x0020;
/// do not follow symlinks
pub const O_NOFOLLOW = 0x0100;
/// allow open of symlinks
pub const O_SYMLINK = 0x200000;
/// descriptor requested for event notifications only
pub const O_EVTONLY = 0x8000;
/// mark as close-on-exec
pub const O_CLOEXEC = 0x1000000;
pub const O_ACCMODE = 3;
pub const O_ALERT = 536870912;
pub const O_ASYNC = 64;
pub const O_DIRECTORY = 1048576;
pub const O_DP_GETRAWENCRYPTED = 1;
pub const O_DP_GETRAWUNENCRYPTED = 2;
pub const O_DSYNC = 4194304;
pub const O_FSYNC = O_SYNC;
pub const O_NOCTTY = 131072;
pub const O_POPUP = 2147483648;
pub const O_SYNC = 128;
pub const SEEK_SET = 0x0;
pub const SEEK_CUR = 0x1;
pub const SEEK_END = 0x2;
pub const DT_UNKNOWN = 0;
pub const DT_FIFO = 1;
pub const DT_CHR = 2;
pub const DT_DIR = 4;
pub const DT_BLK = 6;
pub const DT_REG = 8;
pub const DT_LNK = 10;
pub const DT_SOCK = 12;
pub const DT_WHT = 14;
/// block specified signal set
pub const SIG_BLOCK = 1;
/// unblock specified signal set
pub const SIG_UNBLOCK = 2;
/// set specified signal set
pub const SIG_SETMASK = 3;
/// hangup
pub const SIGHUP = 1;
/// interrupt
pub const SIGINT = 2;
/// quit
pub const SIGQUIT = 3;
/// illegal instruction (not reset when caught)
pub const SIGILL = 4;
/// trace trap (not reset when caught)
pub const SIGTRAP = 5;
/// abort()
pub const SIGABRT = 6;
/// pollable event ([XSR] generated, not supported)
pub const SIGPOLL = 7;
/// compatibility
pub const SIGIOT = SIGABRT;
/// EMT instruction
pub const SIGEMT = 7;
/// floating point exception
pub const SIGFPE = 8;
/// kill (cannot be caught or ignored)
pub const SIGKILL = 9;
/// bus error
pub const SIGBUS = 10;
/// segmentation violation
pub const SIGSEGV = 11;
/// bad argument to system call
pub const SIGSYS = 12;
/// write on a pipe with no one to read it
pub const SIGPIPE = 13;
/// alarm clock
pub const SIGALRM = 14;
/// software termination signal from kill
pub const SIGTERM = 15;
/// urgent condition on IO channel
pub const SIGURG = 16;
/// sendable stop signal not from tty
pub const SIGSTOP = 17;
/// stop signal from tty
pub const SIGTSTP = 18;
/// continue a stopped process
pub const SIGCONT = 19;
/// to parent on child stop or exit
pub const SIGCHLD = 20;
/// to readers pgrp upon background tty read
pub const SIGTTIN = 21;
/// like TTIN for output if (tp->t_local<OSTOP)
pub const SIGTTOU = 22;
/// input/output possible signal
pub const SIGIO = 23;
/// exceeded CPU time limit
pub const SIGXCPU = 24;
/// exceeded file size limit
pub const SIGXFSZ = 25;
/// virtual time alarm
pub const SIGVTALRM = 26;
/// profiling time alarm
pub const SIGPROF = 27;
/// window size changes
pub const SIGWINCH = 28;
/// information request
pub const SIGINFO = 29;
/// user defined signal 1
pub const SIGUSR1 = 30;
/// user defined signal 2
pub const SIGUSR2 = 31;
/// no flag value
pub const KEVENT_FLAG_NONE = 0x000;
/// immediate timeout
pub const KEVENT_FLAG_IMMEDIATE = 0x001;
/// output events only include change
pub const KEVENT_FLAG_ERROR_EVENTS = 0x002;
/// add event to kq (implies enable)
pub const EV_ADD = 0x0001;
/// delete event from kq
pub const EV_DELETE = 0x0002;
/// enable event
pub const EV_ENABLE = 0x0004;
/// disable event (not reported)
pub const EV_DISABLE = 0x0008;
/// only report one occurrence
pub const EV_ONESHOT = 0x0010;
/// clear event state after reporting
pub const EV_CLEAR = 0x0020;
/// force immediate event output
/// ... with or without EV_ERROR
/// ... use KEVENT_FLAG_ERROR_EVENTS
/// on syscalls supporting flags
pub const EV_RECEIPT = 0x0040;
/// disable event after reporting
pub const EV_DISPATCH = 0x0080;
/// unique kevent per udata value
pub const EV_UDATA_SPECIFIC = 0x0100;
/// ... in combination with EV_DELETE
/// will defer delete until udata-specific
/// event enabled. EINPROGRESS will be
/// returned to indicate the deferral
pub const EV_DISPATCH2 = EV_DISPATCH | EV_UDATA_SPECIFIC;
/// report that source has vanished
/// ... only valid with EV_DISPATCH2
pub const EV_VANISHED = 0x0200;
/// reserved by system
pub const EV_SYSFLAGS = 0xF000;
/// filter-specific flag
pub const EV_FLAG0 = 0x1000;
/// filter-specific flag
pub const EV_FLAG1 = 0x2000;
/// EOF detected
pub const EV_EOF = 0x8000;
/// error, data contains errno
pub const EV_ERROR = 0x4000;
pub const EV_POLL = EV_FLAG0;
pub const EV_OOBAND = EV_FLAG1;
pub const EVFILT_READ = -1;
pub const EVFILT_WRITE = -2;
/// attached to aio requests
pub const EVFILT_AIO = -3;
/// attached to vnodes
pub const EVFILT_VNODE = -4;
/// attached to struct proc
pub const EVFILT_PROC = -5;
/// attached to struct proc
pub const EVFILT_SIGNAL = -6;
/// timers
pub const EVFILT_TIMER = -7;
/// Mach portsets
pub const EVFILT_MACHPORT = -8;
/// Filesystem events
pub const EVFILT_FS = -9;
/// User events
pub const EVFILT_USER = -10;
/// Virtual memory events
pub const EVFILT_VM = -12;
/// Exception events
pub const EVFILT_EXCEPT = -15;
pub const EVFILT_SYSCOUNT = 17;
/// On input, NOTE_TRIGGER causes the event to be triggered for output.
pub const NOTE_TRIGGER = 0x01000000;
/// ignore input fflags
pub const NOTE_FFNOP = 0x00000000;
/// and fflags
pub const NOTE_FFAND = 0x40000000;
/// or fflags
pub const NOTE_FFOR = 0x80000000;
/// copy fflags
pub const NOTE_FFCOPY = 0xc0000000;
/// mask for operations
pub const NOTE_FFCTRLMASK = 0xc0000000;
pub const NOTE_FFLAGSMASK = 0x00ffffff;
/// low water mark
pub const NOTE_LOWAT = 0x00000001;
/// OOB data
pub const NOTE_OOB = 0x00000002;
/// vnode was removed
pub const NOTE_DELETE = 0x00000001;
/// data contents changed
pub const NOTE_WRITE = 0x00000002;
/// size increased
pub const NOTE_EXTEND = 0x00000004;
/// attributes changed
pub const NOTE_ATTRIB = 0x00000008;
/// link count changed
pub const NOTE_LINK = 0x00000010;
/// vnode was renamed
pub const NOTE_RENAME = 0x00000020;
/// vnode access was revoked
pub const NOTE_REVOKE = 0x00000040;
/// No specific vnode event: to test for EVFILT_READ activation
pub const NOTE_NONE = 0x00000080;
/// vnode was unlocked by flock(2)
pub const NOTE_FUNLOCK = 0x00000100;
/// process exited
pub const NOTE_EXIT = 0x80000000;
/// process forked
pub const NOTE_FORK = 0x40000000;
/// process exec'd
pub const NOTE_EXEC = 0x20000000;
/// shared with EVFILT_SIGNAL
pub const NOTE_SIGNAL = 0x08000000;
/// exit status to be returned, valid for child process only
pub const NOTE_EXITSTATUS = 0x04000000;
/// provide details on reasons for exit
pub const NOTE_EXIT_DETAIL = 0x02000000;
/// mask for signal & exit status
pub const NOTE_PDATAMASK = 0x000fffff;
pub const NOTE_PCTRLMASK = (~NOTE_PDATAMASK);
pub const NOTE_EXIT_DETAIL_MASK = 0x00070000;
pub const NOTE_EXIT_DECRYPTFAIL = 0x00010000;
pub const NOTE_EXIT_MEMORY = 0x00020000;
pub const NOTE_EXIT_CSERROR = 0x00040000;
/// will react on memory pressure
pub const NOTE_VM_PRESSURE = 0x80000000;
/// will quit on memory pressure, possibly after cleaning up dirty state
pub const NOTE_VM_PRESSURE_TERMINATE = 0x40000000;
/// will quit immediately on memory pressure
pub const NOTE_VM_PRESSURE_SUDDEN_TERMINATE = 0x20000000;
/// there was an error
pub const NOTE_VM_ERROR = 0x10000000;
/// data is seconds
pub const NOTE_SECONDS = 0x00000001;
/// data is microseconds
pub const NOTE_USECONDS = 0x00000002;
/// data is nanoseconds
pub const NOTE_NSECONDS = 0x00000004;
/// absolute timeout
pub const NOTE_ABSOLUTE = 0x00000008;
/// ext[1] holds leeway for power aware timers
pub const NOTE_LEEWAY = 0x00000010;
/// system does minimal timer coalescing
pub const NOTE_CRITICAL = 0x00000020;
/// system does maximum timer coalescing
pub const NOTE_BACKGROUND = 0x00000040;
pub const NOTE_MACH_CONTINUOUS_TIME = 0x00000080;
/// data is mach absolute time units
pub const NOTE_MACHTIME = 0x00000100;
pub const AF_UNSPEC = 0;
pub const AF_LOCAL = 1;
pub const AF_UNIX = AF_LOCAL;
pub const AF_INET = 2;
pub const AF_SYS_CONTROL = 2;
pub const AF_IMPLINK = 3;
pub const AF_PUP = 4;
pub const AF_CHAOS = 5;
pub const AF_NS = 6;
pub const AF_ISO = 7;
pub const AF_OSI = AF_ISO;
pub const AF_ECMA = 8;
pub const AF_DATAKIT = 9;
pub const AF_CCITT = 10;
pub const AF_SNA = 11;
pub const AF_DECnet = 12;
pub const AF_DLI = 13;
pub const AF_LAT = 14;
pub const AF_HYLINK = 15;
pub const AF_APPLETALK = 16;
pub const AF_ROUTE = 17;
pub const AF_LINK = 18;
pub const AF_XTP = 19;
pub const AF_COIP = 20;
pub const AF_CNT = 21;
pub const AF_RTIP = 22;
pub const AF_IPX = 23;
pub const AF_SIP = 24;
pub const AF_PIP = 25;
pub const AF_ISDN = 28;
pub const AF_E164 = AF_ISDN;
pub const AF_KEY = 29;
pub const AF_INET6 = 30;
pub const AF_NATM = 31;
pub const AF_SYSTEM = 32;
pub const AF_NETBIOS = 33;
pub const AF_PPP = 34;
pub const AF_MAX = 40;
pub const PF_UNSPEC = AF_UNSPEC;
pub const PF_LOCAL = AF_LOCAL;
pub const PF_UNIX = PF_LOCAL;
pub const PF_INET = AF_INET;
pub const PF_IMPLINK = AF_IMPLINK;
pub const PF_PUP = AF_PUP;
pub const PF_CHAOS = AF_CHAOS;
pub const PF_NS = AF_NS;
pub const PF_ISO = AF_ISO;
pub const PF_OSI = AF_ISO;
pub const PF_ECMA = AF_ECMA;
pub const PF_DATAKIT = AF_DATAKIT;
pub const PF_CCITT = AF_CCITT;
pub const PF_SNA = AF_SNA;
pub const PF_DECnet = AF_DECnet;
pub const PF_DLI = AF_DLI;
pub const PF_LAT = AF_LAT;
pub const PF_HYLINK = AF_HYLINK;
pub const PF_APPLETALK = AF_APPLETALK;
pub const PF_ROUTE = AF_ROUTE;
pub const PF_LINK = AF_LINK;
pub const PF_XTP = AF_XTP;
pub const PF_COIP = AF_COIP;
pub const PF_CNT = AF_CNT;
pub const PF_SIP = AF_SIP;
pub const PF_IPX = AF_IPX;
pub const PF_RTIP = AF_RTIP;
pub const PF_PIP = AF_PIP;
pub const PF_ISDN = AF_ISDN;
pub const PF_KEY = AF_KEY;
pub const PF_INET6 = AF_INET6;
pub const PF_NATM = AF_NATM;
pub const PF_SYSTEM = AF_SYSTEM;
pub const PF_NETBIOS = AF_NETBIOS;
pub const PF_PPP = AF_PPP;
pub const PF_MAX = AF_MAX;
pub const SYSPROTO_EVENT = 1;
pub const SYSPROTO_CONTROL = 2;
pub const SOCK_STREAM = 1;
pub const SOCK_DGRAM = 2;
pub const SOCK_RAW = 3;
pub const SOCK_RDM = 4;
pub const SOCK_SEQPACKET = 5;
pub const SOCK_MAXADDRLEN = 255;
/// Not actually supported by Darwin, but Zig supplies a shim.
/// This numerical value is not ABI-stable. It need only not conflict
/// with any other "SOCK_" bits.
pub const SOCK_CLOEXEC = 1 << 15;
/// Not actually supported by Darwin, but Zig supplies a shim.
/// This numerical value is not ABI-stable. It need only not conflict
/// with any other "SOCK_" bits.
pub const SOCK_NONBLOCK = 1 << 16;
pub const IPPROTO_ICMP = 1;
pub const IPPROTO_ICMPV6 = 58;
pub const IPPROTO_TCP = 6;
pub const IPPROTO_UDP = 17;
pub const IPPROTO_IP = 0;
pub const IPPROTO_IPV6 = 41;
pub const SOL_SOCKET = 0xffff;
pub const SO_DEBUG = 0x0001;
pub const SO_ACCEPTCONN = 0x0002;
pub const SO_REUSEADDR = 0x0004;
pub const SO_KEEPALIVE = 0x0008;
pub const SO_DONTROUTE = 0x0010;
pub const SO_BROADCAST = 0x0020;
pub const SO_USELOOPBACK = 0x0040;
pub const SO_LINGER = 0x1080;
pub const SO_OOBINLINE = 0x0100;
pub const SO_REUSEPORT = 0x0200;
pub const SO_ACCEPTFILTER = 0x1000;
pub const SO_SNDBUF = 0x1001;
pub const SO_RCVBUF = 0x1002;
pub const SO_SNDLOWAT = 0x1003;
pub const SO_RCVLOWAT = 0x1004;
pub const SO_SNDTIMEO = 0x1005;
pub const SO_RCVTIMEO = 0x1006;
pub const SO_ERROR = 0x1007;
pub const SO_TYPE = 0x1008;
pub const SO_NREAD = 0x1020;
pub const SO_NKE = 0x1021;
pub const SO_NOSIGPIPE = 0x1022;
pub const SO_NOADDRERR = 0x1023;
pub const SO_NWRITE = 0x1024;
pub const SO_REUSESHAREUID = 0x1025;
fn wstatus(x: u32) u32 {
return x & 0o177;
}
const wstopped = 0o177;
pub fn WEXITSTATUS(x: u32) u32 {
return x >> 8;
}
pub fn WTERMSIG(x: u32) u32 {
return wstatus(x);
}
pub fn WSTOPSIG(x: u32) u32 {
return x >> 8;
}
pub fn WIFEXITED(x: u32) bool {
return wstatus(x) == 0;
}
pub fn WIFSTOPPED(x: u32) bool {
return wstatus(x) == wstopped and WSTOPSIG(x) != 0x13;
}
pub fn WIFSIGNALED(x: u32) bool {
return wstatus(x) != wstopped and wstatus(x) != 0;
}
/// Operation not permitted
pub const EPERM = 1;
/// No such file or directory
pub const ENOENT = 2;
/// No such process
pub const ESRCH = 3;
/// Interrupted system call
pub const EINTR = 4;
/// Input/output error
pub const EIO = 5;
/// Device not configured
pub const ENXIO = 6;
/// Argument list too long
pub const E2BIG = 7;
/// Exec format error
pub const ENOEXEC = 8;
/// Bad file descriptor
pub const EBADF = 9;
/// No child processes
pub const ECHILD = 10;
/// Resource deadlock avoided
pub const EDEADLK = 11;
/// Cannot allocate memory
pub const ENOMEM = 12;
/// Permission denied
pub const EACCES = 13;
/// Bad address
pub const EFAULT = 14;
/// Block device required
pub const ENOTBLK = 15;
/// Device / Resource busy
pub const EBUSY = 16;
/// File exists
pub const EEXIST = 17;
/// Cross-device link
pub const EXDEV = 18;
/// Operation not supported by device
pub const ENODEV = 19;
/// Not a directory
pub const ENOTDIR = 20;
/// Is a directory
pub const EISDIR = 21;
/// Invalid argument
pub const EINVAL = 22;
/// Too many open files in system
pub const ENFILE = 23;
/// Too many open files
pub const EMFILE = 24;
/// Inappropriate ioctl for device
pub const ENOTTY = 25;
/// Text file busy
pub const ETXTBSY = 26;
/// File too large
pub const EFBIG = 27;
/// No space left on device
pub const ENOSPC = 28;
/// Illegal seek
pub const ESPIPE = 29;
/// Read-only file system
pub const EROFS = 30;
/// Too many links
pub const EMLINK = 31;
/// Broken pipe
// math software
pub const EPIPE = 32;
/// Numerical argument out of domain
pub const EDOM = 33;
/// Result too large
// non-blocking and interrupt i/o
pub const ERANGE = 34;
/// Resource temporarily unavailable
pub const EAGAIN = 35;
/// Operation would block
pub const EWOULDBLOCK = EAGAIN;
/// Operation now in progress
pub const EINPROGRESS = 36;
/// Operation already in progress
// ipc/network software -- argument errors
pub const EALREADY = 37;
/// Socket operation on non-socket
pub const ENOTSOCK = 38;
/// Destination address required
pub const EDESTADDRREQ = 39;
/// Message too long
pub const EMSGSIZE = 40;
/// Protocol wrong type for socket
pub const EPROTOTYPE = 41;
/// Protocol not available
pub const ENOPROTOOPT = 42;
/// Protocol not supported
pub const EPROTONOSUPPORT = 43;
/// Socket type not supported
pub const ESOCKTNOSUPPORT = 44;
/// Operation not supported
pub const ENOTSUP = 45;
/// Operation not supported. Alias of `ENOTSUP`.
pub const EOPNOTSUPP = ENOTSUP;
/// Protocol family not supported
pub const EPFNOSUPPORT = 46;
/// Address family not supported by protocol family
pub const EAFNOSUPPORT = 47;
/// Address already in use
pub const EADDRINUSE = 48;
/// Can't assign requested address
// ipc/network software -- operational errors
pub const EADDRNOTAVAIL = 49;
/// Network is down
pub const ENETDOWN = 50;
/// Network is unreachable
pub const ENETUNREACH = 51;
/// Network dropped connection on reset
pub const ENETRESET = 52;
/// Software caused connection abort
pub const ECONNABORTED = 53;
/// Connection reset by peer
pub const ECONNRESET = 54;
/// No buffer space available
pub const ENOBUFS = 55;
/// Socket is already connected
pub const EISCONN = 56;
/// Socket is not connected
pub const ENOTCONN = 57;
/// Can't send after socket shutdown
pub const ESHUTDOWN = 58;
/// Too many references: can't splice
pub const ETOOMANYREFS = 59;
/// Operation timed out
pub const ETIMEDOUT = 60;
/// Connection refused
pub const ECONNREFUSED = 61;
/// Too many levels of symbolic links
pub const ELOOP = 62;
/// File name too long
pub const ENAMETOOLONG = 63;
/// Host is down
pub const EHOSTDOWN = 64;
/// No route to host
pub const EHOSTUNREACH = 65;
/// Directory not empty
// quotas & mush
pub const ENOTEMPTY = 66;
/// Too many processes
pub const EPROCLIM = 67;
/// Too many users
pub const EUSERS = 68;
/// Disc quota exceeded
// Network File System
pub const EDQUOT = 69;
/// Stale NFS file handle
pub const ESTALE = 70;
/// Too many levels of remote in path
pub const EREMOTE = 71;
/// RPC struct is bad
pub const EBADRPC = 72;
/// RPC version wrong
pub const ERPCMISMATCH = 73;
/// RPC prog. not avail
pub const EPROGUNAVAIL = 74;
/// Program version wrong
pub const EPROGMISMATCH = 75;
/// Bad procedure for program
pub const EPROCUNAVAIL = 76;
/// No locks available
pub const ENOLCK = 77;
/// Function not implemented
pub const ENOSYS = 78;
/// Inappropriate file type or format
pub const EFTYPE = 79;
/// Authentication error
pub const EAUTH = 80;
/// Need authenticator
// Intelligent device errors
pub const ENEEDAUTH = 81;
/// Device power is off
pub const EPWROFF = 82;
/// Device error, e.g. paper out
pub const EDEVERR = 83;
/// Value too large to be stored in data type
// Program loading errors
pub const EOVERFLOW = 84;
/// Bad executable
pub const EBADEXEC = 85;
/// Bad CPU type in executable
pub const EBADARCH = 86;
/// Shared library version mismatch
pub const ESHLIBVERS = 87;
/// Malformed Macho file
pub const EBADMACHO = 88;
/// Operation canceled
pub const ECANCELED = 89;
/// Identifier removed
pub const EIDRM = 90;
/// No message of desired type
pub const ENOMSG = 91;
/// Illegal byte sequence
pub const EILSEQ = 92;
/// Attribute not found
pub const ENOATTR = 93;
/// Bad message
pub const EBADMSG = 94;
/// Reserved
pub const EMULTIHOP = 95;
/// No message available on STREAM
pub const ENODATA = 96;
/// Reserved
pub const ENOLINK = 97;
/// No STREAM resources
pub const ENOSR = 98;
/// Not a STREAM
pub const ENOSTR = 99;
/// Protocol error
pub const EPROTO = 100;
/// STREAM ioctl timeout
pub const ETIME = 101;
/// No such policy registered
pub const ENOPOLICY = 103;
/// State not recoverable
pub const ENOTRECOVERABLE = 104;
/// Previous owner died
pub const EOWNERDEAD = 105;
/// Interface output queue is full
pub const EQFULL = 106;
/// Must be equal largest errno
pub const ELAST = 106;
pub const SIGSTKSZ = 131072;
pub const MINSIGSTKSZ = 32768;
pub const SS_ONSTACK = 1;
pub const SS_DISABLE = 4;
pub const stack_t = extern struct {
ss_sp: [*]u8,
ss_size: isize,
ss_flags: i32,
};
pub const S_IFMT = 0o170000;
pub const S_IFIFO = 0o010000;
pub const S_IFCHR = 0o020000;
pub const S_IFDIR = 0o040000;
pub const S_IFBLK = 0o060000;
pub const S_IFREG = 0o100000;
pub const S_IFLNK = 0o120000;
pub const S_IFSOCK = 0o140000;
pub const S_IFWHT = 0o160000;
pub const S_ISUID = 0o4000;
pub const S_ISGID = 0o2000;
pub const S_ISVTX = 0o1000;
pub const S_IRWXU = 0o700;
pub const S_IRUSR = 0o400;
pub const S_IWUSR = 0o200;
pub const S_IXUSR = 0o100;
pub const S_IRWXG = 0o070;
pub const S_IRGRP = 0o040;
pub const S_IWGRP = 0o020;
pub const S_IXGRP = 0o010;
pub const S_IRWXO = 0o007;
pub const S_IROTH = 0o004;
pub const S_IWOTH = 0o002;
pub const S_IXOTH = 0o001;
pub fn S_ISFIFO(m: u32) bool {
return m & S_IFMT == S_IFIFO;
}
pub fn S_ISCHR(m: u32) bool {
return m & S_IFMT == S_IFCHR;
}
pub fn S_ISDIR(m: u32) bool {
return m & S_IFMT == S_IFDIR;
}
pub fn S_ISBLK(m: u32) bool {
return m & S_IFMT == S_IFBLK;
}
pub fn S_ISREG(m: u32) bool {
return m & S_IFMT == S_IFREG;
}
pub fn S_ISLNK(m: u32) bool {
return m & S_IFMT == S_IFLNK;
}
pub fn S_ISSOCK(m: u32) bool {
return m & S_IFMT == S_IFSOCK;
}
pub fn S_IWHT(m: u32) bool {
return m & S_IFMT == S_IFWHT;
}
pub const HOST_NAME_MAX = 72;
pub const AT_FDCWD = -2;
/// Use effective ids in access check
pub const AT_EACCESS = 0x0010;
/// Act on the symlink itself not the target
pub const AT_SYMLINK_NOFOLLOW = 0x0020;
/// Act on target of symlink
pub const AT_SYMLINK_FOLLOW = 0x0040;
/// Path refers to directory
pub const AT_REMOVEDIR = 0x0080;
pub const addrinfo = extern struct {
flags: i32,
family: i32,
socktype: i32,
protocol: i32,
addrlen: socklen_t,
canonname: ?[*:0]u8,
addr: ?*sockaddr,
next: ?*addrinfo,
};
pub const RTLD_LAZY = 0x1;
pub const RTLD_NOW = 0x2;
pub const RTLD_LOCAL = 0x4;
pub const RTLD_GLOBAL = 0x8;
pub const RTLD_NOLOAD = 0x10;
pub const RTLD_NODELETE = 0x80;
pub const RTLD_FIRST = 0x100;
pub const RTLD_NEXT = @intToPtr(*c_void, @bitCast(usize, @as(isize, -1)));
pub const RTLD_DEFAULT = @intToPtr(*c_void, @bitCast(usize, @as(isize, -2)));
pub const RTLD_SELF = @intToPtr(*c_void, @bitCast(usize, @as(isize, -3)));
pub const RTLD_MAIN_ONLY = @intToPtr(*c_void, @bitCast(usize, @as(isize, -5)));
/// duplicate file descriptor
pub const F_DUPFD = 0;
/// get file descriptor flags
pub const F_GETFD = 1;
/// set file descriptor flags
pub const F_SETFD = 2;
/// get file status flags
pub const F_GETFL = 3;
/// set file status flags
pub const F_SETFL = 4;
/// get SIGIO/SIGURG proc/pgrp
pub const F_GETOWN = 5;
/// set SIGIO/SIGURG proc/pgrp
pub const F_SETOWN = 6;
/// get record locking information
pub const F_GETLK = 7;
/// set record locking information
pub const F_SETLK = 8;
/// F_SETLK; wait if blocked
pub const F_SETLKW = 9;
/// F_SETLK; wait if blocked, return on timeout
pub const F_SETLKWTIMEOUT = 10;
pub const F_FLUSH_DATA = 40;
/// Used for regression test
pub const F_CHKCLEAN = 41;
/// Preallocate storage
pub const F_PREALLOCATE = 42;
/// Truncate a file without zeroing space
pub const F_SETSIZE = 43;
/// Issue an advisory read async with no copy to user
pub const F_RDADVISE = 44;
/// turn read ahead off/on for this fd
pub const F_RDAHEAD = 45;
/// turn data caching off/on for this fd
pub const F_NOCACHE = 48;
/// file offset to device offset
pub const F_LOG2PHYS = 49;
/// return the full path of the fd
pub const F_GETPATH = 50;
/// fsync + ask the drive to flush to the media
pub const F_FULLFSYNC = 51;
/// find which component (if any) is a package
pub const F_PATHPKG_CHECK = 52;
/// "freeze" all fs operations
pub const F_FREEZE_FS = 53;
/// "thaw" all fs operations
pub const F_THAW_FS = 54;
/// turn data caching off/on (globally) for this file
pub const F_GLOBAL_NOCACHE = 55;
/// add detached signatures
pub const F_ADDSIGS = 59;
/// add signature from same file (used by dyld for shared libs)
pub const F_ADDFILESIGS = 61;
/// used in conjunction with F_NOCACHE to indicate that DIRECT, synchonous writes
/// should not be used (i.e. its ok to temporaily create cached pages)
pub const F_NODIRECT = 62;
///Get the protection class of a file from the EA, returns int
pub const F_GETPROTECTIONCLASS = 63;
///Set the protection class of a file for the EA, requires int
pub const F_SETPROTECTIONCLASS = 64;
///file offset to device offset, extended
pub const F_LOG2PHYS_EXT = 65;
///get record locking information, per-process
pub const F_GETLKPID = 66;
///Mark the file as being the backing store for another filesystem
pub const F_SETBACKINGSTORE = 70;
///return the full path of the FD, but error in specific mtmd circumstances
pub const F_GETPATH_MTMINFO = 71;
///Returns the code directory, with associated hashes, to the caller
pub const F_GETCODEDIR = 72;
///No SIGPIPE generated on EPIPE
pub const F_SETNOSIGPIPE = 73;
///Status of SIGPIPE for this fd
pub const F_GETNOSIGPIPE = 74;
///For some cases, we need to rewrap the key for AKS/MKB
pub const F_TRANSCODEKEY = 75;
///file being written to a by single writer... if throttling enabled, writes
///may be broken into smaller chunks with throttling in between
pub const F_SINGLE_WRITER = 76;
///Get the protection version number for this filesystem
pub const F_GETPROTECTIONLEVEL = 77;
///Add detached code signatures (used by dyld for shared libs)
pub const F_FINDSIGS = 78;
///Add signature from same file, only if it is signed by Apple (used by dyld for simulator)
pub const F_ADDFILESIGS_FOR_DYLD_SIM = 83;
///fsync + issue barrier to drive
pub const F_BARRIERFSYNC = 85;
///Add signature from same file, return end offset in structure on success
pub const F_ADDFILESIGS_RETURN = 97;
///Check if Library Validation allows this Mach-O file to be mapped into the calling process
pub const F_CHECK_LV = 98;
///Deallocate a range of the file
pub const F_PUNCHHOLE = 99;
///Trim an active file
pub const F_TRIM_ACTIVE_FILE = 100;
pub const FCNTL_FS_SPECIFIC_BASE = 0x00010000;
///mark the dup with FD_CLOEXEC
pub const F_DUPFD_CLOEXEC = 67;
///close-on-exec flag
pub const FD_CLOEXEC = 1;
/// shared or read lock
pub const F_RDLCK = 1;
/// unlock
pub const F_UNLCK = 2;
/// exclusive or write lock
pub const F_WRLCK = 3;
pub const LOCK_SH = 1;
pub const LOCK_EX = 2;
pub const LOCK_UN = 8;
pub const LOCK_NB = 4;
pub const nfds_t = u32;
pub const pollfd = extern struct {
fd: fd_t,
events: i16,
revents: i16,
};
pub const POLLIN = 0x001;
pub const POLLPRI = 0x002;
pub const POLLOUT = 0x004;
pub const POLLRDNORM = 0x040;
pub const POLLWRNORM = POLLOUT;
pub const POLLRDBAND = 0x080;
pub const POLLWRBAND = 0x100;
pub const POLLEXTEND = 0x0200;
pub const POLLATTRIB = 0x0400;
pub const POLLNLINK = 0x0800;
pub const POLLWRITE = 0x1000;
pub const POLLERR = 0x008;
pub const POLLHUP = 0x010;
pub const POLLNVAL = 0x020;
pub const POLLSTANDARD = POLLIN | POLLPRI | POLLOUT | POLLRDNORM | POLLRDBAND | POLLWRBAND | POLLERR | POLLHUP | POLLNVAL;
pub const CLOCK_REALTIME = 0;
pub const CLOCK_MONOTONIC = 6;
pub const CLOCK_MONOTONIC_RAW = 4;
pub const CLOCK_MONOTONIC_RAW_APPROX = 5;
pub const CLOCK_UPTIME_RAW = 8;
pub const CLOCK_UPTIME_RAW_APPROX = 9;
pub const CLOCK_PROCESS_CPUTIME_ID = 12;
pub const CLOCK_THREAD_CPUTIME_ID = 16;
/// Max open files per process
/// https://opensource.apple.com/source/xnu/xnu-4903.221.2/bsd/sys/syslimits.h.auto.html
pub const OPEN_MAX = 10240;
pub const RUSAGE_SELF = 0;
pub const RUSAGE_CHILDREN = -1;
pub const rusage = extern struct {
utime: timeval,
stime: timeval,
maxrss: isize,
ixrss: isize,
idrss: isize,
isrss: isize,
minflt: isize,
majflt: isize,
nswap: isize,
inblock: isize,
oublock: isize,
msgsnd: isize,
msgrcv: isize,
nsignals: isize,
nvcsw: isize,
nivcsw: isize,
};
pub const rlimit_resource = extern enum(c_int) {
CPU = 0,
FSIZE = 1,
DATA = 2,
STACK = 3,
CORE = 4,
AS = 5,
RSS = 5,
MEMLOCK = 6,
NPROC = 7,
NOFILE = 8,
_,
};
pub const rlim_t = u64;
/// No limit
pub const RLIM_INFINITY: rlim_t = (1 << 63) - 1;
pub const RLIM_SAVED_MAX = RLIM_INFINITY;
pub const RLIM_SAVED_CUR = RLIM_INFINITY;
pub const rlimit = extern struct {
/// Soft limit
cur: rlim_t,
/// Hard limit
max: rlim_t,
};
pub const SHUT_RD = 0;
pub const SHUT_WR = 1;
pub const SHUT_RDWR = 2;
// Term
pub const VEOF = 0;
pub const VEOL = 1;
pub const VEOL2 = 2;
pub const VERASE = 3;
pub const VWERASE = 4;
pub const VKILL = 5;
pub const VREPRINT = 6;
pub const VINTR = 8;
pub const VQUIT = 9;
pub const VSUSP = 10;
pub const VDSUSP = 11;
pub const VSTART = 12;
pub const VSTOP = 13;
pub const VLNEXT = 14;
pub const VDISCARD = 15;
pub const VMIN = 16;
pub const VTIME = 17;
pub const VSTATUS = 18;
pub const NCCS = 20; // 2 spares (7, 19)
pub const IGNBRK = 0x00000001; // ignore BREAK condition
pub const BRKINT = 0x00000002; // map BREAK to SIGINTR
pub const IGNPAR = 0x00000004; // ignore (discard) parity errors
pub const PARMRK = 0x00000008; // mark parity and framing errors
pub const INPCK = 0x00000010; // enable checking of parity errors
pub const ISTRIP = 0x00000020; // strip 8th bit off chars
pub const INLCR = 0x00000040; // map NL into CR
pub const IGNCR = 0x00000080; // ignore CR
pub const ICRNL = 0x00000100; // map CR to NL (ala CRMOD)
pub const IXON = 0x00000200; // enable output flow control
pub const IXOFF = 0x00000400; // enable input flow control
pub const IXANY = 0x00000800; // any char will restart after stop
pub const IMAXBEL = 0x00002000; // ring bell on input queue full
pub const IUTF8 = 0x00004000; // maintain state for UTF-8 VERASE
pub const OPOST = 0x00000001; //enable following output processing
pub const ONLCR = 0x00000002; // map NL to CR-NL (ala CRMOD)
pub const OXTABS = 0x00000004; // expand tabs to spaces
pub const ONOEOT = 0x00000008; // discard EOT's (^D) on output)
pub const OCRNL = 0x00000010; // map CR to NL on output
pub const ONOCR = 0x00000020; // no CR output at column 0
pub const ONLRET = 0x00000040; // NL performs CR function
pub const OFILL = 0x00000080; // use fill characters for delay
pub const NLDLY = 0x00000300; // \n delay
pub const TABDLY = 0x00000c04; // horizontal tab delay
pub const CRDLY = 0x00003000; // \r delay
pub const FFDLY = 0x00004000; // form feed delay
pub const BSDLY = 0x00008000; // \b delay
pub const VTDLY = 0x00010000; // vertical tab delay
pub const OFDEL = 0x00020000; // fill is DEL, else NUL
pub const NL0 = 0x00000000;
pub const NL1 = 0x00000100;
pub const NL2 = 0x00000200;
pub const NL3 = 0x00000300;
pub const TAB0 = 0x00000000;
pub const TAB1 = 0x00000400;
pub const TAB2 = 0x00000800;
pub const TAB3 = 0x00000004;
pub const CR0 = 0x00000000;
pub const CR1 = 0x00001000;
pub const CR2 = 0x00002000;
pub const CR3 = 0x00003000;
pub const FF0 = 0x00000000;
pub const FF1 = 0x00004000;
pub const BS0 = 0x00000000;
pub const BS1 = 0x00008000;
pub const VT0 = 0x00000000;
pub const VT1 = 0x00010000;
pub const CIGNORE = 0x00000001; // ignore control flags
pub const CSIZE = 0x00000300; // character size mask
pub const CS5 = 0x00000000; // 5 bits (pseudo)
pub const CS6 = 0x00000100; // 6 bits
pub const CS7 = 0x00000200; // 7 bits
pub const CS8 = 0x00000300; // 8 bits
pub const CSTOPB = 0x0000040; // send 2 stop bits
pub const CREAD = 0x00000800; // enable receiver
pub const PARENB = 0x00001000; // parity enable
pub const PARODD = 0x00002000; // odd parity, else even
pub const HUPCL = 0x00004000; // hang up on last close
pub const CLOCAL = 0x00008000; // ignore modem status lines
pub const CCTS_OFLOW = 0x00010000; // CTS flow control of output
pub const CRTSCTS = (CCTS_OFLOW | CRTS_IFLOW);
pub const CRTS_IFLOW = 0x00020000; // RTS flow control of input
pub const CDTR_IFLOW = 0x00040000; // DTR flow control of input
pub const CDSR_OFLOW = 0x00080000; // DSR flow control of output
pub const CCAR_OFLOW = 0x00100000; // DCD flow control of output
pub const MDMBUF = 0x00100000; // old name for CCAR_OFLOW
pub const ECHOKE = 0x00000001; // visual erase for line kill
pub const ECHOE = 0x00000002; // visually erase chars
pub const ECHOK = 0x00000004; // echo NL after line kill
pub const ECHO = 0x00000008; // enable echoing
pub const ECHONL = 0x00000010; // echo NL even if ECHO is off
pub const ECHOPRT = 0x00000020; // visual erase mode for hardcopy
pub const ECHOCTL = 0x00000040; // echo control chars as ^(Char)
pub const ISIG = 0x00000080; // enable signals INTR, QUIT, [D]SUSP
pub const ICANON = 0x00000100; // canonicalize input lines
pub const ALTWERASE = 0x00000200; // use alternate WERASE algorithm
pub const IEXTEN = 0x00000400; // enable DISCARD and LNEXT
pub const EXTPROC = 0x00000800; // external processing
pub const TOSTOP = 0x00400000; // stop background jobs from output
pub const FLUSHO = 0x00800000; // output being flushed (state)
pub const NOKERNINFO = 0x02000000; // no kernel output from VSTATUS
pub const PENDIN = 0x20000000; // XXX retype pending input (state)
pub const NOFLSH = 0x80000000; // don't flush after interrupt
pub const TCSANOW = 0; // make change immediate
pub const TCSADRAIN = 1; // drain output, then change
pub const TCSAFLUSH = 2; // drain output, flush input
pub const TCSASOFT = 0x10; // flag - don't alter h.w. state
pub const TCSA = extern enum(c_uint) {
NOW,
DRAIN,
FLUSH,
_,
};
pub const B0 = 0;
pub const B50 = 50;
pub const B75 = 75;
pub const B110 = 110;
pub const B134 = 134;
pub const B150 = 150;
pub const B200 = 200;
pub const B300 = 300;
pub const B600 = 600;
pub const B1200 = 1200;
pub const B1800 = 1800;
pub const B2400 = 2400;
pub const B4800 = 4800;
pub const B9600 = 9600;
pub const B19200 = 19200;
pub const B38400 = 38400;
pub const B7200 = 7200;
pub const B14400 = 14400;
pub const B28800 = 28800;
pub const B57600 = 57600;
pub const B76800 = 76800;
pub const B115200 = 115200;
pub const B230400 = 230400;
pub const EXTA = 19200;
pub const EXTB = 38400;
pub const TCIFLUSH = 1;
pub const TCOFLUSH = 2;
pub const TCIOFLUSH = 3;
pub const TCOOFF = 1;
pub const TCOON = 2;
pub const TCIOFF = 3;
pub const TCION = 4;
pub const cc_t = u8;
pub const speed_t = u64;
pub const tcflag_t = u64;
pub const termios = extern struct {
iflag: tcflag_t, // input flags
oflag: tcflag_t, // output flags
cflag: tcflag_t, // control flags
lflag: tcflag_t, // local flags
cc: [NCCS]cc_t, // control chars
ispeed: speed_t align(8), // input speed
ospeed: speed_t, // output speed
};
pub const winsize = extern struct {
ws_row: u16,
ws_col: u16,
ws_xpixel: u16,
ws_ypixel: u16,
};
pub const TIOCGWINSZ = ior(0x40000000, 't', 104, @sizeOf(winsize));
pub const IOCPARM_MASK = 0x1fff;
fn ior(inout: u32, group: usize, num: usize, len: usize) usize {
return (inout | ((len & IOCPARM_MASK) << 16) | ((group) << 8) | (num));
} | lib/std/os/bits/darwin.zig |
const std = @import("../std.zig");
const builtin = std.builtin;
const io = std.io;
pub const Packing = enum {
/// Pack data to byte alignment
Byte,
/// Pack data to bit alignment
Bit,
};
/// Creates a deserializer that deserializes types from any stream.
/// If `is_packed` is true, the data stream is treated as bit-packed,
/// otherwise data is expected to be packed to the smallest byte.
/// Types may implement a custom deserialization routine with a
/// function named `deserialize` in the form of:
/// pub fn deserialize(self: *Self, deserializer: var) !void
/// which will be called when the deserializer is used to deserialize
/// that type. It will pass a pointer to the type instance to deserialize
/// into and a pointer to the deserializer struct.
pub fn Deserializer(comptime endian: builtin.Endian, comptime packing: Packing, comptime InStreamType: type) type {
return struct {
in_stream: if (packing == .Bit) io.BitInStream(endian, InStreamType) else InStreamType,
const Self = @This();
pub fn init(in_stream: InStreamType) Self {
return Self{
.in_stream = switch (packing) {
.Bit => io.bitInStream(endian, in_stream),
.Byte => in_stream,
},
};
}
pub fn alignToByte(self: *Self) void {
if (packing == .Byte) return;
self.in_stream.alignToByte();
}
//@BUG: inferred error issue. See: #1386
fn deserializeInt(self: *Self, comptime T: type) (InStreamType.Error || error{EndOfStream})!T {
comptime assert(trait.is(.Int)(T) or trait.is(.Float)(T));
const u8_bit_count = 8;
const t_bit_count = comptime meta.bitCount(T);
const U = std.meta.IntType(false, t_bit_count);
const Log2U = math.Log2Int(U);
const int_size = (U.bit_count + 7) / 8;
if (packing == .Bit) {
const result = try self.in_stream.readBitsNoEof(U, t_bit_count);
return @bitCast(T, result);
}
var buffer: [int_size]u8 = undefined;
const read_size = try self.in_stream.read(buffer[0..]);
if (read_size < int_size) return error.EndOfStream;
if (int_size == 1) {
if (t_bit_count == 8) return @bitCast(T, buffer[0]);
const PossiblySignedByte = std.meta.IntType(T.is_signed, 8);
return @truncate(T, @bitCast(PossiblySignedByte, buffer[0]));
}
var result = @as(U, 0);
for (buffer) |byte, i| {
switch (endian) {
.Big => {
result = (result << u8_bit_count) | byte;
},
.Little => {
result |= @as(U, byte) << @intCast(Log2U, u8_bit_count * i);
},
}
}
return @bitCast(T, result);
}
/// Deserializes and returns data of the specified type from the stream
pub fn deserialize(self: *Self, comptime T: type) !T {
var value: T = undefined;
try self.deserializeInto(&value);
return value;
}
/// Deserializes data into the type pointed to by `ptr`
pub fn deserializeInto(self: *Self, ptr: var) !void {
const T = @TypeOf(ptr);
comptime assert(trait.is(.Pointer)(T));
if (comptime trait.isSlice(T) or comptime trait.isPtrTo(.Array)(T)) {
for (ptr) |*v|
try self.deserializeInto(v);
return;
}
comptime assert(trait.isSingleItemPtr(T));
const C = comptime meta.Child(T);
const child_type_id = @typeInfo(C);
//custom deserializer: fn(self: *Self, deserializer: var) !void
if (comptime trait.hasFn("deserialize")(C)) return C.deserialize(ptr, self);
if (comptime trait.isPacked(C) and packing != .Bit) {
var packed_deserializer = deserializer(endian, .Bit, self.in_stream);
return packed_deserializer.deserializeInto(ptr);
}
switch (child_type_id) {
.Void => return,
.Bool => ptr.* = (try self.deserializeInt(u1)) > 0,
.Float, .Int => ptr.* = try self.deserializeInt(C),
.Struct => {
const info = @typeInfo(C).Struct;
inline for (info.fields) |*field_info| {
const name = field_info.name;
const FieldType = field_info.field_type;
if (FieldType == void or FieldType == u0) continue;
//it doesn't make any sense to read pointers
if (comptime trait.is(.Pointer)(FieldType)) {
@compileError("Will not " ++ "read field " ++ name ++ " of struct " ++
@typeName(C) ++ " because it " ++ "is of pointer-type " ++
@typeName(FieldType) ++ ".");
}
try self.deserializeInto(&@field(ptr, name));
}
},
.Union => {
const info = @typeInfo(C).Union;
if (info.tag_type) |TagType| {
//we avoid duplicate iteration over the enum tags
// by getting the int directly and casting it without
// safety. If it is bad, it will be caught anyway.
const TagInt = @TagType(TagType);
const tag = try self.deserializeInt(TagInt);
inline for (info.fields) |field_info| {
if (field_info.enum_field.?.value == tag) {
const name = field_info.name;
const FieldType = field_info.field_type;
ptr.* = @unionInit(C, name, undefined);
try self.deserializeInto(&@field(ptr, name));
return;
}
}
//This is reachable if the enum data is bad
return error.InvalidEnumTag;
}
@compileError("Cannot meaningfully deserialize " ++ @typeName(C) ++
" because it is an untagged union. Use a custom deserialize().");
},
.Optional => {
const OC = comptime meta.Child(C);
const exists = (try self.deserializeInt(u1)) > 0;
if (!exists) {
ptr.* = null;
return;
}
ptr.* = @as(OC, undefined); //make it non-null so the following .? is guaranteed safe
const val_ptr = &ptr.*.?;
try self.deserializeInto(val_ptr);
},
.Enum => {
var value = try self.deserializeInt(@TagType(C));
ptr.* = try meta.intToEnum(C, value);
},
else => {
@compileError("Cannot deserialize " ++ @tagName(child_type_id) ++ " types (unimplemented).");
},
}
}
};
}
pub fn deserializer(
comptime endian: builtin.Endian,
comptime packing: Packing,
in_stream: var,
) Deserializer(endian, packing, @TypeOf(in_stream)) {
return Deserializer(endian, packing, @TypeOf(in_stream)).init(in_stream);
}
/// Creates a serializer that serializes types to any stream.
/// If `is_packed` is true, the data will be bit-packed into the stream.
/// Note that the you must call `serializer.flush()` when you are done
/// writing bit-packed data in order ensure any unwritten bits are committed.
/// If `is_packed` is false, data is packed to the smallest byte. In the case
/// of packed structs, the struct will written bit-packed and with the specified
/// endianess, after which data will resume being written at the next byte boundary.
/// Types may implement a custom serialization routine with a
/// function named `serialize` in the form of:
/// pub fn serialize(self: Self, serializer: var) !void
/// which will be called when the serializer is used to serialize that type. It will
/// pass a const pointer to the type instance to be serialized and a pointer
/// to the serializer struct.
pub fn Serializer(comptime endian: builtin.Endian, comptime packing: Packing, comptime OutStreamType: type) type {
return struct {
out_stream: if (packing == .Bit) BitOutStream(endian, OutStreamType) else OutStreamType,
const Self = @This();
pub const Error = OutStreamType.Error;
pub fn init(out_stream: OutStreamType) Self {
return Self{
.out_stream = switch (packing) {
.Bit => io.bitOutStream(endian, out_stream),
.Byte => out_stream,
},
};
}
/// Flushes any unwritten bits to the stream
pub fn flush(self: *Self) Error!void {
if (packing == .Bit) return self.out_stream.flushBits();
}
fn serializeInt(self: *Self, value: var) Error!void {
const T = @TypeOf(value);
comptime assert(trait.is(.Int)(T) or trait.is(.Float)(T));
const t_bit_count = comptime meta.bitCount(T);
const u8_bit_count = comptime meta.bitCount(u8);
const U = std.meta.IntType(false, t_bit_count);
const Log2U = math.Log2Int(U);
const int_size = (U.bit_count + 7) / 8;
const u_value = @bitCast(U, value);
if (packing == .Bit) return self.out_stream.writeBits(u_value, t_bit_count);
var buffer: [int_size]u8 = undefined;
if (int_size == 1) buffer[0] = u_value;
for (buffer) |*byte, i| {
const idx = switch (endian) {
.Big => int_size - i - 1,
.Little => i,
};
const shift = @intCast(Log2U, idx * u8_bit_count);
const v = u_value >> shift;
byte.* = if (t_bit_count < u8_bit_count) v else @truncate(u8, v);
}
try self.out_stream.write(&buffer);
}
/// Serializes the passed value into the stream
pub fn serialize(self: *Self, value: var) Error!void {
const T = comptime @TypeOf(value);
if (comptime trait.isIndexable(T)) {
for (value) |v|
try self.serialize(v);
return;
}
//custom serializer: fn(self: Self, serializer: var) !void
if (comptime trait.hasFn("serialize")(T)) return T.serialize(value, self);
if (comptime trait.isPacked(T) and packing != .Bit) {
var packed_serializer = Serializer(endian, .Bit, Error).init(self.out_stream);
try packed_serializer.serialize(value);
try packed_serializer.flush();
return;
}
switch (@typeInfo(T)) {
.Void => return,
.Bool => try self.serializeInt(@as(u1, @boolToInt(value))),
.Float, .Int => try self.serializeInt(value),
.Struct => {
const info = @typeInfo(T);
inline for (info.Struct.fields) |*field_info| {
const name = field_info.name;
const FieldType = field_info.field_type;
if (FieldType == void or FieldType == u0) continue;
//It doesn't make sense to write pointers
if (comptime trait.is(.Pointer)(FieldType)) {
@compileError("Will not " ++ "serialize field " ++ name ++
" of struct " ++ @typeName(T) ++ " because it " ++
"is of pointer-type " ++ @typeName(FieldType) ++ ".");
}
try self.serialize(@field(value, name));
}
},
.Union => {
const info = @typeInfo(T).Union;
if (info.tag_type) |TagType| {
const active_tag = meta.activeTag(value);
try self.serialize(active_tag);
//This inline loop is necessary because active_tag is a runtime
// value, but @field requires a comptime value. Our alternative
// is to check each field for a match
inline for (info.fields) |field_info| {
if (field_info.enum_field.?.value == @enumToInt(active_tag)) {
const name = field_info.name;
const FieldType = field_info.field_type;
try self.serialize(@field(value, name));
return;
}
}
unreachable;
}
@compileError("Cannot meaningfully serialize " ++ @typeName(T) ++
" because it is an untagged union. Use a custom serialize().");
},
.Optional => {
if (value == null) {
try self.serializeInt(@as(u1, @boolToInt(false)));
return;
}
try self.serializeInt(@as(u1, @boolToInt(true)));
const OC = comptime meta.Child(T);
const val_ptr = &value.?;
try self.serialize(val_ptr.*);
},
.Enum => {
try self.serializeInt(@enumToInt(value));
},
else => @compileError("Cannot serialize " ++ @tagName(@typeInfo(T)) ++ " types (unimplemented)."),
}
}
};
}
pub fn serializer(
comptime endian: builtin.Endian,
comptime packing: Packing,
out_stream: var,
) Serializer(endian, packing, @TypeOf(out_stream)) {
return Serializer(endian, packing, @TypeOf(out_stream)).init(out_stream);
}
fn testIntSerializerDeserializer(comptime endian: builtin.Endian, comptime packing: io.Packing) !void {
@setEvalBranchQuota(1500);
//@NOTE: if this test is taking too long, reduce the maximum tested bitsize
const max_test_bitsize = 128;
const total_bytes = comptime blk: {
var bytes = 0;
comptime var i = 0;
while (i <= max_test_bitsize) : (i += 1) bytes += (i / 8) + @boolToInt(i % 8 > 0);
break :blk bytes * 2;
};
var data_mem: [total_bytes]u8 = undefined;
var out = io.fixedBufferStream(&data_mem);
var serializer = serializer(endian, packing, out.outStream());
var in = io.fixedBufferStream(&data_mem);
var deserializer = Deserializer(endian, packing, in.inStream());
comptime var i = 0;
inline while (i <= max_test_bitsize) : (i += 1) {
const U = std.meta.IntType(false, i);
const S = std.meta.IntType(true, i);
try serializer.serializeInt(@as(U, i));
if (i != 0) try serializer.serializeInt(@as(S, -1)) else try serializer.serialize(@as(S, 0));
}
try serializer.flush();
i = 0;
inline while (i <= max_test_bitsize) : (i += 1) {
const U = std.meta.IntType(false, i);
const S = std.meta.IntType(true, i);
const x = try deserializer.deserializeInt(U);
const y = try deserializer.deserializeInt(S);
expect(x == @as(U, i));
if (i != 0) expect(y == @as(S, -1)) else expect(y == 0);
}
const u8_bit_count = comptime meta.bitCount(u8);
//0 + 1 + 2 + ... n = (n * (n + 1)) / 2
//and we have each for unsigned and signed, so * 2
const total_bits = (max_test_bitsize * (max_test_bitsize + 1));
const extra_packed_byte = @boolToInt(total_bits % u8_bit_count > 0);
const total_packed_bytes = (total_bits / u8_bit_count) + extra_packed_byte;
expect(in.pos == if (packing == .Bit) total_packed_bytes else total_bytes);
//Verify that empty error set works with serializer.
//deserializer is covered by FixedBufferStream
var null_serializer = io.serializer(endian, packing, std.io.null_out_stream);
try null_serializer.serialize(data_mem[0..]);
try null_serializer.flush();
}
test "Serializer/Deserializer Int" {
try testIntSerializerDeserializer(.Big, .Byte);
try testIntSerializerDeserializer(.Little, .Byte);
// TODO these tests are disabled due to tripping an LLVM assertion
// https://github.com/ziglang/zig/issues/2019
//try testIntSerializerDeserializer(builtin.Endian.Big, true);
//try testIntSerializerDeserializer(builtin.Endian.Little, true);
}
fn testIntSerializerDeserializerInfNaN(
comptime endian: builtin.Endian,
comptime packing: io.Packing,
) !void {
const mem_size = (16 * 2 + 32 * 2 + 64 * 2 + 128 * 2) / comptime meta.bitCount(u8);
var data_mem: [mem_size]u8 = undefined;
var out = io.fixedBufferStream(&data_mem);
var serializer = serializer(endian, packing, out.outStream());
var in = io.fixedBufferStream(&data_mem);
var deserializer = deserializer(endian, packing, in.inStream());
//@TODO: isInf/isNan not currently implemented for f128.
try serializer.serialize(std.math.nan(f16));
try serializer.serialize(std.math.inf(f16));
try serializer.serialize(std.math.nan(f32));
try serializer.serialize(std.math.inf(f32));
try serializer.serialize(std.math.nan(f64));
try serializer.serialize(std.math.inf(f64));
//try serializer.serialize(std.math.nan(f128));
//try serializer.serialize(std.math.inf(f128));
const nan_check_f16 = try deserializer.deserialize(f16);
const inf_check_f16 = try deserializer.deserialize(f16);
const nan_check_f32 = try deserializer.deserialize(f32);
deserializer.alignToByte();
const inf_check_f32 = try deserializer.deserialize(f32);
const nan_check_f64 = try deserializer.deserialize(f64);
const inf_check_f64 = try deserializer.deserialize(f64);
//const nan_check_f128 = try deserializer.deserialize(f128);
//const inf_check_f128 = try deserializer.deserialize(f128);
expect(std.math.isNan(nan_check_f16));
expect(std.math.isInf(inf_check_f16));
expect(std.math.isNan(nan_check_f32));
expect(std.math.isInf(inf_check_f32));
expect(std.math.isNan(nan_check_f64));
expect(std.math.isInf(inf_check_f64));
//expect(std.math.isNan(nan_check_f128));
//expect(std.math.isInf(inf_check_f128));
}
test "Serializer/Deserializer Int: Inf/NaN" {
try testIntSerializerDeserializerInfNaN(.Big, .Byte);
try testIntSerializerDeserializerInfNaN(.Little, .Byte);
try testIntSerializerDeserializerInfNaN(.Big, .Bit);
try testIntSerializerDeserializerInfNaN(.Little, .Bit);
}
fn testAlternateSerializer(self: var, serializer: var) !void {
try serializer.serialize(self.f_f16);
}
fn testSerializerDeserializer(comptime endian: builtin.Endian, comptime packing: io.Packing) !void {
const ColorType = enum(u4) {
RGB8 = 1,
RA16 = 2,
R32 = 3,
};
const TagAlign = union(enum(u32)) {
A: u8,
B: u8,
C: u8,
};
const Color = union(ColorType) {
RGB8: struct {
r: u8,
g: u8,
b: u8,
a: u8,
},
RA16: struct {
r: u16,
a: u16,
},
R32: u32,
};
const PackedStruct = packed struct {
f_i3: i3,
f_u2: u2,
};
//to test custom serialization
const Custom = struct {
f_f16: f16,
f_unused_u32: u32,
pub fn deserialize(self: *@This(), deserializer: var) !void {
try deserializer.deserializeInto(&self.f_f16);
self.f_unused_u32 = 47;
}
pub const serialize = testAlternateSerializer;
};
const MyStruct = struct {
f_i3: i3,
f_u8: u8,
f_tag_align: TagAlign,
f_u24: u24,
f_i19: i19,
f_void: void,
f_f32: f32,
f_f128: f128,
f_packed_0: PackedStruct,
f_i7arr: [10]i7,
f_of64n: ?f64,
f_of64v: ?f64,
f_color_type: ColorType,
f_packed_1: PackedStruct,
f_custom: Custom,
f_color: Color,
};
const my_inst = MyStruct{
.f_i3 = -1,
.f_u8 = 8,
.f_tag_align = TagAlign{ .B = 148 },
.f_u24 = 24,
.f_i19 = 19,
.f_void = {},
.f_f32 = 32.32,
.f_f128 = 128.128,
.f_packed_0 = PackedStruct{ .f_i3 = -1, .f_u2 = 2 },
.f_i7arr = [10]i7{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },
.f_of64n = null,
.f_of64v = 64.64,
.f_color_type = ColorType.R32,
.f_packed_1 = PackedStruct{ .f_i3 = 1, .f_u2 = 1 },
.f_custom = Custom{ .f_f16 = 38.63, .f_unused_u32 = 47 },
.f_color = Color{ .R32 = 123822 },
};
var data_mem: [@sizeOf(MyStruct)]u8 = undefined;
var out = io.fixedBufferStream(&data_mem);
var serializer = serializer(endian, packing, out.outStream());
var in = io.fixedBufferStream(&data_mem);
var deserializer = deserializer(endian, packing, in.inStream());
try serializer.serialize(my_inst);
const my_copy = try deserializer.deserialize(MyStruct);
expect(meta.eql(my_copy, my_inst));
}
test "Serializer/Deserializer generic" {
if (std.Target.current.os.tag == .windows) {
// TODO https://github.com/ziglang/zig/issues/508
return error.SkipZigTest;
}
try testSerializerDeserializer(builtin.Endian.Big, .Byte);
try testSerializerDeserializer(builtin.Endian.Little, .Byte);
try testSerializerDeserializer(builtin.Endian.Big, .Bit);
try testSerializerDeserializer(builtin.Endian.Little, .Bit);
}
fn testBadData(comptime endian: builtin.Endian, comptime packing: io.Packing) !void {
const E = enum(u14) {
One = 1,
Two = 2,
};
const A = struct {
e: E,
};
const C = union(E) {
One: u14,
Two: f16,
};
var data_mem: [4]u8 = undefined;
var out = io.fixedBufferStream.init(&data_mem);
var serializer = serializer(endian, packing, out.outStream());
var in = io.fixedBufferStream(&data_mem);
var deserializer = deserializer(endian, packing, in.inStream());
try serializer.serialize(@as(u14, 3));
expectError(error.InvalidEnumTag, deserializer.deserialize(A));
out.pos = 0;
try serializer.serialize(@as(u14, 3));
try serializer.serialize(@as(u14, 88));
expectError(error.InvalidEnumTag, deserializer.deserialize(C));
}
test "Deserializer bad data" {
try testBadData(.Big, .Byte);
try testBadData(.Little, .Byte);
try testBadData(.Big, .Bit);
try testBadData(.Little, .Bit);
} | lib/std/io/serialization.zig |
const std = @import("std");
const io = std.io;
const math = std.math;
const mem = std.mem;
const assert = std.debug.assert;
const MAXBITS = 15;
const MAXLCODES = 286;
const MAXDCODES = 30;
const MAXCODES = MAXLCODES + MAXDCODES;
const FIXLCODES = 288;
// The maximum length of a Huffman code's prefix we can decode using the fast
// path. The factor 9 is inherited from Zlib, tweaking the value showed little
// or no changes in the profiler output.
const PREFIX_LUT_BITS = 9;
const Huffman = struct {
const LUTEntry = packed struct { symbol: u16 align(4), len: u16 };
// Number of codes for each possible length
count: [MAXBITS + 1]u16,
// Mapping between codes and symbols
symbol: [MAXCODES]u16,
// The decoding process uses a trick explained by <NAME> in [1].
// We basically precompute for a fixed number of codes (0 <= x <= 2^N-1)
// the symbol and the effective code length we'd get if the decoder was run
// on the given N-bit sequence.
// A code with length 0 means the sequence is not a valid prefix for this
// canonical Huffman code and we have to decode it using a slower method.
//
// [1] https://github.com/madler/zlib/blob/v1.2.11/doc/algorithm.txt#L58
prefix_lut: [1 << PREFIX_LUT_BITS]LUTEntry,
// The following info refer to the codes of length PREFIX_LUT_BITS+1 and are
// used to bootstrap the bit-by-bit reading method if the fast-path fails.
last_code: u16,
last_index: u16,
min_code_len: u16,
fn construct(self: *Huffman, code_length: []const u16) !void {
for (self.count) |*val| {
val.* = 0;
}
self.min_code_len = math.maxInt(u16);
for (code_length) |len| {
if (len != 0 and len < self.min_code_len)
self.min_code_len = len;
self.count[len] += 1;
}
// All zero.
if (self.count[0] == code_length.len)
return;
var left: isize = 1;
for (self.count[1..]) |val| {
// Each added bit doubles the amount of codes.
left *= 2;
// Make sure the number of codes with this length isn't too high.
left -= @as(isize, @bitCast(i16, val));
if (left < 0)
return error.InvalidTree;
}
// Compute the offset of the first symbol represented by a code of a
// given length in the symbol table, together with the first canonical
// Huffman code for that length.
var offset: [MAXBITS + 1]u16 = undefined;
var codes: [MAXBITS + 1]u16 = undefined;
{
offset[1] = 0;
codes[1] = 0;
var len: usize = 1;
while (len < MAXBITS) : (len += 1) {
offset[len + 1] = offset[len] + self.count[len];
codes[len + 1] = (codes[len] + self.count[len]) << 1;
}
}
self.prefix_lut = mem.zeroes(@TypeOf(self.prefix_lut));
for (code_length) |len, symbol| {
if (len != 0) {
// Fill the symbol table.
// The symbols are assigned sequentially for each length.
self.symbol[offset[len]] = @truncate(u16, symbol);
// Track the last assigned offset.
offset[len] += 1;
}
if (len == 0 or len > PREFIX_LUT_BITS)
continue;
// Given a Huffman code of length N we transform it into an index
// into the lookup table by reversing its bits and filling the
// remaining bits (PREFIX_LUT_BITS - N) with every possible
// combination of bits to act as a wildcard.
const bits_to_fill = @intCast(u5, PREFIX_LUT_BITS - len);
const rev_code = bitReverse(u16, codes[len], len);
// Track the last used code, but only for lengths < PREFIX_LUT_BITS.
codes[len] += 1;
var j: usize = 0;
while (j < @as(usize, 1) << bits_to_fill) : (j += 1) {
const index = rev_code | (j << @intCast(u5, len));
assert(self.prefix_lut[index].len == 0);
self.prefix_lut[index] = .{
.symbol = @truncate(u16, symbol),
.len = @truncate(u16, len),
};
}
}
self.last_code = codes[PREFIX_LUT_BITS + 1];
self.last_index = offset[PREFIX_LUT_BITS + 1] - self.count[PREFIX_LUT_BITS + 1];
}
};
// Reverse bit-by-bit a N-bit code.
fn bitReverse(comptime T: type, value: T, N: usize) T {
const r = @bitReverse(T, value);
return r >> @intCast(math.Log2Int(T), @typeInfo(T).Int.bits - N);
}
pub fn InflateStream(comptime ReaderType: type) type {
return struct {
const Self = @This();
pub const Error = ReaderType.Error || error{
EndOfStream,
BadCounts,
InvalidBlockType,
InvalidDistance,
InvalidFixedCode,
InvalidLength,
InvalidStoredSize,
InvalidSymbol,
InvalidTree,
MissingEOBCode,
NoLastLength,
OutOfCodes,
};
pub const Reader = io.Reader(*Self, Error, read);
inner_reader: ReaderType,
// True if the decoder met the end of the compressed stream, no further
// data can be decompressed
seen_eos: bool,
state: union(enum) {
// Parse a compressed block header and set up the internal state for
// decompressing its contents.
DecodeBlockHeader: void,
// Decode all the symbols in a compressed block.
DecodeBlockData: void,
// Copy N bytes of uncompressed data from the underlying stream into
// the window.
Copy: usize,
// Copy 1 byte into the window.
CopyLit: u8,
// Copy L bytes from the window itself, starting from D bytes
// behind.
CopyFrom: struct { distance: u16, length: u16 },
},
// Sliding window for the LZ77 algorithm
window: struct {
const WSelf = @This();
// invariant: buffer length is always a power of 2
buf: []u8,
// invariant: ri <= wi
wi: usize = 0, // Write index
ri: usize = 0, // Read index
el: usize = 0, // Number of readable elements
fn readable(self: *WSelf) usize {
return self.el;
}
fn writable(self: *WSelf) usize {
return self.buf.len - self.el;
}
// Insert a single byte into the window.
// Returns 1 if there's enough space for the new byte and 0
// otherwise.
fn append(self: *WSelf, value: u8) usize {
if (self.writable() < 1) return 0;
self.appendUnsafe(value);
return 1;
}
// Insert a single byte into the window.
// Assumes there's enough space.
inline fn appendUnsafe(self: *WSelf, value: u8) void {
self.buf[self.wi] = value;
self.wi = (self.wi + 1) & (self.buf.len - 1);
self.el += 1;
}
// Fill dest[] with data from the window, starting from the read
// position. This updates the read pointer.
// Returns the number of read bytes or 0 if there's nothing to read
// yet.
fn read(self: *WSelf, dest: []u8) usize {
const N = math.min(dest.len, self.readable());
if (N == 0) return 0;
if (self.ri + N < self.buf.len) {
// The data doesn't wrap around
mem.copy(u8, dest, self.buf[self.ri .. self.ri + N]);
} else {
// The data wraps around the buffer, split the copy
std.mem.copy(u8, dest, self.buf[self.ri..]);
// How much data we've copied from `ri` to the end
const r = self.buf.len - self.ri;
std.mem.copy(u8, dest[r..], self.buf[0 .. N - r]);
}
self.ri = (self.ri + N) & (self.buf.len - 1);
self.el -= N;
return N;
}
// Copy `length` bytes starting from `distance` bytes behind the
// write pointer.
// Be careful as the length may be greater than the distance, that's
// how the compressor encodes run-length encoded sequences.
fn copyFrom(self: *WSelf, distance: usize, length: usize) usize {
const N = math.min(length, self.writable());
if (N == 0) return 0;
// TODO: Profile and, if needed, replace with smarter juggling
// of the window memory for the non-overlapping case.
var i: usize = 0;
while (i < N) : (i += 1) {
const index = (self.wi -% distance) & (self.buf.len - 1);
self.appendUnsafe(self.buf[index]);
}
return N;
}
},
// Compressor-local Huffman tables used to decompress blocks with
// dynamic codes.
huffman_tables: [2]Huffman = undefined,
// Huffman tables used for decoding length/distance pairs.
hdist: *Huffman,
hlen: *Huffman,
// Temporary buffer for the bitstream.
// Bits 0..`bits_left` are filled with data, the remaining ones are zeros.
bits: u32,
bits_left: usize,
fn peekBits(self: *Self, bits: usize) !u32 {
while (self.bits_left < bits) {
const byte = try self.inner_reader.readByte();
self.bits |= @as(u32, byte) << @intCast(u5, self.bits_left);
self.bits_left += 8;
}
const mask = (@as(u32, 1) << @intCast(u5, bits)) - 1;
return self.bits & mask;
}
fn readBits(self: *Self, bits: usize) !u32 {
const val = self.peekBits(bits);
self.discardBits(bits);
return val;
}
fn discardBits(self: *Self, bits: usize) void {
self.bits >>= @intCast(u5, bits);
self.bits_left -= bits;
}
fn stored(self: *Self) !void {
// Discard the remaining bits, the length field is always
// byte-aligned (and so is the data).
self.discardBits(self.bits_left);
const length = try self.inner_reader.readIntLittle(u16);
const length_cpl = try self.inner_reader.readIntLittle(u16);
if (length != ~length_cpl)
return error.InvalidStoredSize;
self.state = .{ .Copy = length };
}
fn fixed(self: *Self) !void {
comptime var lencode: Huffman = undefined;
comptime var distcode: Huffman = undefined;
// The Huffman codes are specified in the RFC1951, section 3.2.6
comptime {
@setEvalBranchQuota(100000);
const len_lengths =
[_]u16{8} ** 144 ++
[_]u16{9} ** 112 ++
[_]u16{7} ** 24 ++
[_]u16{8} ** 8;
assert(len_lengths.len == FIXLCODES);
try lencode.construct(len_lengths[0..]);
const dist_lengths = [_]u16{5} ** MAXDCODES;
try distcode.construct(dist_lengths[0..]);
}
self.hlen = &lencode;
self.hdist = &distcode;
self.state = .DecodeBlockData;
}
fn dynamic(self: *Self) !void {
// Number of length codes
const nlen = (try self.readBits(5)) + 257;
// Number of distance codes
const ndist = (try self.readBits(5)) + 1;
// Number of code length codes
const ncode = (try self.readBits(4)) + 4;
if (nlen > MAXLCODES or ndist > MAXDCODES)
return error.BadCounts;
// Permutation of code length codes
const ORDER = [19]u16{
16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4,
12, 3, 13, 2, 14, 1, 15,
};
// Build the Huffman table to decode the code length codes
var lencode: Huffman = undefined;
{
var lengths = std.mem.zeroes([19]u16);
// Read the code lengths, missing ones are left as zero
for (ORDER[0..ncode]) |val| {
lengths[val] = @intCast(u16, try self.readBits(3));
}
try lencode.construct(lengths[0..]);
}
// Read the length/literal and distance code length tables.
// Zero the table by default so we can avoid explicitly writing out
// zeros for codes 17 and 18
var lengths = std.mem.zeroes([MAXCODES]u16);
var i: usize = 0;
while (i < nlen + ndist) {
const symbol = try self.decode(&lencode);
switch (symbol) {
0...15 => {
lengths[i] = symbol;
i += 1;
},
16 => {
// repeat last length 3..6 times
if (i == 0) return error.NoLastLength;
const last_length = lengths[i - 1];
const repeat = 3 + (try self.readBits(2));
const last_index = i + repeat;
while (i < last_index) : (i += 1) {
lengths[i] = last_length;
}
},
17 => {
// repeat zero 3..10 times
i += 3 + (try self.readBits(3));
},
18 => {
// repeat zero 11..138 times
i += 11 + (try self.readBits(7));
},
else => return error.InvalidSymbol,
}
}
if (i > nlen + ndist)
return error.InvalidLength;
// Check if the end of block code is present
if (lengths[256] == 0)
return error.MissingEOBCode;
try self.huffman_tables[0].construct(lengths[0..nlen]);
try self.huffman_tables[1].construct(lengths[nlen .. nlen + ndist]);
self.hlen = &self.huffman_tables[0];
self.hdist = &self.huffman_tables[1];
self.state = .DecodeBlockData;
}
fn codes(self: *Self, lencode: *Huffman, distcode: *Huffman) !bool {
// Size base for length codes 257..285
const LENS = [29]u16{
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258,
};
// Extra bits for length codes 257..285
const LEXT = [29]u16{
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0,
};
// Offset base for distance codes 0..29
const DISTS = [30]u16{
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577,
};
// Extra bits for distance codes 0..29
const DEXT = [30]u16{
0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
};
while (true) {
const symbol = try self.decode(lencode);
switch (symbol) {
0...255 => {
// Literal value
const c = @truncate(u8, symbol);
if (self.window.append(c) == 0) {
self.state = .{ .CopyLit = c };
return false;
}
},
256 => {
// End of block symbol
return true;
},
257...285 => {
// Length/distance pair
const length_symbol = symbol - 257;
const length = LENS[length_symbol] +
@intCast(u16, try self.readBits(LEXT[length_symbol]));
const distance_symbol = try self.decode(distcode);
const distance = DISTS[distance_symbol] +
@intCast(u16, try self.readBits(DEXT[distance_symbol]));
if (distance > self.window.buf.len)
return error.InvalidDistance;
const written = self.window.copyFrom(distance, length);
if (written != length) {
self.state = .{
.CopyFrom = .{
.distance = distance,
.length = length - @truncate(u16, written),
},
};
return false;
}
},
else => return error.InvalidFixedCode,
}
}
}
fn decode(self: *Self, h: *Huffman) !u16 {
// Using u32 instead of u16 to reduce the number of casts needed.
var prefix: u32 = 0;
// Fast path, read some bits and hope they're the prefix of some code.
// We can't read PREFIX_LUT_BITS as we don't want to read past the
// deflate stream end, use an incremental approach instead.
var code_len = h.min_code_len;
while (true) {
_ = try self.peekBits(code_len);
// Small optimization win, use as many bits as possible in the
// table lookup.
prefix = self.bits & ((1 << PREFIX_LUT_BITS) - 1);
const lut_entry = &h.prefix_lut[prefix];
// The code is longer than PREFIX_LUT_BITS!
if (lut_entry.len == 0)
break;
// If the code lenght doesn't increase we found a match.
if (lut_entry.len <= code_len) {
self.discardBits(code_len);
return lut_entry.symbol;
}
code_len = lut_entry.len;
}
// The sequence we've read is not a prefix of any code of length <=
// PREFIX_LUT_BITS, keep decoding it using a slower method.
prefix = try self.readBits(PREFIX_LUT_BITS);
// Speed up the decoding by starting from the first code length
// that's not covered by the table.
var len: usize = PREFIX_LUT_BITS + 1;
var first: usize = h.last_code;
var index: usize = h.last_index;
// Reverse the prefix so that the LSB becomes the MSB and make space
// for the next bit.
var code = bitReverse(u32, prefix, PREFIX_LUT_BITS + 1);
while (len <= MAXBITS) : (len += 1) {
code |= try self.readBits(1);
const count = h.count[len];
if (code < first + count) {
return h.symbol[index + (code - first)];
}
index += count;
first += count;
first <<= 1;
code <<= 1;
}
return error.OutOfCodes;
}
fn step(self: *Self) !void {
while (true) {
switch (self.state) {
.DecodeBlockHeader => {
// The compressed stream is done.
if (self.seen_eos) return;
const last = @intCast(u1, try self.readBits(1));
const kind = @intCast(u2, try self.readBits(2));
self.seen_eos = last != 0;
// The next state depends on the block type.
switch (kind) {
0 => try self.stored(),
1 => try self.fixed(),
2 => try self.dynamic(),
3 => return error.InvalidBlockType,
}
},
.DecodeBlockData => {
if (!try self.codes(self.hlen, self.hdist)) {
return;
}
self.state = .DecodeBlockHeader;
},
.Copy => |*length| {
const N = math.min(self.window.writable(), length.*);
// TODO: This loop can be more efficient. On the other
// hand uncompressed blocks are not that common so...
var i: usize = 0;
while (i < N) : (i += 1) {
var tmp: [1]u8 = undefined;
if ((try self.inner_reader.read(&tmp)) != 1) {
// Unexpected end of stream, keep this error
// consistent with the use of readBitsNoEof.
return error.EndOfStream;
}
self.window.appendUnsafe(tmp[0]);
}
if (N != length.*) {
length.* -= N;
return;
}
self.state = .DecodeBlockHeader;
},
.CopyLit => |c| {
if (self.window.append(c) == 0) {
return;
}
self.state = .DecodeBlockData;
},
.CopyFrom => |*info| {
const written = self.window.copyFrom(info.distance, info.length);
if (written != info.length) {
info.length -= @truncate(u16, written);
return;
}
self.state = .DecodeBlockData;
},
}
}
}
fn init(source: ReaderType, window_slice: []u8) Self {
assert(math.isPowerOfTwo(window_slice.len));
return Self{
.inner_reader = source,
.window = .{ .buf = window_slice },
.seen_eos = false,
.state = .DecodeBlockHeader,
.hdist = undefined,
.hlen = undefined,
.bits = 0,
.bits_left = 0,
};
}
// Implements the io.Reader interface
pub fn read(self: *Self, buffer: []u8) Error!usize {
if (buffer.len == 0)
return 0;
// Try reading as much as possible from the window
var read_amt: usize = self.window.read(buffer);
while (read_amt < buffer.len) {
// Run the state machine, we can detect the "effective" end of
// stream condition by checking if any progress was made.
// Why "effective"? Because even though `seen_eos` is true we
// may still have to finish processing other decoding steps.
try self.step();
// No progress was made
if (self.window.readable() == 0)
break;
read_amt += self.window.read(buffer[read_amt..]);
}
return read_amt;
}
pub fn reader(self: *Self) Reader {
return .{ .context = self };
}
};
}
pub fn inflateStream(reader: anytype, window_slice: []u8) InflateStream(@TypeOf(reader)) {
return InflateStream(@TypeOf(reader)).init(reader, window_slice);
} | lib/std/compress/deflate.zig |
const std = @import("std");
const enum_parser = @import("enum_parser.zig");
const fmt = @import("fmt_structs.zig");
const expect = std.testing.expect;
const expectError = std.testing.expectError;
const str = []const u8;
const print = std.debug.print;
const Allocator = std.mem.Allocator;
const TokenIterator = std.mem.TokenIterator;
const tools = @import("tools.zig");
const streql = tools.streql;
const recursivePrintTypeInfoStruct = tools.recursivePrintTypeInfoStruct;
pub const Join = fmt.Join;
pub const Match = fmt.Match;
pub const Unformat = fmt.Unformat;
pub const Error = error{
ParseError,
ParseIntError,
EndIterError,
NotImplementedError,
DelimByteError,
} || Allocator.Error || enum_parser.Error;
pub fn ParserStr(comptime T: type) (fn (?*Allocator, str) Error!Unformat(T)) {
return struct {
const wrappedParseFn = Parser(T);
fn parseWrap(alloc: ?*Allocator, val: str) Error!Unformat(T) {
// in order to re-use the Parser(T) provided function when parsing
// *formatted* structs, we want a dummy iterator that returns only
// one token: the entire string. That's why I call tokenize with a
// delimiter that's almost never used in practice: 0x0. So if 0x0
// is encountered within a string (*not* at the last position, as
// in a C string), it raises an error.
// TODO: How to do create a dummy TokenIterator without the usual
// .next() function?
const delim_bytes: []const u8 = ([1]u8{0x0})[0..];
var dummy_iter = std.mem.tokenize(val, delim_bytes);
if (dummy_iter.next()) |token| {
if (token.len != val.len) {
return Error.DelimByteError;
}
} else {
return Error.DelimByteError;
}
// re-init token iterator:
dummy_iter = std.mem.tokenize(val, delim_bytes);
var parsed: T = try wrappedParseFn(alloc, &dummy_iter);
// TODO:
// 1. not sure if this is safe,
// 2. is there a way to copy data without realloc an Unformat(T)?
var unformatted: Unformat(T) = undefined;
fmt.castUnformatRecur(T, &parsed, &unformatted);
return unformatted;
}
}.parseWrap;
}
/// A parser function for a variety of complicated, nested types known at
/// compile time. Currently, it supports structs, slices, arrays, integers,
/// []const u8, and enums.
pub fn Parser(comptime T: type) (fn (?*Allocator, *TokenIterator) Error!T) {
return struct {
fn parse(opt_alloc: ?*Allocator, iter: *TokenIterator) Error!T {
return parseRecur(T, opt_alloc, iter);
}
/// Parse a struct of type t. fields[i] == 1 iff we ignore the optional.
/// If it fails, the caller can backtrack!
fn parseStructOptions(
opt_alloc: ?*Allocator,
comptime n_fields: u32,
comptime t: type,
comptime fields: []const std.builtin.TypeInfo.StructField,
options: [n_fields]u32,
iter: *TokenIterator,
) Error!t {
var skip = false;
var failed = false;
var parsed: t = undefined;
inline for (fields) |f, i| {
comptime const typeinfo = @typeInfo(t);
comptime var subtype = f.field_type;
skip = false;
if (@typeInfo(subtype) == .Optional) {
// unwrap Optionals here, to allow for backtracking.
if (options[i] == 0) {
subtype = @typeInfo(subtype).Optional.child;
} else {
@field(parsed, f.name) = null;
// TODO: could be simplified using continue! but not
// supported with comptime now, it seems.
skip = true;
}
}
if (!skip) {
const parse_attempt = parseRecur(subtype, opt_alloc, iter) catch {
failed = true;
return Error.ParseError;
//break :blk;
};
@field(parsed, f.name) = parse_attempt;
skip = false;
}
}
return parsed;
}
fn parseRecur(
comptime t: type,
opt_alloc: ?*Allocator,
iter: *TokenIterator,
) Error!t {
var parsed: t = undefined;
//print("> {}\n", .{@typeInfo(t)});
if (t == str) { // TODO move to switch()
const v = iter.next();
// for debugging with assembly.
// const v = @call(.{ .modifier = .never_inline }, iter.next, .{});
return v orelse Error.EndIterError;
}
comptime var typeinfo = @typeInfo(t);
switch (typeinfo) {
.Int => {
if (iter.next()) |val| {
const parsed_int: t = std.fmt.parseInt(t, val, 10) catch {
return Error.ParseError;
};
return parsed_int;
} else {
return Error.EndIterError;
}
},
.Optional => {
comptime var child_type = typeinfo.Optional.child;
return parseRecur(child_type, opt_alloc, iter) catch null;
},
.Enum => {
const enumParser = try enum_parser.EnumParser(t);
if (iter.next()) |val| {
return try enumParser(val);
} else {
return Error.EndIterError;
}
},
.Struct => {
comptime const is_fmt = fmt.isFormattedStruct(t);
if (is_fmt and t.fmt_struct == .join_struct) {
// TODO call t.parse?
var sub_iter: std.mem.TokenIterator = undefined;
if (iter.next()) |val| {
sub_iter = t.tokenize(val);
return t{
.child = try parseRecur(t.child_type, opt_alloc, &sub_iter),
};
} else {
return Error.ParseError;
}
} else if (is_fmt and t.fmt_struct == .match_struct) {
const iter_backup = iter.index;
const maybe_matched = try parseRecur(str, opt_alloc, iter);
// print("cur:{},to_match:{}\n", .{ maybe_matched, t.to_match });
if (streql(maybe_matched, t.to_match)) {
return t{};
} else {
return Error.ParseError;
}
} else {
const n_fields = typeinfo.Struct.fields.len;
comptime const n_options = computeStructMaxNValues(n_fields, typeinfo);
comptime const n_combinations = nFieldsCombinations(n_options[0..]);
comptime const fields = typeinfo.Struct.fields;
const backup_iter = iter.index;
var comb_i: u32 = 0;
// try to parse with every possible combination of
// optional and union tagswhen it fails, backtrack
// (rewind iterator) and try the next combination
while (comb_i < n_combinations) : (comb_i += 1) {
iter.index = backup_iter;
const options = intToFieldsOptions(n_fields, comb_i, n_options);
parsed = parseStructOptions(opt_alloc, n_fields, t, fields, options, iter) catch {
continue;
};
return parsed;
}
return Error.ParseError;
}
},
.Pointer => {
comptime const subtype = typeinfo.Pointer.child;
if (typeinfo.Pointer.size == .Slice) {
var array = std.ArrayList(subtype).init(opt_alloc.?);
while (true) {
const e = parseRecur(subtype, opt_alloc, iter) catch |e| {
if (e == Error.NotImplementedError) {
return e;
} else {
break;
}
};
try array.append(e);
}
return array.toOwnedSlice();
// TODO Could we turn opt_alloc to be comptime known?
// thus we could check that when the type
// require dynamic memory allocation at comptime,
// alloc is not null? Or is it a misuse of optionals?
} else {
var ret = try opt_alloc.?.create(subtype);
//print("create:{}\n", .{@ptrToInt(ret)});
ret.* = parseRecur(subtype, opt_alloc, iter) catch |e| {
//print("destroy:{}\n", .{@ptrToInt(ret)});
opt_alloc.?.destroy(ret);
return e;
};
return ret;
}
},
.Union => {
if (typeinfo.Union.tag_type) |tag_type| {
comptime const n_values = typeinfo.Union.fields.len;
comptime const fields = typeinfo.Union.fields;
const backup_iter = iter.index;
comptime var i = 0;
var res: t = undefined;
inline while (i < n_values) : (i += 1) {
iter.index = backup_iter;
comptime var subtype = fields[i].field_type;
const parsed_subtype = parseRecur(?subtype, opt_alloc, iter) catch undefined;
if (parsed_subtype) |p| {
return @unionInit(t, fields[i].name, p);
}
}
return Error.ParseError;
} else {
return Error.NotImplementedError;
}
},
.Array => {
comptime const subtype = typeinfo.Array.child;
if (typeinfo.Array.sentinel) |v| {
return Error.NotImplementedError;
}
const len: comptime_int = typeinfo.Array.len;
var array: [len]subtype = [_]subtype{undefined} ** len;
var i: u32 = 0;
while (i < len) : (i += 1) {
array[i] = parseRecur(subtype, opt_alloc, iter) catch |e| {
if (e == Error.NotImplementedError) {
return e;
} else {
break;
}
};
}
return array;
},
else => {
return Error.NotImplementedError;
},
}
return parsed;
}
}.parse;
}
// helpers
fn structFirstFieldType(comptime T: type) type {
return @typeInfo(T).Struct.fields[0].field_type;
}
/// For each field in the struct, return the number of possible choices - 1:
/// - optionals: 2-1=1 choices (present or absent),
/// (cancelled: - tagged unions: N-1 choices)
/// - all the other types: 0 choices.
fn computeStructMaxNValues(
comptime n_fields: u32,
comptime typeinfo: std.builtin.TypeInfo,
) [n_fields]u32 {
var n_options = [_]u32{0} ** n_fields;
inline for (typeinfo.Struct.fields) |f, i| {
if (@typeInfo(f.field_type) == .Optional) {
n_options[i] = 1;
}
//else if (@typeInfo(f.field_type) == .Union) {
//n_options[i] = @typeInfo(f.field_type).tag_type.?.fields.len;
// n_options[i] = @typeInfo(f.field_type).Union.fields.len;
//}
}
return n_options;
}
/// Encode an integer i in the basis defined by n_options. See examples:
/// examples:
/// - if n_options = {7, ..., 7}, then it is base 8 encoding.
/// - if n_options = {2, 0, 1}, then intToFieldsOptions will return:
/// * i = 0: {0, 0, 0}
/// * i = 1: {0, 0, 1}
/// * i = 2: {1, 0, 0}
/// * i = 3: {1, 0, 1}
/// * i = 4: {2, 0, 0}
/// * i = 5: {2, 0, 1}
fn intToFieldsOptions(comptime n: u32, i: u32, n_options: [n]u32) [n]u32 {
var options = [_]u32{0} ** n;
var multiples: [n]u32 = undefined;
// multiples[i] = prod_{j<i} (n_options[j]+1)
multiples[0] = 1;
var k: u32 = 1;
while (k < n) : (k += 1) {
multiples[k] = (n_options[k - 1] + 1) * multiples[k - 1];
}
var j: u32 = n - 1;
var rest: u32 = i;
while (true) : (j -= 1) {
if (rest < multiples[j]) {
options[j] = 0;
} else {
options[j] = rest / multiples[j];
rest = rest % multiples[j];
}
if (j == 0)
break;
}
return options;
}
fn nFieldsCombinations(n_options: []const u32) u32 {
var prod: u32 = 1;
for (n_options) |e|
prod *= (e + 1);
return prod;
}
test "helper int 2 field" {
const n_options: [5]u32 = .{ 1, 0, 1, 5, 3 };
const n_combinations = nFieldsCombinations(&n_options);
expect(n_combinations == 96);
const u = intToFieldsOptions(n_options.len, n_combinations - 1, n_options);
expect(std.mem.eql(u32, &u, &n_options));
const v = intToFieldsOptions(n_options.len, 9, n_options);
const res: [5]u32 = .{ 1, 0, 0, 2, 0 };
expect(std.mem.eql(u32, &res, &v));
}
// tests
test "parser slice int" {
var alloc = std.testing.allocator;
const p = try Parser([]u32)(alloc, &std.mem.tokenize("1 3 5 3", " "));
defer alloc.free(p);
expect(p.len == 4);
expect((p[0] == 1) and (p[1] == 3) and (p[2] == 5) and (p[3] == 3));
}
test "parser struct" {
var alloc = std.testing.allocator;
const Pair = struct {
a: u32,
b: u32,
};
const pair = try Parser(Pair)(alloc, &std.mem.tokenize("2 49", " "));
expect(pair.a == 2);
expect(pair.b == 49);
}
test "parser struct enum" {
var alloc = std.testing.allocator;
const Result = enum {
ok,
not_ok,
};
const Pair = struct {
res: Result,
a: u32,
};
const pair = try Parser(Pair)(alloc, &std.mem.tokenize("ok 49", " "));
expect(pair.res == .ok);
expect(pair.a == 49);
}
test "parser array struct" {
var alloc = std.testing.allocator;
const Pair = struct {
a: u32,
b: u32,
};
const OtherPair = struct {
a: [2]u32,
};
const pairs = "6 78 999 0";
const pair2 = try Parser([2]OtherPair)(alloc, &std.mem.tokenize(pairs, " "));
expect(pair2[0].a[1] == 78 and pair2[1].a[1] == 0);
const pair_slice: []Pair = try Parser([]Pair)(alloc, &std.mem.tokenize(pairs, " "));
defer alloc.free(pair_slice);
expect(pair_slice[0].a == 6 and pair_slice[1].a == 999);
}
test "fmt parser slice" {
var alloc = std.testing.allocator;
const q = try ParserStr(Join([]u32, " "))(alloc, "1 3 5 3");
defer alloc.free(q);
expect((q[0] == 1) and (q[1] == 3) and (q[2] == 5) and (q[3] == 3));
}
test "parser optional" {
const parser = Parser(?u32);
const q = try parser(null, &std.mem.tokenize("", " "));
expect(q == null);
}
test "parser recursive base" {
var alloc = std.testing.allocator;
const ChainedList = struct {
_0: Match("("),
val: u32,
next: ?*@This(),
_1: Match(")"),
pub fn deinit(list: *const @This(), alloc_: *std.mem.Allocator) void {
var opt_cur: ?*const @This() = list;
while (opt_cur) |cur| {
var next: ?*@This() = cur.next;
opt_cur = next;
alloc_.destroy(cur);
}
}
pub fn sum(list: *const @This()) u32 {
var acc: u32 = 0;
var opt_cur: ?*const @This() = list;
while (opt_cur) |cur| {
acc += cur.val;
opt_cur = cur.next;
}
return acc;
}
};
const parser = Parser(*ChainedList);
const list = try parser(
alloc,
&std.mem.tokenize("( 3 ( 32 ( 5 ) ) )", " "),
);
defer list.deinit(alloc);
expect(list.sum() == 3 + 32 + 5);
}
test "parser union" {
var alloc = std.testing.allocator;
const VanillaUnion = union {
a: u32,
b: str,
};
var parser1 = Parser(VanillaUnion);
expectError(Error.NotImplementedError, parser1(alloc, &std.mem.tokenize("32", "\t")));
var parser2 = Parser([]VanillaUnion);
expectError(Error.NotImplementedError, parser2(alloc, &std.mem.tokenize("32 blabla", " ")));
var parser3 = Parser([2]VanillaUnion);
expectError(Error.NotImplementedError, parser3(alloc, &std.mem.tokenize("32 blabla", " ")));
const TaggedUnion = union(enum) {
a: u32,
b: str,
};
const tinfo = @typeInfo(TaggedUnion);
// print("{}\n", .{tinfo});
// print("{}\n", .{tinfo.Union.fields.len});
// print("{}\n", .{@typeInfo(tinfo.Union.tag_type.?)});
// print("{}\n", .{@typeInfo(tinfo.Union.tag_type.?).Enum.fields.len});
const parser = Parser(TaggedUnion);
const parsed = try parser(alloc, &std.mem.tokenize("3", " "));
expect(parsed.a == 3);
const parsed2 = try parser(alloc, &std.mem.tokenize("xyzzyx", " "));
expect(streql(parsed2.b, "xyzzyx"));
const slice_parser = Parser([]TaggedUnion);
const parsed3 = try slice_parser(alloc, &std.mem.tokenize("chaussette 33", " "));
defer alloc.free(parsed3);
expect(streql(parsed3[0].b, "chaussette"));
expect(parsed3[1].a == 33);
const array_parser = Parser([5]TaggedUnion);
const parsed4 = try slice_parser(alloc, &std.mem.tokenize("gism 99 endless blockades 33393", " "));
defer alloc.free(parsed4);
expect(streql(parsed4[0].b, "gism"));
expect(parsed4[1].a == 99);
expect(streql(parsed4[2].b, "endless"));
expect(streql(parsed4[3].b, "blockades"));
expect(parsed4[4].a == 33393);
}
test "parser nested union" {
var alloc = std.testing.allocator;
const E = enum {
ok,
not_ok,
meh,
};
const TaggedUnion = union(enum) {
a: u32,
b: E, // order matters
c: str,
};
const S = struct {
a: u32,
b: TaggedUnion,
c: ?TaggedUnion,
};
const parser = ParserStr(Join([]Join(S, " "), "\n"));
const ex =
\\8 ok
\\92 883
\\222221 delicious
\\21 mmm meh
;
const parsed = try parser(alloc, ex);
defer alloc.free(parsed);
expect(parsed[0].a == 8 and parsed[0].b.b == E.ok and parsed[0].c == null);
expect(parsed[1].a == 92 and parsed[1].b.a == 883);
expect(parsed[2].a == 222221 and streql(parsed[2].b.c, "delicious"));
expect(parsed[3].a == 21 and streql(parsed[3].b.c, "mmm") and parsed[3].c.?.b == E.meh);
}
test "fmt parser join" {
const Pair = struct {
a: u32,
b: u32,
};
const JoinPair = Join(Pair, " ");
expect(fmt.isFormattedStruct(JoinPair));
expect(structFirstFieldType(JoinPair) == Pair);
expect(!fmt.isFormattedStruct(Pair));
const pair = try ParserStr(JoinPair)(null, "28 499992");
expect(pair.a == 28 and pair.b == 499992);
}
test "parser match" {
const A = struct {
_0: Match("A"),
a: u32,
};
const parser = Parser(A);
const parsed = try parser(null, &std.mem.tokenize("A 33", " "));
expect(parsed.a == 33);
const B = struct {
_0: Match("B"),
a: str,
_1: Match("C"),
};
const U = union(enum) {
a: A,
b: B,
};
const parser2 = Parser(U);
const parsed2 = try parser2(null, &std.mem.tokenize("B bobo C", " "));
expect(streql("bobo", parsed2.b.a));
expectError(Error.ParseError, parser2(null, &std.mem.tokenize("B bobo", " ")));
expectError(Error.ParseError, parser2(null, &std.mem.tokenize("bobo C", " ")));
}
test "cast format unformat" {
const Pair = struct {
a: u32,
b: u32,
};
const JoinPair = Join(Pair, " ");
var p = Pair{ .a = 32, .b = 966 };
var p2 = JoinPair{ .child = .{ .a = 76, .b = 99999 } };
var ptr = @ptrCast(*Pair, &p2);
p = ptr.*;
expect(p.a == 76 and p.b == 99999);
}
test "fmt parser join nested" {
var alloc = std.testing.allocator;
const Nested = struct {
c: u32,
d: u32,
};
const PContainer = struct {
a: u32,
b: Join(Nested, ":"),
};
const Container = Unformat(PContainer);
const C = Container{
.a = 3,
.b = .{
.c = 2,
.d = 45,
},
};
expect(C.b.c == (Nested{ .c = 2, .d = 45 }).c);
expect(!fmt.isFormattedStruct(PContainer));
expect(!fmt.isFormattedStruct(Container));
const p = try ParserStr(Join([]u16, ":"))(alloc, "2323:78:333");
defer alloc.free(p);
expect(p.len == 3);
expect((p[0] == 2323) and (p[1] == 78) and (p[2] == 333));
}
test "AoC day7" {
var alloc = std.testing.allocator;
const Color = struct {
n: ?u32,
modifier: str,
color: str,
ignore_bags: ?str,
};
//comptime const n_fields = @typeInfo(Color).Struct.fields.len;
//comptime const n_options = computeStructMaxNValues(n_fields, @typeInfo(Color));
//for (n_options) |o| print("{}\n", .{o});
//const n_combinations = nFieldsCombinations(n_options[0..]);
//var comb_i: u32 = 0;
//while (comb_i < n_combinations) : (comb_i += 1) {
// const options = intToFieldsOptions(n_fields, comb_i, n_options);
// for (options) |o| print("{}-", .{o});
// print("\n", .{});
//}
const LHS_parser = Parser(Color);
const example_1 = "dotted tomato"; // .n and .ignore_bags are absent
var iter_lhs: TokenIterator = std.mem.tokenize(example_1, " ");
const LHS_parsed = try LHS_parser(alloc, &iter_lhs);
expect(streql(LHS_parsed.modifier, "dotted"));
expect(streql(LHS_parsed.color, "tomato"));
const slice_parser = Parser([]Color);
const example_2 = "4 dark tomato bags, 3 plaid orange bags, 5 posh teal bags.";
// all the fields are present here.
var iter = std.mem.tokenize(example_2, " ");
const RHS_parsed = try slice_parser(alloc, &iter);
defer alloc.free(RHS_parsed);
expect(RHS_parsed.len == 3);
expect(RHS_parsed[0].n.? == 4);
expect(streql(RHS_parsed[0].modifier, "dark"));
expect(streql(RHS_parsed[0].color, "tomato"));
expect(RHS_parsed[1].n.? == 3);
expect(streql(RHS_parsed[1].modifier, "plaid"));
expect(streql(RHS_parsed[1].color, "orange"));
expect(RHS_parsed[2].n.? == 5);
expect(streql(RHS_parsed[2].modifier, "posh"));
expect(streql(RHS_parsed[2].color, "teal"));
}
test "AoC day8 (modified)" {
const alloc = std.testing.allocator;
const Opcode = enum {
nop,
acc,
jmp,
};
const Instruction = struct {
opcode: Opcode,
operand: ?i32,
};
// Parser definition:
// within a struct, opcodes and operands are space-separated:
const PInstruction = Join(Instruction, " ");
// parse unknown number of space-separated instructions, separated by \n:
const PInstructions = Join([]PInstruction, "\n");
// name the data structure without formatting
const Instructions = Unformat(PInstructions);
expect(Instructions == []Instruction);
const parser = ParserStr(PInstructions);
const raw_instructions =
\\jmp +109
\\acc +10
\\jmp +18
\\nop
;
const parsed = try parser(alloc, raw_instructions);
defer alloc.free(parsed);
expect(parsed.len == 4);
expect(parsed[2].opcode == .jmp and parsed[2].operand.? == 18);
expect(parsed[3].opcode == .nop and parsed[3].operand == null);
}
test "simple backtrack" {
var alloc = std.testing.allocator;
const NoBacktrack = struct {
a: ?u32,
b: u32,
};
const parser = Parser(NoBacktrack);
const v = try parser(alloc, &std.mem.tokenize("3 4554444", " "));
expect(v.a.? == 3 and v.b == 4554444);
const u = try parser(alloc, &std.mem.tokenize("91733", " "));
expect(u.b == 91733);
const parser_str = ParserStr(NoBacktrack);
const w = try parser_str(alloc, "91733");
expect(w.b == 91733);
}
test "caveat type names" {
var alloc = std.testing.allocator;
const In2 = struct {
a: u32,
b: u32,
};
const In1 = struct {
a: u32,
b: Join(In2, "-"),
};
const ParsableData = Join(In1, " ");
// problem is here: the type created by Unformat will recursively look
// for formatted structs (depth-first search). It finds that In2 has no
// nested formatted structs, i.e. Unformat(Join(In2, "-")) = In2.
// therefore, it doesn't need to change the type of In1.b.
// However, when it tries to unformat ParsableData, it notices that
// Unformat(Join(In1, " ")) != In1 (b/c in the new type, In1.b is of type
// In2). Therefore, it has to create a new type.
// This new type will be identical to In1 in all respects, if we
// recursively compare the TypeInfos of the structures.
// But the pointer .fields at the level of In1 differ!
const Data = Unformat(ParsableData);
const parser = ParserStr(ParsableData);
const parsed = try parser(alloc, "0 1-2");
const manually_created = Data{
.a = 0,
.b = .{
.a = 1,
.b = 2,
},
};
// this gives struct names like this:
// print("\n{}\n", .{parsed});
// print("{}\n", .{manually_created});
}
test "caveat functions in structs" {
const alloc = std.testing.allocator;
const Opcode = enum {
mov,
add,
};
const Instruction = struct {
opcode: Opcode,
two_operands: Join([2]str, " "),
fn exec(i: *@This()) void {
print("Execute {}\n", .{i.opcode});
}
};
const PInstruction = Join(Instruction, " ");
const Instruction_ = Unformat(PInstruction);
// Here is the problem! Instruction_ is like Instruction, except that it
// lost all its decls. Here, it lacks the function exec!
expect(Instruction_ != Instruction);
const parser = ParserStr(PInstruction);
const raw_instructions = "mov R2 R1";
const parsed = try parser(alloc, raw_instructions);
// parsed.exec(); // Fails!!! :-(
} | src/chelar.zig |
const std = @import("std");
const panic = std.debug.panic;
const OutStream = std.io.OutStream;
fn print_to(file: std.fs.File, val: anytype) void {
file.outStream().print("{}", .{val}) catch |err| {
panic("error ({})", .{err});
};
}
pub fn print(val: anytype) void {
print_to(std.io.getStdOut(), val);
}
pub fn puts(val: anytype) void {
print(val);
print("\n");
}
pub fn puts_fmt(comptime format: []const u8, args: anytype) void {
std.io.getStdOut().outStream().print(format, args) catch |err| {
panic("error ({})", .{err});
};
print("\n");
}
pub fn print_e(val: anytype) void {
print_to(std.io.getStdErr(), val);
}
pub fn puts_e(val: anytype) void {
print_e(val);
print_e("\n");
}
pub fn putskv_e(key: []const u8, val: anytype) void {
print_e(key);
print_e(" (");
print_e(val);
print_e(")\n");
}
pub fn puts_fn(fnName: []const u8) void {
print_e(" |-->> ");
print_e(fnName);
print_e("\n");
}
pub fn readStdinAll(buf: [*]u8) []const u8 {
const size_max = 20000;
var i: usize = 0;
const stdin_stream = std.io.getStdIn().inStream();
while (true) {
const byte = stdin_stream.readByte() catch |err| switch (err) {
error.EndOfStream => {
break;
},
else => |e| {
panic("error ({})", .{e});
},
};
buf[i] = byte;
i += 1;
if (size_max <= i) {
panic("error: Too large Input", .{});
}
}
return buf[0..i];
}
pub fn strlen(chars: []const u8) usize {
var i: usize = 0;
while (i < chars.len) : (i += 1) {
if (chars[i] == 0) {
return i;
}
}
return chars.len;
}
pub fn strcpy(dest: [*]u8, src: []const u8) void {
var i: usize = 0;
while (true) : (i += 1) {
dest[i] = src[i];
if (src[i] == 0) {
break;
}
if (strlen(src) - 1 <= i) {
dest[i + 1] = 0;
break;
}
}
}
pub fn indexOf(str: []const u8, ch: u8, from: usize) i32 {
var i = from;
while (true) : (i += 1) {
if (str.len <= i) {
return -1;
}
if (str[i] == 0) {
return -1;
}
if (str[i] == ch) {
break;
}
}
return @intCast(i32, i);
}
pub fn matchAnyChar(chars: []const u8, ch: u8) bool {
return 0 <= indexOf(chars, ch, 0);
}
pub fn dumpStr(str: [*:0]u8) void {
var i: usize = 0;
while (true) : (i += 1) {
print_e("str ");
print_e(i);
print_e(" (");
print_e(str[i]);
print_e(")");
print_e("\n");
if (str[i] == 0) {
break;
}
if (100 <= i) {
print_e("over limit\n");
break;
}
}
}
pub fn substring(dest: [*]u8, src: []const u8, index_start: usize, index_end: usize) void {
var i: usize = 0;
var size = index_end - index_start;
while (i < size) : (i += 1) {
if (src[index_start + i] == 0) {
size = i;
break;
}
dest[i] = src[index_start + i];
}
dest[size] = 0;
}
pub fn strncmp(s1: []const u8, s2: [*:0]const u8, len: usize) bool {
var i: usize = 0;
while (i < len) : (i += 1) {
if (s1[i] != s2[i]) {
return false;
}
}
return true;
}
pub fn strEq(s1: []const u8, s2: []const u8) bool {
if (strlen(s1) != strlen(s2)) {
return false;
}
const len = strlen(s1);
var i: usize = 0;
while (i < len) : (i += 1) {
if (s1[i] != s2[i]) {
return false;
}
}
return true;
}
test "strEq" {
const assert = std.debug.assert;
const testing = std.testing;
const expect = testing.expect;
const expectEqual = testing.expectEqual;
const str: [5]u8 = [_]u8{ 'f', 'o', 'o', 0, 'x' };
assert(true == strEq(&str, "foo"));
assert(false == strEq("foo", "foox"));
assert(true == strEq("foo", "foo"));
}
pub fn strTrim(str: []const u8) []const u8 {
const len = strlen(str);
return str[0..len];
}
pub fn isNumeric(ch: u8) bool {
return '0' <= ch and ch <= '9';
}
pub fn indexOfNonNumeric(str: []const u8, start_index: usize) usize {
var i: usize = start_index;
while (i < str.len) : (i += 1) {
if (!isNumeric(str[i])) {
break;
}
}
return i;
}
pub fn concat(dest: []u8, s1: []const u8, s2: []const u8) void {
var di: usize = 0;
var s1i: usize = 0;
var s2i: usize = 0;
const len1: usize = strlen2(s1);
while (s1i < len1) {
dest[di] = s1[s1i];
di += 1;
s1i += 1;
}
const len2: usize = strlen2(s2);
while (s2i < len2) {
dest[di] = s2[s2i];
di += 1;
s2i += 1;
}
dest[di] = 0;
}
pub fn parseInt(str: []const u8) i32 {
return std.fmt.parseInt(i32, str, 10) catch |err| {
panic("Failed to parse ({})", .{str});
};
}
pub fn bufPrint(buf: []u8, comptime fmt: []const u8, args: anytype) []u8 {
return std.fmt.bufPrint(buf, fmt, args) catch |err| {
panic("err ({})", .{err});
};
} | lib/utils.zig |
pub const Context = extern struct {
params: Params,
itw: f32,
ith: f32,
tex_data: [*c]u8,
// omitted rest of struct
pub fn init(params: *Params) !*Context {
return fonsCreateInternal(params) orelse error.FailedToCreateFONS;
}
pub fn deinit(self: *Context) void {
fonsDeleteInternal(self);
}
};
pub const Params = extern struct {
width: c_int = 256,
height: c_int = 256,
flags: Flags = .top_left,
user_ptr: *anyopaque,
renderCreate: ?fn (?*anyopaque, c_int, c_int) callconv(.C) c_int = null,
renderResize: ?fn (?*anyopaque, c_int, c_int) callconv(.C) c_int = null,
renderUpdate: ?fn (?*anyopaque, [*c]c_int, [*c]const u8) callconv(.C) c_int = null,
};
pub const Flags = enum(u8) {
top_left = 1,
bottom_left = 2,
};
pub const Align = enum(c_int) {
// horizontal
left = 1, // Default
center = 2,
right = 4,
// vertical
top = 8,
middle = 16,
bottom = 32,
baseline = 64,
default = 65,
// combos
left_middle = 17,
center_middle = 18,
right_middle = 20,
top_left = 9,
};
pub const ErrorCode = enum(c_int) {
atlas_full = 1,
scratch_full = 2, // Scratch memory used to render glyphs is full, requested size reported in 'val', you may need to bump up FONS_SCRATCH_BUF_SIZE.
overflow = 3, // Calls to fonsPushState has created too large stack, if you need deep state stack bump up FONS_MAX_STATES.
underflow = 4, // Trying to pop too many states fonsPopState().
};
pub const Quad = extern struct {
x0: f32,
y0: f32,
s0: f32,
t0: f32,
x1: f32,
y1: f32,
s1: f32,
t1: f32,
};
pub const FONSfont = opaque {};
pub const TextIter = extern struct {
x: f32,
y: f32,
nextx: f32,
nexty: f32,
scale: f32,
spacing: f32,
color: c_uint,
codepoint: c_uint,
isize: c_short,
iblur: c_short,
font: ?*FONSfont,
prevGlyphIndex: c_int,
str: [*c]const u8,
next: [*c]const u8,
end: [*c]const u8,
utf8state: c_uint,
};
pub const FONS_INVALID = -1;
pub extern fn fonsCreateInternal(params: [*c]Params) ?*Context;
pub extern fn fonsDeleteInternal(s: ?*Context) void;
pub extern fn fonsSetErrorCallback(s: ?*Context, callback: ?fn (?*anyopaque, c_int, c_int) callconv(.C) void, uptr: ?*anyopaque) void;
pub extern fn fonsGetAtlasSize(s: ?*Context, width: [*c]c_int, height: [*c]c_int) void;
pub extern fn fonsExpandAtlas(s: ?*Context, width: c_int, height: c_int) c_int;
pub extern fn fonsResetAtlas(stash: ?*Context, width: c_int, height: c_int) c_int;
pub extern fn fonsAddFontMem(stash: ?*Context, name: [*c]const u8, data: [*c]const u8, dataSize: c_int, freeData: c_int) c_int;
pub extern fn fonsGetFontByName(s: ?*Context, name: [*c]const u8) c_int;
pub extern fn fonsAddFallbackFont(stash: ?*Context, base: c_int, fallback: c_int) c_int;
pub extern fn fonsPushState(s: ?*Context) void;
pub extern fn fonsPopState(s: ?*Context) void;
pub extern fn fonsClearState(s: ?*Context) void;
pub extern fn fonsSetSize(s: ?*Context, size: f32) void;
pub extern fn fonsSetColor(s: ?*Context, color: c_uint) void;
pub extern fn fonsSetSpacing(s: ?*Context, spacing: f32) void;
pub extern fn fonsSetBlur(s: ?*Context, blur: f32) void;
pub extern fn fonsSetAlign(s: ?*Context, alignment: Align) void;
pub extern fn fonsSetFont(s: ?*Context, font: c_int) void;
pub extern fn fonsTextBounds(s: ?*Context, x: f32, y: f32, string: [*c]const u8, end: [*c]const u8, bounds: [*c]f32) f32;
pub extern fn fonsLineBounds(s: ?*Context, y: f32, miny: [*c]f32, maxy: [*c]f32) void;
pub extern fn fonsVertMetrics(s: ?*Context, ascender: [*c]f32, descender: [*c]f32, lineh: [*c]f32) void;
pub extern fn fonsTextIterInit(stash: ?*Context, iter: [*c]TextIter, x: f32, y: f32, str: [*c]const u8, len: c_int) c_int;
pub extern fn fonsTextIterNext(stash: ?*Context, iter: [*c]TextIter, quad: [*c]Quad) c_int;
pub extern fn fonsGetTextureData(stash: ?*Context, width: [*c]c_int, height: [*c]c_int) [*c]const u8;
pub extern fn fonsValidateTexture(s: ?*Context, dirty: [*c]c_int) c_int; | gamekit/deps/fontstash/fontstash.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/day03.txt");
pub fn main() !void {
var readings = try loadReadings(u12, data);
defer readings.deinit();
var sums = try sumallbits(u12, readings.items);
defer sums.deinit();
var power = part1(readings.items.len, sums.items);
print("gamma {}, epsilon {}, power {}\n", .{ power.gamma, power.epsilon, power.power });
try part2(readings.items);
}
const Power = struct { gamma: u32, epsilon: u32, power: u32 };
fn part1(total: usize, sums: []const u32) Power {
var power = Power{ .gamma = 0, .epsilon = 0, .power = 0 };
for (sums) |count, i| {
if (count >= total / 2) power.gamma |= @as(u32, 1) << @intCast(u5, i);
if (count <= total / 2) power.epsilon |= @as(u32, 1) << @intCast(u5, i);
}
power.power = power.gamma * power.epsilon;
return power;
}
fn part2(readings: []u12) !void {
var oxylist = ArrayList(u12).init(gpa);
try oxylist.appendSlice(readings);
defer oxylist.deinit();
var removeList = ArrayList(u16).init(gpa);
defer removeList.deinit();
var biterator: u5 = std.meta.bitCount(u12);
filter: while (biterator > 0) : (biterator -= 1) {
const bit = biterator - 1;
const sum = sumbit(u12, oxylist.items, bit);
const common: u1 = if (sum >= oxylist.items.len - sum) 1 else 0;
for (oxylist.items) |item, i| {
if ((isBitOne(item, bit) and common == 0) or (!isBitOne(item, bit) and common == 1)) try removeList.append(@intCast(u16, i));
}
// Since indexes were added in order, reverse so we go backwards
std.mem.reverse(u16, removeList.items);
for (removeList.items) |remove| {
_ = oxylist.orderedRemove(remove);
if (oxylist.items.len == 1) break :filter;
}
try removeList.resize(0);
}
const oxygen = oxylist.items[0];
var co2list = ArrayList(u12).init(gpa);
try co2list.appendSlice(readings);
defer co2list.deinit();
try removeList.resize(0);
biterator = std.meta.bitCount(u12);
filter: while (biterator > 0) : (biterator -= 1) {
const bit = biterator - 1;
const sum = sumbit(u12, co2list.items, bit);
const uncommon: u1 = if (sum >= co2list.items.len - sum) 0 else 1;
for (co2list.items) |item, i| {
if ((isBitOne(item, bit) and uncommon == 0) or (!isBitOne(item, bit) and uncommon == 1)) try removeList.append(@intCast(u16, i));
}
// Since indexes were added in order, reverse so we go backwards
std.mem.reverse(u16, removeList.items);
for (removeList.items) |remove| {
_ = co2list.orderedRemove(remove);
if (co2list.items.len == 1) break :filter;
}
try removeList.resize(0);
}
const co2 = co2list.items[0];
const lifesupport = @intCast(u32, oxygen) * @intCast(u32, co2);
print("oxygen {}, co2 {}, life support {}\n", .{ oxygen, co2, lifesupport });
}
fn isBitOne(num: u32, pos: u5) bool {
const bitmask = @as(u32, 1) << pos;
return num & bitmask != 0;
}
test "bit me" {
assert(isBitOne(0b1000_0000_0001, 0) == true);
assert(isBitOne(0b1000_0000_0001, 1) == false);
}
fn loadReadings(T: anytype, buf: []const u8) !ArrayList(T) {
var list = ArrayList(T).init(gpa);
var tokenIter = tokenize(u8, buf, " \r\n ");
while (tokenIter.next()) |token| {
try list.append(try parseInt(T, token, 2));
}
return list;
}
test "loadReadings" {
var readings = try loadReadings(u7, @embedFile("../data/day03-example.txt"));
defer readings.deinit();
assert(readings.items[0] == 0b00100);
}
fn sumbit(T: anytype, items: []const T, bit: u5) u32 {
var sum: u32 = 0;
for (items) |number| {
if (isBitOne(@intCast(u32, number), bit)) sum += 1;
}
return sum;
}
fn sumallbits(T: anytype, items: []const T) !ArrayList(u32) {
const bitCount = std.meta.bitCount(T);
var sums = try ArrayList(u32).initCapacity(gpa, bitCount);
try sums.resize(bitCount);
std.mem.set(u32, sums.items, 0);
for (items) |number| {
var i: u5 = 0;
while (i < bitCount) : (i += 1) {
if (isBitOne(@intCast(u32, number), i)) sums.items[i] += 1;
}
}
return sums;
}
test "sums" {
var readings = try loadReadings(u5, @embedFile("../data/day03-example.txt"));
defer readings.deinit();
var sums = try sumallbits(u5, readings.items);
defer sums.deinit();
assert(sums.items[0] == 5);
assert(sums.items[1] == 7);
assert(sums.items[2] == 8);
assert(sums.items[3] == 5);
assert(sums.items[4] == 7);
var sum = sumbit(u5, readings.items, 0);
assert(sum == 5);
}
test "part1" {
var readings = try loadReadings(u5, @embedFile("../data/day03-example.txt"));
defer readings.deinit();
var sums = try sumallbits(u5, readings.items);
defer sums.deinit();
var power = part1(readings.items.len, sums.items);
assert(power.gamma == 22);
assert(power.epsilon == 9);
assert(power.power == 198);
}
fn keepOnesAtPos(list: *ArrayList(u12), pos: u4) void {
var i = list.items.len;
while (i > 0) : (i -= 1) {
if (!isBitOne(list.items[i - 1], pos)) _ = list.swapRemove(i - 1);
if (list.items.len == 1) return;
}
}
fn keepZeroesAtPos(list: *ArrayList(u12), pos: u4) void {
var i = list.items.len;
while (i > 0) : (i -= 1) {
if (isBitOne(list.items[i - 1], pos)) _ = list.swapRemove(i - 1);
if (list.items.len == 1) return;
}
}
test "oxygen" {
var readings = try loadReadings(u5, @embedFile("../data/day03-example.txt"));
defer readings.deinit();
var removeList = ArrayList(u5).init(gpa);
defer removeList.deinit();
var bitpath = ArrayList(u1).init(gpa);
defer bitpath.deinit();
var biterator: u5 = std.meta.bitCount(u5);
filter: while (biterator > 0) : (biterator -= 1) {
const bit = biterator - 1;
const sum = sumbit(u5, readings.items, bit);
// print("sum0 {} sum1 {}\n", .{ readings.items.len - sum, sum });
const common: u1 = if (sum >= readings.items.len - sum) 1 else 0;
try bitpath.append(common);
for (readings.items) |item, i| {
if ((isBitOne(item, bit) and common == 0) or (!isBitOne(item, bit) and common == 1)) try removeList.append(@intCast(u5, i));
}
// Since indexes were added in order, reverse so we go backwards
std.mem.reverse(u5, removeList.items);
for (removeList.items) |remove| {
_ = readings.orderedRemove(remove);
if (readings.items.len == 1) break :filter;
}
try removeList.resize(0);
}
print("path {any}, {any}, 0b{b}", .{ bitpath.items, readings.items, readings.items[0] });
assert(readings.items.len == 1 and readings.items[0] == 23);
}
test "co2" {
var readings = try loadReadings(u5, @embedFile("../data/day03-example.txt"));
defer readings.deinit();
var removeList = ArrayList(u5).init(gpa);
defer removeList.deinit();
var bitpath = ArrayList(u1).init(gpa);
defer bitpath.deinit();
var biterator: u5 = std.meta.bitCount(u5);
filter: while (biterator > 0) : (biterator -= 1) {
const bit = biterator - 1;
const sum = sumbit(u5, readings.items, bit);
// print("sum0 {} sum1 {}\n", .{ readings.items.len - sum, sum });
const uncommon: u1 = if (sum >= readings.items.len - sum) 0 else 1;
try bitpath.append(uncommon);
for (readings.items) |item, i| {
if ((isBitOne(item, bit) and uncommon == 0) or (!isBitOne(item, bit) and uncommon == 1)) try removeList.append(@intCast(u5, i));
}
// Since indexes were added in order, reverse so we go backwards
std.mem.reverse(u5, removeList.items);
for (removeList.items) |remove| {
_ = readings.orderedRemove(remove);
if (readings.items.len == 1) break :filter;
}
try removeList.resize(0);
}
print("path {any}, {any}, 0b{b}", .{ bitpath.items, readings.items, readings.items[0] });
assert(readings.items.len == 1 and readings.items[0] == 10);
}
// 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/day03.zig |
const std = @import("std");
const math = std.math;
const expect = std.testing.expect;
pub fn __fmah(x: f16, y: f16, z: f16) callconv(.C) f16 {
// TODO: more efficient implementation
return @floatCast(f16, fmaf(x, y, z));
}
pub fn fmaf(x: f32, y: f32, z: f32) callconv(.C) f32 {
const xy = @as(f64, x) * y;
const xy_z = xy + z;
const u = @bitCast(u64, xy_z);
const e = (u >> 52) & 0x7FF;
if ((u & 0x1FFFFFFF) != 0x10000000 or e == 0x7FF or (xy_z - xy == z and xy_z - z == xy)) {
return @floatCast(f32, xy_z);
} else {
// TODO: Handle inexact case with double-rounding
return @floatCast(f32, xy_z);
}
}
/// NOTE: Upstream fma.c has been rewritten completely to raise fp exceptions more accurately.
pub fn fma(x: f64, y: f64, z: f64) callconv(.C) f64 {
if (!math.isFinite(x) or !math.isFinite(y)) {
return x * y + z;
}
if (!math.isFinite(z)) {
return z;
}
if (x == 0.0 or y == 0.0) {
return x * y + z;
}
if (z == 0.0) {
return x * y;
}
const x1 = math.frexp(x);
var ex = x1.exponent;
var xs = x1.significand;
const x2 = math.frexp(y);
var ey = x2.exponent;
var ys = x2.significand;
const x3 = math.frexp(z);
var ez = x3.exponent;
var zs = x3.significand;
var spread = ex + ey - ez;
if (spread <= 53 * 2) {
zs = math.scalbn(zs, -spread);
} else {
zs = math.copysign(math.floatMin(f64), zs);
}
const xy = dd_mul(xs, ys);
const r = dd_add(xy.hi, zs);
spread = ex + ey;
if (r.hi == 0.0) {
return xy.hi + zs + math.scalbn(xy.lo, spread);
}
const adj = add_adjusted(r.lo, xy.lo);
if (spread + math.ilogb(r.hi) > -1023) {
return math.scalbn(r.hi + adj, spread);
} else {
return add_and_denorm(r.hi, adj, spread);
}
}
pub fn __fmax(a: f80, b: f80, c: f80) callconv(.C) f80 {
// TODO: more efficient implementation
return @floatCast(f80, fmaq(a, b, c));
}
/// Fused multiply-add: Compute x * y + z with a single rounding error.
///
/// We use scaling to avoid overflow/underflow, along with the
/// canonical precision-doubling technique adapted from:
///
/// <NAME>. A Floating-Point Technique for Extending the
/// Available Precision. Numer. Math. 18, 224-242 (1971).
pub fn fmaq(x: f128, y: f128, z: f128) callconv(.C) f128 {
if (!math.isFinite(x) or !math.isFinite(y)) {
return x * y + z;
}
if (!math.isFinite(z)) {
return z;
}
if (x == 0.0 or y == 0.0) {
return x * y + z;
}
if (z == 0.0) {
return x * y;
}
const x1 = math.frexp(x);
var ex = x1.exponent;
var xs = x1.significand;
const x2 = math.frexp(y);
var ey = x2.exponent;
var ys = x2.significand;
const x3 = math.frexp(z);
var ez = x3.exponent;
var zs = x3.significand;
var spread = ex + ey - ez;
if (spread <= 113 * 2) {
zs = math.scalbn(zs, -spread);
} else {
zs = math.copysign(math.floatMin(f128), zs);
}
const xy = dd_mul128(xs, ys);
const r = dd_add128(xy.hi, zs);
spread = ex + ey;
if (r.hi == 0.0) {
return xy.hi + zs + math.scalbn(xy.lo, spread);
}
const adj = add_adjusted128(r.lo, xy.lo);
if (spread + math.ilogb(r.hi) > -16383) {
return math.scalbn(r.hi + adj, spread);
} else {
return add_and_denorm128(r.hi, adj, spread);
}
}
pub fn fmal(x: c_longdouble, y: c_longdouble, z: c_longdouble) callconv(.C) c_longdouble {
switch (@typeInfo(c_longdouble).Float.bits) {
16 => return __fmah(x, y, z),
32 => return fmaf(x, y, z),
64 => return fma(x, y, z),
80 => return __fmax(x, y, z),
128 => return fmaq(x, y, z),
else => @compileError("unreachable"),
}
}
const dd = struct {
hi: f64,
lo: f64,
};
fn dd_add(a: f64, b: f64) dd {
var ret: dd = undefined;
ret.hi = a + b;
const s = ret.hi - a;
ret.lo = (a - (ret.hi - s)) + (b - s);
return ret;
}
fn dd_mul(a: f64, b: f64) dd {
var ret: dd = undefined;
const split: f64 = 0x1.0p27 + 1.0;
var p = a * split;
var ha = a - p;
ha += p;
var la = a - ha;
p = b * split;
var hb = b - p;
hb += p;
var lb = b - hb;
p = ha * hb;
var q = ha * lb + la * hb;
ret.hi = p + q;
ret.lo = p - ret.hi + q + la * lb;
return ret;
}
fn add_adjusted(a: f64, b: f64) f64 {
var sum = dd_add(a, b);
if (sum.lo != 0) {
var uhii = @bitCast(u64, sum.hi);
if (uhii & 1 == 0) {
// hibits += copysign(1.0, sum.hi, sum.lo)
const uloi = @bitCast(u64, sum.lo);
uhii += 1 - ((uhii ^ uloi) >> 62);
sum.hi = @bitCast(f64, uhii);
}
}
return sum.hi;
}
fn add_and_denorm(a: f64, b: f64, scale: i32) f64 {
var sum = dd_add(a, b);
if (sum.lo != 0) {
var uhii = @bitCast(u64, sum.hi);
const bits_lost = -@intCast(i32, (uhii >> 52) & 0x7FF) - scale + 1;
if ((bits_lost != 1) == (uhii & 1 != 0)) {
const uloi = @bitCast(u64, sum.lo);
uhii += 1 - (((uhii ^ uloi) >> 62) & 2);
sum.hi = @bitCast(f64, uhii);
}
}
return math.scalbn(sum.hi, scale);
}
/// A struct that represents a floating-point number with twice the precision
/// of f128. We maintain the invariant that "hi" stores the high-order
/// bits of the result.
const dd128 = struct {
hi: f128,
lo: f128,
};
/// Compute a+b exactly, returning the exact result in a struct dd. We assume
/// that both a and b are finite, but make no assumptions about their relative
/// magnitudes.
fn dd_add128(a: f128, b: f128) dd128 {
var ret: dd128 = undefined;
ret.hi = a + b;
const s = ret.hi - a;
ret.lo = (a - (ret.hi - s)) + (b - s);
return ret;
}
/// Compute a+b, with a small tweak: The least significant bit of the
/// result is adjusted into a sticky bit summarizing all the bits that
/// were lost to rounding. This adjustment negates the effects of double
/// rounding when the result is added to another number with a higher
/// exponent. For an explanation of round and sticky bits, see any reference
/// on FPU design, e.g.,
///
/// <NAME>. An Implementation Guide to a Proposed Standard for
/// Floating-Point Arithmetic. Computer, vol. 13, no. 1, Jan 1980.
fn add_adjusted128(a: f128, b: f128) f128 {
var sum = dd_add128(a, b);
if (sum.lo != 0) {
var uhii = @bitCast(u128, sum.hi);
if (uhii & 1 == 0) {
// hibits += copysign(1.0, sum.hi, sum.lo)
const uloi = @bitCast(u128, sum.lo);
uhii += 1 - ((uhii ^ uloi) >> 126);
sum.hi = @bitCast(f128, uhii);
}
}
return sum.hi;
}
/// Compute ldexp(a+b, scale) with a single rounding error. It is assumed
/// that the result will be subnormal, and care is taken to ensure that
/// double rounding does not occur.
fn add_and_denorm128(a: f128, b: f128, scale: i32) f128 {
var sum = dd_add128(a, b);
// If we are losing at least two bits of accuracy to denormalization,
// then the first lost bit becomes a round bit, and we adjust the
// lowest bit of sum.hi to make it a sticky bit summarizing all the
// bits in sum.lo. With the sticky bit adjusted, the hardware will
// break any ties in the correct direction.
//
// If we are losing only one bit to denormalization, however, we must
// break the ties manually.
if (sum.lo != 0) {
var uhii = @bitCast(u128, sum.hi);
const bits_lost = -@intCast(i32, (uhii >> 112) & 0x7FFF) - scale + 1;
if ((bits_lost != 1) == (uhii & 1 != 0)) {
const uloi = @bitCast(u128, sum.lo);
uhii += 1 - (((uhii ^ uloi) >> 126) & 2);
sum.hi = @bitCast(f128, uhii);
}
}
return math.scalbn(sum.hi, scale);
}
/// Compute a*b exactly, returning the exact result in a struct dd. We assume
/// that both a and b are normalized, so no underflow or overflow will occur.
/// The current rounding mode must be round-to-nearest.
fn dd_mul128(a: f128, b: f128) dd128 {
var ret: dd128 = undefined;
const split: f128 = 0x1.0p57 + 1.0;
var p = a * split;
var ha = a - p;
ha += p;
var la = a - ha;
p = b * split;
var hb = b - p;
hb += p;
var lb = b - hb;
p = ha * hb;
var q = ha * lb + la * hb;
ret.hi = p + q;
ret.lo = p - ret.hi + q + la * lb;
return ret;
}
test "32" {
const epsilon = 0.000001;
try expect(math.approxEqAbs(f32, fmaf(0.0, 5.0, 9.124), 9.124, epsilon));
try expect(math.approxEqAbs(f32, fmaf(0.2, 5.0, 9.124), 10.124, epsilon));
try expect(math.approxEqAbs(f32, fmaf(0.8923, 5.0, 9.124), 13.5855, epsilon));
try expect(math.approxEqAbs(f32, fmaf(1.5, 5.0, 9.124), 16.624, epsilon));
try expect(math.approxEqAbs(f32, fmaf(37.45, 5.0, 9.124), 196.374004, epsilon));
try expect(math.approxEqAbs(f32, fmaf(89.123, 5.0, 9.124), 454.739005, epsilon));
try expect(math.approxEqAbs(f32, fmaf(123123.234375, 5.0, 9.124), 615625.295875, epsilon));
}
test "64" {
const epsilon = 0.000001;
try expect(math.approxEqAbs(f64, fma(0.0, 5.0, 9.124), 9.124, epsilon));
try expect(math.approxEqAbs(f64, fma(0.2, 5.0, 9.124), 10.124, epsilon));
try expect(math.approxEqAbs(f64, fma(0.8923, 5.0, 9.124), 13.5855, epsilon));
try expect(math.approxEqAbs(f64, fma(1.5, 5.0, 9.124), 16.624, epsilon));
try expect(math.approxEqAbs(f64, fma(37.45, 5.0, 9.124), 196.374, epsilon));
try expect(math.approxEqAbs(f64, fma(89.123, 5.0, 9.124), 454.739, epsilon));
try expect(math.approxEqAbs(f64, fma(123123.234375, 5.0, 9.124), 615625.295875, epsilon));
}
test "128" {
const epsilon = 0.000001;
try expect(math.approxEqAbs(f128, fmaq(0.0, 5.0, 9.124), 9.124, epsilon));
try expect(math.approxEqAbs(f128, fmaq(0.2, 5.0, 9.124), 10.124, epsilon));
try expect(math.approxEqAbs(f128, fmaq(0.8923, 5.0, 9.124), 13.5855, epsilon));
try expect(math.approxEqAbs(f128, fmaq(1.5, 5.0, 9.124), 16.624, epsilon));
try expect(math.approxEqAbs(f128, fmaq(37.45, 5.0, 9.124), 196.374, epsilon));
try expect(math.approxEqAbs(f128, fmaq(89.123, 5.0, 9.124), 454.739, epsilon));
try expect(math.approxEqAbs(f128, fmaq(123123.234375, 5.0, 9.124), 615625.295875, epsilon));
} | lib/compiler_rt/fma.zig |
const builtin = @import("builtin");
const TypeId = builtin.TypeId;
const std = @import("index.zig");
/// This function is intended to be used only in tests. It prints diagnostics to stderr
/// and then aborts when actual_error_union is not expected_error.
pub fn expectError(expected_error: anyerror, actual_error_union: var) void {
// TODO remove the workaround here for https://github.com/ziglang/zig/issues/1936
if (actual_error_union) |actual_payload| {
// TODO remove workaround here for https://github.com/ziglang/zig/issues/557
if (@sizeOf(@typeOf(actual_payload)) == 0) {
std.debug.panic("expected error.{}, found {} value", @errorName(expected_error), @typeName(@typeOf(actual_payload)));
} else {
std.debug.panic("expected error.{}, found {}", @errorName(expected_error), actual_payload);
}
} else |actual_error| {
if (expected_error != actual_error) {
std.debug.panic("expected error.{}, found error.{}", @errorName(expected_error), @errorName(actual_error));
}
}
}
/// This function is intended to be used only in tests. When the two values are not
/// equal, prints diagnostics to stderr to show exactly how they are not equal,
/// then aborts.
/// The types must match exactly.
pub fn expectEqual(expected: var, actual: @typeOf(expected)) void {
switch (@typeInfo(@typeOf(actual))) {
TypeId.NoReturn,
TypeId.BoundFn,
TypeId.ArgTuple,
TypeId.Opaque,
=> @compileError("value of type " ++ @typeName(@typeOf(actual)) ++ " encountered"),
TypeId.Undefined,
TypeId.Null,
TypeId.Void,
=> return,
TypeId.Type,
TypeId.Bool,
TypeId.Int,
TypeId.Float,
TypeId.ComptimeFloat,
TypeId.ComptimeInt,
TypeId.Enum,
TypeId.Namespace,
TypeId.Fn,
TypeId.Promise,
TypeId.Vector,
TypeId.ErrorSet,
=> {
if (actual != expected) {
std.debug.panic("expected {}, found {}", expected, actual);
}
},
TypeId.Pointer => |pointer| {
switch (pointer.size) {
builtin.TypeInfo.Pointer.Size.One,
builtin.TypeInfo.Pointer.Size.Many,
=> {
if (actual != expected) {
std.debug.panic("expected {}, found {}", expected, actual);
}
},
builtin.TypeInfo.Pointer.Size.Slice => {
if (actual.ptr != expected.ptr) {
std.debug.panic("expected slice ptr {}, found {}", expected.ptr, actual.ptr);
}
if (actual.len != expected.len) {
std.debug.panic("expected slice len {}, found {}", expected.len, actual.len);
}
},
}
},
TypeId.Array => |array| expectEqualSlices(array.child, &expected, &actual),
TypeId.Struct => {
@compileError("TODO implement testing.expectEqual for structs");
},
TypeId.Union => |union_info| {
if (union_info.tag_type == null) {
@compileError("Unable to compare untagged union values");
}
@compileError("TODO implement testing.expectEqual for tagged unions");
},
TypeId.Optional => {
if (expected) |expected_payload| {
if (actual) |actual_payload| {
expectEqual(expected_payload, actual_payload);
} else {
std.debug.panic("expected {}, found null", expected_payload);
}
} else {
if (actual) |actual_payload| {
std.debug.panic("expected null, found {}", actual_payload);
}
}
},
TypeId.ErrorUnion => {
if (expected) |expected_payload| {
if (actual) |actual_payload| {
expectEqual(expected_payload, actual_payload);
} else |actual_err| {
std.debug.panic("expected {}, found {}", expected_payload, actual_err);
}
} else |expected_err| {
if (actual) |actual_payload| {
std.debug.panic("expected {}, found {}", expected_err, actual_payload);
} else |actual_err| {
expectEqual(expected_err, actual_err);
}
}
},
}
}
/// This function is intended to be used only in tests. When the two slices are not
/// equal, prints diagnostics to stderr to show exactly how they are not equal,
/// then aborts.
pub fn expectEqualSlices(comptime T: type, expected: []const T, actual: []const T) void {
// TODO better printing of the difference
// If the arrays are small enough we could print the whole thing
// If the child type is u8 and no weird bytes, we could print it as strings
// Even for the length difference, it would be useful to see the values of the slices probably.
if (expected.len != actual.len) {
std.debug.panic("slice lengths differ. expected {}, found {}", expected.len, actual.len);
}
var i: usize = 0;
while (i < expected.len) : (i += 1) {
if (expected[i] != actual[i]) {
std.debug.panic("index {} incorrect. expected {}, found {}", i, expected[i], actual[i]);
}
}
}
/// This function is intended to be used only in tests. When `ok` is false, the test fails.
/// A message is printed to stderr and then abort is called.
pub fn expect(ok: bool) void {
if (!ok) @panic("test failure");
} | std/testing.zig |
const os = @import("root").os;
const std = @import("std");
const regs = @import("regs.zig");
const paging = @import("../paging.zig");
pub const page_sizes = [_]u64 {
0x1000, // 4K page
0x10000,
0x200000, // 2M page
0x2000000,
0x40000000, // 1G page
0x8000000000, // 512G page
};
const LevelType = u3;
const PatIndex = u3;
const la64: u64 = 1 << 12;
const cr3 = regs.ControlRegister(u64, "cr3");
const cr4 = regs.ControlRegister(u64, "cr4");
fn PATContext() type {
const PATEncoding = u8;
const PATValue = u64;
const ia32_pat = regs.MSR(PATValue, 0x00000277);
const uncacheable_encoding = 0x00;
const write_combining_encoding = 0x01;
const writethrough_encoding = 0x04;
const write_back_encoding = 0x06;
return struct {
// The value of IA32_PAT itself
value: PATValue,
// Cache the indices for each memory type
uncacheable: ?PatIndex,
write_combining: ?PatIndex,
writethrough: ?PatIndex,
write_back: ?PatIndex,
pub fn init_from_pat_value(value: PATValue) @This() {
return .{
.value = value,
.uncacheable = find_pat_index(value, uncacheable_encoding),
.write_combining = find_pat_index(value, write_combining_encoding),
.writethrough = find_pat_index(value, writethrough_encoding),
.write_back = find_pat_index(value, write_back_encoding),
};
}
fn encoding_at_index(value: PATValue, idx: PatIndex) PATEncoding {
return @truncate(u8, value >> (@as(u6, idx) * 8));
}
fn memory_type_at_index(self: *const @This(), idx: PatIndex) ?MemoryType {
return switch(encoding_at_index(self.value, idx)) {
uncacheable_encoding => .DeviceUncacheable,
write_combining_encoding => .DeviceWriteCombining,
writethrough_encoding => .MemoryWritethrough,
write_back_encoding => .MemoryWriteBack,
else => null,
};
}
fn find_pat_index(pat: PATValue, enc: PATEncoding) ?PatIndex {
var idx: PatIndex = 0;
while(true): (idx += 1) {
if(encoding_at_index(pat, idx) == enc)
return idx;
if(idx == 7)
return null;
}
}
pub fn find_memtype(self: *const @This(), memtype: MemoryType) ?PatIndex {
var idx: PatIndex = 0;
while(true): (idx += 1) {
if(self.memory_type_at_index(idx) == memtype)
return idx;
if(idx == 7)
return null;
}
}
pub fn apply(self: *const @This()) void {
ia32_pat.write(self.value);
}
pub fn get_active() ?@This() {
const id = regs.cpuid(0x00000001);
if(id) |i| {
if(((i.edx >> 16) & 1) != 0)
return init_from_pat_value(ia32_pat.read());
}
return null;
}
pub fn make_default() ?@This() {
const default = comptime init_from_pat_value(0
// We set writeback as index 0 for our page tables
| write_back_encoding << 0
// The order of the rest shouldn't matter
| write_combining_encoding << 8
| writethrough_encoding << 16
| uncacheable_encoding << 24
);
return default;
}
};
}
fn level_size(level: LevelType) u64 {
return @as(u64, 0x1000) << (@as(u6, level) * 9);
}
pub fn make_page_table() !u64 {
const pt = try os.memory.pmm.alloc_phys(0x1000);
const pt_bytes = os.platform.phys_slice(u8).init(pt, 0x1000);
@memset(pt_bytes.to_slice_writeback().ptr, 0x00, 0x1000);
return pt;
}
pub fn is_5levelpaging() bool {
return cr4.read() & la64 != 0;
}
pub const PagingContext = struct {
pat: ?PATContext(),
cr3_val: u64,
level5paging: bool,
gigapage_allowed: bool,
wb_virt_base: u64 = undefined,
wc_virt_base: u64 = undefined,
uc_virt_base: u64 = undefined,
max_phys: u64 = undefined,
pub fn apply(self: *@This()) void {
// First apply the PAT, shouldn't cause any errors
if(self.pat) |pat|
@call(.{.modifier = .always_inline}, PATContext().apply, .{&pat});
regs.IA32_EFER.write(regs.IA32_EFER.read() | (1 << 11)); // NXE
// Set 5 level paging bit
const old_cr4 = cr4.read();
cr4.write(
if(self.level5paging)
old_cr4 | la64
else
old_cr4 & ~la64
);
@call(.{.modifier = .always_inline}, cr3.write, .{self.cr3_val});
}
pub fn read_current() void {
const id = regs.cpuid(0x80000001);
const curr = &os.memory.paging.kernel_context;
curr.pat = PATContext().get_active();
curr.cr3_val = cr3.read();
// Test if 5 level paging currently is enabled
curr.level5paging = is_5levelpaging();
// Check CPUID to determine if enabled or not
curr.gigapage_allowed = false;// if(id) |i| ((i.edx >> 26) & 1) == 1 else false;
}
pub fn make_default() !@This() {
const curr = &os.memory.paging.kernel_context;
const pt = try make_page_table();
// 32TB ought to be enough for anyone...
const max_phys = 0x200000000000;
const curr_base = os.memory.paging.kernel_context.wb_virt_base;
return @This(){
.pat = PATContext().make_default(),
.cr3_val = pt,
.level5paging = curr.level5paging,
.gigapage_allowed = false,//curr.gigapage_allowed,
.wb_virt_base = curr_base,
.wc_virt_base = curr_base + max_phys,
.uc_virt_base = curr_base + max_phys * 2,
.max_phys = max_phys,
};
}
pub fn can_map_at_level(self: *const @This(), level: LevelType) bool {
return level < @as(LevelType, 2) + @boolToInt(self.gigapage_allowed);
}
pub fn check_phys(self: *const @This(), phys: u64) void {
if(comptime(std.debug.runtime_safety)) {
if(phys > self.max_phys) @panic("Physical address out of range");
}
}
pub fn phys_to_write_back_virt(self: *const @This(), phys: u64) u64 {
self.check_phys(phys);
return self.wb_virt_base + phys;
}
pub fn phys_to_write_combining_virt(self: *const @This(), phys: u64) u64 {
self.check_phys(phys);
return self.wc_virt_base + phys;
}
pub fn phys_to_uncached_virt(self: *const @This(), phys: u64) u64 {
self.check_phys(phys);
return self.uc_virt_base + phys;
}
pub fn make_heap_base(self: *const @This()) u64 {
// Just after last physical memory mapping
return self.uc_virt_base + self.max_phys;
}
pub fn root_table(self: *@This(), virt: u64) TablePTE {
return .{
.phys = self.cr3_val,
.curr_level = if(self.level5paging) 5 else 4,
.context = self,
.perms = os.memory.paging.rwx(),
.underlying = null,
};
}
pub fn decode(self: *@This(), enc: *EncodedPTE, level: LevelType) PTE {
var pte = PTEEncoding{.raw = enc.*};
if(!pte.present.read())
return .Empty;
if(!pte.is_mapping.read() and level != 0)
return .{.Table = self.decode_table(enc, level)};
return .{.Mapping = self.decode_mapping(enc, level)};
}
fn decode_memtype(self: *@This(), map: MappingEncoding, level: LevelType) ?MemoryType {
// TODO: MTRR awareness (?)
// right now we assume all MTRRs are WB
if(self.pat) |pat| {
// Formula for PAT index is 4*PAT + 2*CD + 1*WT
var pat_idx: PatIndex = 0;
const pat_bit = if(level == 0) map.is_mapping_or_pat_low.read() else map.pat_high.read();
if(pat_bit)
pat_idx += 4;
if(map.cache_disable.read())
pat_idx += 2;
if(map.writethrough.read())
pat_idx += 1;
return pat.memory_type_at_index(pat_idx);
} else {
switch(map.cache_disable.read()) {
true => return MemoryType.DeviceUncacheable,
false =>
switch(map.writethrough.read()) {
true => return MemoryType.MemoryWritethrough,
false => return MemoryType.MemoryWriteBack,
},
}
}
}
pub fn decode_mapping(self: *@This(), enc: *EncodedPTE, level: LevelType) MappingPTE {
const map = MappingEncoding{.raw = enc.*};
const memtype: MemoryType = self.decode_memtype(map, level) orelse @panic("Unknown memory type");
return .{
.context = self,
.phys = if(level == 0) enc.* & phys_bitmask else enc.* & phys_bitmask_high,
.level = level,
.memtype = memtype,
.underlying = @ptrCast(*MappingEncoding, enc),
.perms = .{
.writable = map.writable.read(),
.executable = !map.execute_disable.read(),
.userspace = map.user.read(),
},
};
}
pub fn decode_table(self: *@This(), enc: *EncodedPTE, level: LevelType) TablePTE {
const tbl = TableEncoding{.raw = enc.*};
return .{
.context = self,
.phys = enc.* & phys_bitmask,
.curr_level = level,
.underlying = @ptrCast(*TableEncoding, enc),
.perms = .{
.writable = tbl.writable.read(),
.executable = !tbl.execute_disable.read(),
.userspace = tbl.user.read(),
},
};
}
pub fn encode_empty(self: *const @This(), level: LevelType) EncodedPTE {
return 0;
}
pub fn encode_table(self: *const @This(), pte: TablePTE) !EncodedPTE {
var tbl = TableEncoding{.raw = pte.phys};
tbl.writable.write(pte.perms.writable);
tbl.user.write(pte.perms.userspace);
tbl.execute_disable.write(!pte.perms.executable);
tbl.present.write(true);
tbl.is_mapping.write(false);
return tbl.raw;
}
fn encode_memory_type(self: *const @This(), enc: *MappingEncoding, pte: MappingPTE) void {
// TODO: MTRR awareness (?)
// right now we assume all MTRRs are WB
const mt = pte.memtype orelse @panic("Unknown memory type");
if(self.pat) |pat| {
// Formula for PAT index is 4*PAT + 2*CD + 1*WT
const idx = pat.find_memtype(mt) orelse @panic("Could not find PAT index");
if(idx & 4 != 0) {
if(pte.level == 0) {
enc.is_mapping_or_pat_low.write(true);
}
else {
enc.pat_high.write(true);
}
}
if(idx & 2 != 0)
enc.cache_disable.write(true);
if(idx & 1 != 0)
enc.writethrough.write(true);
} else {
switch(mt) {
.MemoryWritethrough => enc.writethrough.write(true),
.DeviceUncacheable => enc.cache_disable.write(true),
.MemoryWriteBack => { },
else => @panic("Cannot set memory type"),
}
}
}
pub fn encode_mapping(self: *const @This(), pte: MappingPTE) !EncodedPTE {
var map = MappingEncoding{.raw = pte.phys};
// writethrough: bf.boolean(u64, 3),
// cache_disable: bf.boolean(u64, 4),
// is_mapping_or_pat_low: bf.boolean(u64, 7),
// pat_high: bf.boolean(u64, 12),
map.present.write(true);
if(pte.level != 0)
map.is_mapping_or_pat_low.write(true);
map.writable.write(pte.perms.writable);
map.user.write(pte.perms.userspace);
map.execute_disable.write(!pte.perms.executable);
self.encode_memory_type(&map, pte);
return map.raw;
}
pub fn domain(self: *const @This(), level: LevelType, virtaddr: u64) os.platform.virt_slice {
return .{
.ptr = virtaddr & ~(self.page_size(level, virtaddr) - 1),
.len = self.page_size(level, virtaddr),
};
}
pub fn invalidate(self: *const @This(), virt: u64) void {
asm volatile(
\\invlpg (%[virt])
:
: [virt] "r" (virt)
: "memory"
);
}
pub fn page_size(_: *const @This(), level: LevelType, virtaddr: u64) u64 {
return level_size(level);
}
};
pub const MemoryType = extern enum {
// x86 doesn't differentiate between device and normal memory (?)
DeviceUncacheable = 0,
MemoryUncacheable = 0,
DeviceWriteCombining = 1,
MemoryWritethrough = 2,
MemoryWriteBack = 3,
};
const phys_bitmask = 0x7ffffffffffff000;
const phys_bitmask_high = 0x7fffffffffffe000;
const bf = os.lib.bitfields;
const PTEEncoding = extern union {
raw: u64,
present: bf.boolean(u64, 0),
is_mapping: bf.boolean(u64, 7),
};
const MappingEncoding = extern union {
raw: u64,
present: bf.boolean(u64, 0),
writable: bf.boolean(u64, 1),
user: bf.boolean(u64, 2),
writethrough: bf.boolean(u64, 3),
cache_disable: bf.boolean(u64, 4),
accessed: bf.boolean(u64, 5),
is_mapping_or_pat_low: bf.boolean(u64, 7),
pat_high: bf.boolean(u64, 12),
execute_disable: bf.boolean(u64, 63),
};
const TableEncoding = extern union {
raw: u64,
present: bf.boolean(u64, 0),
writable: bf.boolean(u64, 1),
user: bf.boolean(u64, 2),
accessed: bf.boolean(u64, 5),
is_mapping: bf.boolean(u64, 7),
execute_disable: bf.boolean(u64, 63),
};
fn virt_index_at_level(vaddr: u64, level: u6) u9 {
const shamt = 12 + level * 9;
return @truncate(u9, (vaddr >> shamt));
}
const MappingPTE = struct {
phys: u64,
level: u3,
memtype: ?MemoryType,
context: *PagingContext,
perms: os.memory.paging.Perms,
underlying: *MappingEncoding,
pub fn mapped_bytes(self: *const @This()) os.platform.PhysBytes {
return .{
.ptr = self.phys,
.len = self.context.page_size(self.level, self.context.phys_to_write_back_virt(self.phys)),
};
}
pub fn get_type(self: *const @This()) ?MemoryType {
return self.memtype;
}
};
const EncodedPTE = u64;
const TablePTE = struct {
phys: u64,
curr_level: LevelType,
context: *PagingContext,
perms: os.memory.paging.Perms,
underlying: ?*TableEncoding,
pub fn get_child_tables(self: *const @This()) []EncodedPTE {
return os.platform.phys_slice(EncodedPTE).init(self.phys, 512).to_slice_writeback();
}
pub fn skip_to(self: *const @This(), virt: u64) []EncodedPTE {
return self.get_child_tables()[virt_index_at_level(virt, self.curr_level - 1)..];
}
pub fn child_domain(self: *const @This(), virt: u64) os.platform.virt_slice {
return self.context.domain(self.curr_level - 1, virt);
}
pub fn decode_child(self: *const @This(), pte: *EncodedPTE) PTE {
return self.context.decode(pte, self.curr_level - 1);
}
pub fn level(self: *const @This()) LevelType {
return self.curr_level;
}
pub fn add_perms(self: *const @This(), perms: os.memory.paging.Perms) void {
if(perms.executable)
self.underlying.?.execute_disable.write(false);
if(perms.writable)
self.underlying.?.writable.write(true);
if(perms.userspace)
self.underlying.?.user.write(true);
}
pub fn make_child_table(self: *const @This(), enc: *u64, perms: os.memory.paging.Perms) !TablePTE {
const pmem = try make_page_table();
errdefer os.memory.pmm.free_phys(pmem, 0x1000);
var result: TablePTE = .{
.phys = pmem,
.context = self.context,
.curr_level = self.curr_level - 1,
.perms = perms,
.underlying = @ptrCast(*TableEncoding, enc),
};
enc.* = try self.context.encode_table(result);
return result;
}
pub fn make_child_mapping(
self: *const @This(),
enc: *u64,
phys: ?u64,
perms: os.memory.paging.Perms,
memtype: MemoryType,
) !MappingPTE {
const page_size = self.context.page_size(self.level() - 1, undefined);
const pmem = phys orelse try os.memory.pmm.alloc_phys(page_size);
errdefer if(phys == null) os.memory.pmm.free_phys(pmem, page_size);
var result: MappingPTE = .{
.level = self.level() - 1,
.memtype = memtype,
.context = self.context,
.perms = perms,
.underlying = @ptrCast(*MappingEncoding, enc),
.phys = pmem,
};
enc.* = try self.context.encode_mapping(result);
return result;
}
};
const EmptyPte = struct { };
pub const PTE = union(paging.PTEType) {
Mapping: MappingPTE,
Table: TablePTE,
Empty: EmptyPte,
}; | src/platform/x86_64/paging.zig |
const __mulodi4 = @import("mulodi4.zig").__mulodi4;
const testing = @import("std").testing;
fn test__mulodi4(a: i64, b: i64, expected: i64, expected_overflow: c_int) void {
var overflow: c_int = undefined;
const x = __mulodi4(a, b, &overflow);
testing.expect(overflow == expected_overflow and (expected_overflow != 0 or x == expected));
}
test "mulodi4" {
test__mulodi4(0, 0, 0, 0);
test__mulodi4(0, 1, 0, 0);
test__mulodi4(1, 0, 0, 0);
test__mulodi4(0, 10, 0, 0);
test__mulodi4(10, 0, 0, 0);
test__mulodi4(0, 81985529216486895, 0, 0);
test__mulodi4(81985529216486895, 0, 0, 0);
test__mulodi4(0, -1, 0, 0);
test__mulodi4(-1, 0, 0, 0);
test__mulodi4(0, -10, 0, 0);
test__mulodi4(-10, 0, 0, 0);
test__mulodi4(0, -81985529216486895, 0, 0);
test__mulodi4(-81985529216486895, 0, 0, 0);
test__mulodi4(1, 1, 1, 0);
test__mulodi4(1, 10, 10, 0);
test__mulodi4(10, 1, 10, 0);
test__mulodi4(1, 81985529216486895, 81985529216486895, 0);
test__mulodi4(81985529216486895, 1, 81985529216486895, 0);
test__mulodi4(1, -1, -1, 0);
test__mulodi4(1, -10, -10, 0);
test__mulodi4(-10, 1, -10, 0);
test__mulodi4(1, -81985529216486895, -81985529216486895, 0);
test__mulodi4(-81985529216486895, 1, -81985529216486895, 0);
test__mulodi4(3037000499, 3037000499, 9223372030926249001, 0);
test__mulodi4(-3037000499, 3037000499, -9223372030926249001, 0);
test__mulodi4(3037000499, -3037000499, -9223372030926249001, 0);
test__mulodi4(-3037000499, -3037000499, 9223372030926249001, 0);
test__mulodi4(4398046511103, 2097152, 9223372036852678656, 0);
test__mulodi4(-4398046511103, 2097152, -9223372036852678656, 0);
test__mulodi4(4398046511103, -2097152, -9223372036852678656, 0);
test__mulodi4(-4398046511103, -2097152, 9223372036852678656, 0);
test__mulodi4(2097152, 4398046511103, 9223372036852678656, 0);
test__mulodi4(-2097152, 4398046511103, -9223372036852678656, 0);
test__mulodi4(2097152, -4398046511103, -9223372036852678656, 0);
test__mulodi4(-2097152, -4398046511103, 9223372036852678656, 0);
test__mulodi4(0x7FFFFFFFFFFFFFFF, -2, 2, 1);
test__mulodi4(-2, 0x7FFFFFFFFFFFFFFF, 2, 1);
test__mulodi4(0x7FFFFFFFFFFFFFFF, -1, @bitCast(i64, @as(u64, 0x8000000000000001)), 0);
test__mulodi4(-1, 0x7FFFFFFFFFFFFFFF, @bitCast(i64, @as(u64, 0x8000000000000001)), 0);
test__mulodi4(0x7FFFFFFFFFFFFFFF, 0, 0, 0);
test__mulodi4(0, 0x7FFFFFFFFFFFFFFF, 0, 0);
test__mulodi4(0x7FFFFFFFFFFFFFFF, 1, 0x7FFFFFFFFFFFFFFF, 0);
test__mulodi4(1, 0x7FFFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF, 0);
test__mulodi4(0x7FFFFFFFFFFFFFFF, 2, @bitCast(i64, @as(u64, 0x8000000000000001)), 1);
test__mulodi4(2, 0x7FFFFFFFFFFFFFFF, @bitCast(i64, @as(u64, 0x8000000000000001)), 1);
test__mulodi4(@bitCast(i64, @as(u64, 0x8000000000000000)), -2, @bitCast(i64, @as(u64, 0x8000000000000000)), 1);
test__mulodi4(-2, @bitCast(i64, @as(u64, 0x8000000000000000)), @bitCast(i64, @as(u64, 0x8000000000000000)), 1);
test__mulodi4(@bitCast(i64, @as(u64, 0x8000000000000000)), -1, @bitCast(i64, @as(u64, 0x8000000000000000)), 1);
test__mulodi4(-1, @bitCast(i64, @as(u64, 0x8000000000000000)), @bitCast(i64, @as(u64, 0x8000000000000000)), 1);
test__mulodi4(@bitCast(i64, @as(u64, 0x8000000000000000)), 0, 0, 0);
test__mulodi4(0, @bitCast(i64, @as(u64, 0x8000000000000000)), 0, 0);
test__mulodi4(@bitCast(i64, @as(u64, 0x8000000000000000)), 1, @bitCast(i64, @as(u64, 0x8000000000000000)), 0);
test__mulodi4(1, @bitCast(i64, @as(u64, 0x8000000000000000)), @bitCast(i64, @as(u64, 0x8000000000000000)), 0);
test__mulodi4(@bitCast(i64, @as(u64, 0x8000000000000000)), 2, @bitCast(i64, @as(u64, 0x8000000000000000)), 1);
test__mulodi4(2, @bitCast(i64, @as(u64, 0x8000000000000000)), @bitCast(i64, @as(u64, 0x8000000000000000)), 1);
test__mulodi4(@bitCast(i64, @as(u64, 0x8000000000000001)), -2, @bitCast(i64, @as(u64, 0x8000000000000001)), 1);
test__mulodi4(-2, @bitCast(i64, @as(u64, 0x8000000000000001)), @bitCast(i64, @as(u64, 0x8000000000000001)), 1);
test__mulodi4(@bitCast(i64, @as(u64, 0x8000000000000001)), -1, 0x7FFFFFFFFFFFFFFF, 0);
test__mulodi4(-1, @bitCast(i64, @as(u64, 0x8000000000000001)), 0x7FFFFFFFFFFFFFFF, 0);
test__mulodi4(@bitCast(i64, @as(u64, 0x8000000000000001)), 0, 0, 0);
test__mulodi4(0, @bitCast(i64, @as(u64, 0x8000000000000001)), 0, 0);
test__mulodi4(@bitCast(i64, @as(u64, 0x8000000000000001)), 1, @bitCast(i64, @as(u64, 0x8000000000000001)), 0);
test__mulodi4(1, @bitCast(i64, @as(u64, 0x8000000000000001)), @bitCast(i64, @as(u64, 0x8000000000000001)), 0);
test__mulodi4(@bitCast(i64, @as(u64, 0x8000000000000001)), 2, @bitCast(i64, @as(u64, 0x8000000000000000)), 1);
test__mulodi4(2, @bitCast(i64, @as(u64, 0x8000000000000001)), @bitCast(i64, @as(u64, 0x8000000000000000)), 1);
} | lib/std/special/compiler_rt/mulodi4_test.zig |
const std = @import("std");
const sling = @import("sling.zig");
const Self = @This();
pub const EditorData = struct {
filePath: ?[]const u8 = null,
selectedObjectGroup: usize = 0,
selectedEntity: usize = 0,
objectToIndex: std.StringHashMap(usize) = std.StringHashMap(usize).init(sling.alloc),
};
baseObject: *sling.Object.Interface = undefined,
childObjects: []*sling.Object.Interface = undefined,
source: sling.register.SceneRegister = undefined,
editorData: EditorData = .{},
isSpoof: bool = false,
/// If you've registered a type as a scene, then you can pass it in here to construct
/// an empty scene.
pub fn init(comptime baseType: type) *Self {
var fetch = sling.register.RegisteredScenes.get(@typeName(baseType));
if (fetch == null) {
std.debug.panic("Initializing a scene that isnt configured", .{});
}
var sceneRegister: sling.register.SceneRegister = fetch.?;
return initFromInfo(sceneRegister);
}
/// Spoofs a real scene, the base object is not defined, and has the provided children.
/// Children is expected to be a tuple of types that this contains, for example
/// `.{Player,WeaponPickup,Enemy}`
pub fn initSpoof(comptime children: anytype) *Self {
sling.logWarn("Creating a spoofed scene");
var self: *Self = sling.alloc.create(Self) catch unreachable;
self.* = .{};
const childrenType = @typeInfo(@TypeOf(children));
std.debug.assert(childrenType == .Struct and childrenType.Struct.is_tuple);
std.debug.assert(@TypeOf(children[0]) == type);
self.baseObject = undefined;
self.isSpoof = true;
self.childObjects = sling.alloc.alloc(*sling.Object.Interface, children.len) catch unreachable;
inline for (children) |child, i| {
var info = sling.Object.GenBuildData(child).information;
self.editorData.objectToIndex.put(info.name, i) catch unreachable;
self.childObjects[i] = info.create(self);
}
return self;
}
pub fn deinit(self: *Self) void {
sling.logWarn("Deiniting a scene.");
self.editorData.objectToIndex.deinit();
self.baseObject.deinitAll(self.baseObject);
self.baseObject.arena.deinit();
self.baseObject = undefined;
for (self.childObjects) |*co| {
co.*.deinitAll(co.*);
co.*.arena.deinit();
co.* = undefined;
}
sling.alloc.free(self.childObjects);
self.* = undefined;
sling.alloc.destroy(self);
}
/// A more manual approach, takes a scene register and constructs an empty scene.
pub fn initFromInfo(sceneRegister: sling.register.SceneRegister) *Self {
var self: *Self = sling.alloc.create(Self) catch unreachable;
self.* = .{};
self.baseObject = sling.Object.Information.get(sceneRegister.base).createSingleton(self);
self.childObjects = sling.alloc.alloc(*sling.Object.Interface, sceneRegister.dependants.items.len) catch unreachable;
for (self.childObjects) |*obj, i| {
var info = sling.Object.Information.get(sceneRegister.dependants.items[i]);
self.editorData.objectToIndex.put(info.name, i) catch unreachable;
obj.* = info.create(self);
}
sling.log("Created a scene from scene register information.");
return self;
}
/// Takes bytes and creates a scene, it correctly picks the scene type for you provided
/// it exists in your game still.
pub fn initFromBytes(data: []const u8) *Self {
var parsed = sling.serializer.json.JsonLexicon.parse(sling.alloc, data);
defer parsed.deinit();
var self: *Self = sling.alloc.create(Self) catch unreachable;
self.* = .{};
if (parsed.root.data.Map.get("scene_type")) |node| {
std.debug.assert(node.data == .Literal and node.data.Literal == .String);
var ObjectSlice = sling.Object.Information.slice();
for (ObjectSlice) |info| {
if (std.mem.eql(u8, info.name, node.data.Literal.String)) {
var sceneObject = parsed.root.data.Map.get("scene").?;
self.baseObject = info.createSingletonFrom(sceneObject, self);
var sceneRegister = sling.register.RegisteredScenes.get(info.name).?;
self.childObjects = sling.alloc.alloc(*sling.Object.Interface, sceneRegister.dependants.items.len) catch unreachable;
self.source = sceneRegister;
break;
}
}
} else {
std.debug.panic("Failed to find a scene_type definition in the provided bytes:\n{s}", .{data});
}
if (parsed.root.data.Map.get("children")) |childrenList| {
std.debug.assert(childrenList.data == .Map);
var iter = childrenList.data.Map.iterator();
var slice = sling.Object.Information.slice();
var i: usize = 0;
while (iter.next()) |pair| {
for (slice) |info| {
if (std.mem.eql(u8, pair.key_ptr.*, info.name)) {
self.editorData.objectToIndex.put(info.name, i) catch unreachable;
self.childObjects[i] = info.createFrom(pair.value_ptr.*, self);
}
}
i += 1;
}
} else {
std.debug.panic("Failed to find a children definition in the provided bytes:\n{s}", .{data});
}
sling.log("Created a scene from raw bytes.");
return self;
}
/// Takes a filepath and creates a scene, it correctly picks the scene type for you provided
/// it exists in your game still.
pub fn initFromFilepath(path: []const u8) *Self {
var bytes = std.fs.cwd().readFileAlloc(sling.alloc, path, 80_000_000) catch unreachable;
defer sling.alloc.free(bytes);
sling.logFmt("Creating a scene from filepath {s}", .{path});
var self = initFromBytes(bytes);
var ownedPath = sling.alloc.dupeZ(u8, path) catch unreachable;
self.editorData.filePath = ownedPath;
return self;
}
/// You don't need to call this, the game does this for you.
pub fn update(self: *Self) void {
if (!self.isSpoof) {
self.baseObject.update(self.baseObject);
}
for (self.childObjects) |child| {
child.update(child);
}
}
/// Spits out an owned string that represents your scene in your preferrec
/// storage format.
pub fn toBytes(self: *Self, allocator: *std.mem.Allocator) []const u8 {
if (self.isSpoof) {
std.debug.panic("Improper method call on spoofed scene\n", .{});
}
var tree = sling.serializer.Tree.initArena(allocator);
tree.config = &sling.preferredSerializationConfig;
defer tree.deinit();
// Child objects
var children = tree.newObject();
for (self.childObjects) |interface| {
children.data.Map.put(interface.information.name, interface.serialize(interface, tree)) catch unreachable;
}
// Add to root
tree.root = tree.newObject();
var ownedName = tree.alloc.internal().dupeZ(u8, self.baseObject.information.name) catch unreachable;
tree.root.data.Map.put("scene_type", tree.newString(ownedName)) catch unreachable;
tree.root.data.Map.put("scene", self.baseObject.serialize(self.baseObject, tree)) catch unreachable;
tree.root.data.Map.put("children", children) catch unreachable;
// Serialize
return sling.preferredLexicon.convert(allocator, tree);
}
/// Checks if the scene contains a child type, if it does it is returned. Note
/// that this reference is invalidated if you modify the group by appending
/// or deleting.
pub fn has(self: *Self, comptime target: type) ?[]target {
for (self.childObjects) |child| {
if (std.mem.eql(u8, @typeName(target), child.information.name)) {
const wrapper = sling.Object.CollectionType(target);
return @fieldParentPtr(wrapper, "interface", child).value;
}
}
return null;
}
/// Checks if the scene's base type is `target`. If it is, then it returns
/// a temporary reference to the value. It's fine to call this constantly
/// if you need to refer to it frequently.
pub fn is(self: *Self, comptime target: type) ?*target {
if (self.isSpoof) {
return null;
}
if (std.mem.eql(u8, @typeName(target), self.baseObject.information.name)) {
const wrapper = sling.Object.SingletonType(target);
return &@fieldParentPtr(wrapper, "interface", self.baseObject).value;
}
return null;
}
/// The returned entity reference is only good until the next time an entity is appended.
/// Keep this in mind and don't store this reference.
pub fn spawn(self: *Self, comptime target: type) ?*target {
for (self.childObjects) |child| {
if (std.mem.eql(u8, @typeName(target), child.information.name)) {
const wrapper = sling.Object.CollectionType(target);
child.data.Collection.append(child);
var array = @fieldParentPtr(wrapper, "interface", child).value;
return &array[array.len - 1];
}
}
return null;
}
/// Takes a type and returns the index of the interface that contains the type.
/// Mostly useful for editor related functionality
pub fn objectIndexFor(self: *Self, comptime T: type) usize {
return self.editorData.objectToIndex.get(@typeName(T)).?;
}
pub fn setFilepath(self: *Self, path: []const u8) void {
var owned = sling.alloc.dupeZ(u8, path) catch unreachable;
self.editorData.filePath = owned;
} | src/scene.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const Value = @import("./value.zig").Value;
const Vm = @import("./vm.zig").Vm;
const ObjType = enum {
string,
};
pub const Obj = struct {
obj_type: ObjType,
next: ?*Obj,
pub fn create(vm: *Vm, comptime T: type, obj_type: ObjType) *T {
const ptr_t = vm.allocator.create(T) catch @panic("Error creating Obj\n");
ptr_t.obj = Obj{
.obj_type = obj_type,
.next = vm.objects,
};
vm.objects = &ptr_t.obj;
return ptr_t;
}
pub fn asString(self: *Obj) *String {
return @fieldParentPtr(String, "obj", self);
}
pub fn is(self: *Obj, obj_type: ObjType) bool {
return self.obj_type == obj_type;
}
pub fn toValue(self: *Obj) Value {
return Value.fromObj(self);
}
pub fn destroy(self: *Obj, vm: *Vm) void {
switch (self.obj_type) {
.string => self.asString().destroy(vm),
}
}
pub const String = struct {
obj: Obj,
bytes: []const u8,
hash: u32,
fn allocate(vm: *Vm, bytes: []const u8, hash: u32) *String {
const str = Obj.create(vm, @This(), .string);
str.bytes = bytes;
str.hash = hash;
_ = vm.strings.set(str, Value.nil);
return str;
}
pub fn copy(vm: *Vm, bytes: []const u8) *String {
const hash = hashBytes(bytes);
return vm.strings.findString(bytes, hash) orelse {
const heapBytes = vm.allocator.alloc(u8, bytes.len) catch @panic("Error copying String\n");
std.mem.copy(u8, heapBytes, bytes);
return allocate(vm, heapBytes, hash);
};
}
/// Assumes it can take the bytes instead of copying them
pub fn take(vm: *Vm, bytes: []const u8) *String {
const hash = hashBytes(bytes);
const interned = vm.strings.findString(bytes, hash);
if (interned != null) {
vm.allocator.free(bytes);
return interned.?;
}
return allocate(vm, bytes, hash);
}
pub fn destroy(self: *String, vm: *Vm) void {
vm.allocator.free(self.bytes);
vm.allocator.destroy(self);
}
};
};
fn hashBytes(bytes: []const u8) u32 {
var hash: u32 = 2166136261;
for (bytes) |byte| {
hash ^= byte;
hash *%= 16777619;
}
return hash;
} | src/object.zig |
usingnamespace @import("root").preamble;
const log = lib.output.log.scoped(.{
.prefix = "Interrupts",
.filter = .info,
}).write;
const msr = @import("aarch64.zig").msr;
pub const InterruptState = bool;
pub fn get_and_disable_interrupts() InterruptState {
// Get interrupt mask flag
var daif = msr(u64, "DAIF").read();
// Set the flag
msr(u64, "DAIFSET").write(2);
// Check if it was set
return (daif >> 7) & 1 == 0;
}
pub fn set_interrupts(s: InterruptState) void {
if (s) {
// Enable interrupts
msr(u64, "DAIFCLR").write(2);
} else {
// Disable interrupts
msr(u64, "DAIFSET").write(2);
}
}
pub const InterruptFrame = struct {
spsr: u64,
pc: u64,
x31: u64,
x30: u64,
x29: u64,
x28: u64,
x27: u64,
x26: u64,
x25: u64,
x24: u64,
x23: u64,
x22: u64,
x21: u64,
x20: u64,
x19: u64,
x18: u64,
x17: u64,
x16: u64,
x15: u64,
x14: u64,
x13: u64,
x12: u64,
x11: u64,
x10: u64,
x9: u64,
x8: u64,
x7: u64,
x6: u64,
x5: u64,
x4: u64,
x3: u64,
x2: u64,
sp: u64,
_: u64 = undefined,
x1: u64,
x0: u64,
pub fn format(self: *const @This(), fmt: anytype) void {
fmt(" X0 ={0X} X1 ={0X} X2 ={0X} X3 ={0X}\n", .{ self.x0, self.x1, self.x2, self.x3 });
fmt(" X4 ={0X} X5 ={0X} X6 ={0X} X7 ={0X}\n", .{ self.x4, self.x5, self.x6, self.x7 });
fmt(" X8 ={0X} X9 ={0X} X10={0X} X11={0X}\n", .{ self.x8, self.x9, self.x10, self.x11 });
fmt(" X12={0X} X13={0X} X14={0X} X15={0X}\n", .{ self.x12, self.x13, self.x14, self.x15 });
fmt(" X16={0X} X17={0X} X18={0X} X19={0X}\n", .{ self.x16, self.x17, self.x18, self.x19 });
fmt(" X20={0X} X21={0X} X22={0X} X23={0X}\n", .{ self.x20, self.x21, self.x22, self.x23 });
fmt(" X24={0X} X25={0X} X26={0X} X27={0X}\n", .{ self.x24, self.x25, self.x26, self.x27 });
fmt(" X28={0X} X29={0X} X30={0X} X31={0X}\n", .{ self.x28, self.x29, self.x30, self.x31 });
fmt(" PC ={0X} SP ={0X} SPSR={0X}", .{ self.pc, self.sp, self.spsr });
}
pub fn trace_stack(self: *const @This()) void {
os.kernel.debug.dumpFrame(self.x29, self.pc);
}
};
comptime {
asm (
\\handle_interrupt_on_stack:
\\MRS X1, SP_EL0
\\STP X1, XZR, [X0, #-0x20]
\\
\\MSR SP_EL0, X0 // Use this stack
\\
\\LDP X1, X0, [SP], 0x10
\\MSR SPSel, #0 // Switch stacks
\\STP X1, X0, [SP, #-0x10]!
\\
\\SUB SP, SP, #0x10
\\
\\interrupt_common:
\\STP X3, X2, [SP, #-0x10]!
\\STP X5, X4, [SP, #-0x10]!
\\STP X7, X6, [SP, #-0x10]!
\\STP X9, X8, [SP, #-0x10]!
\\STP X11, X10, [SP, #-0x10]!
\\STP X13, X12, [SP, #-0x10]!
\\STP X15, X14, [SP, #-0x10]!
\\STP X17, X16, [SP, #-0x10]!
\\STP X19, X18, [SP, #-0x10]!
\\STP X21, X20, [SP, #-0x10]!
\\STP X23, X22, [SP, #-0x10]!
\\STP X25, X24, [SP, #-0x10]!
\\STP X27, X26, [SP, #-0x10]!
\\STP X29, X28, [SP, #-0x10]!
\\STP X31, X30, [SP, #-0x10]!
\\MRS X0, SPSR_EL1
\\MRS X1, ELR_EL1
\\STP X0, X1, [SP, #-0x10]!
\\MOV X0, SP
\\BL interrupt_handler
\\LDP X0, X1, [SP], 0x10
\\MSR SPSR_EL1, X0
\\MSR ELR_EL1, X1
\\LDP X31, X30, [SP], 0x10
\\LDP X29, X28, [SP], 0x10
\\LDP X27, X26, [SP], 0x10
\\LDP X25, X24, [SP], 0x10
\\LDP X23, X22, [SP], 0x10
\\LDP X21, X20, [SP], 0x10
\\LDP X19, X18, [SP], 0x10
\\LDP X17, X16, [SP], 0x10
\\LDP X15, X14, [SP], 0x10
\\LDP X13, X12, [SP], 0x10
\\LDP X11, X10, [SP], 0x10
\\LDP X9, X8, [SP], 0x10
\\LDP X7, X6, [SP], 0x10
\\LDP X5, X4, [SP], 0x10
\\LDP X3, X2, [SP], 0x10
\\
\\LDP X1, XZR, [SP], 0x10
\\MRS X0, SPSel
\\CBNZ X0, .int_stack_ret
\\ // Return from non-interrupt stack
\\
\\MSR SPSel, #1
\\STP X1, XZR, [SP, #-0x20]
\\MSR SPSel, #0
\\LDP X1, X0, [SP], 0x10
\\MSR SPSel, #1
\\STP X1, X0, [SP, #-0x10]
\\LDP X1, XZR, [SP, #-0x20]
\\MSR SP_EL0, X1
\\LDP X1, X0, [SP, #-0x10]
\\MSR SPSel, #0
\\ERET
\\
\\.int_stack_ret:
\\ // Return from int stack
\\
\\MSR SP_EL0, X1
\\LDP X1, X0, [SP], 0x10
\\MSR SPSel, #0
\\ERET
);
}
/// The vector which uses the already selected interrupt stack
export fn interrupt_irq_stack() callconv(.Naked) void {
asm volatile (
\\STP X1, X0, [SP, #-0x10]!
\\
\\MRS X1, SP_EL0
\\STP X1, XZR, [SP, #-0x10]!
\\
\\B interrupt_common
);
unreachable;
}
/// The vector which switches to the per-CPU scheduler stack
export fn interrupt_sched_stack() callconv(.Naked) void {
asm volatile (
\\STP X1, X0, [SP, #-0x10]!
\\
\\MRS X0, TPIDR_EL1 // Get the current cpu struct
\\LDR X0, [X0, %[sched_stack_offset]] // Get the CPU scheduler stack
\\
\\B handle_interrupt_on_stack
:
: [sched_stack_offset] "i" (@as(usize, @offsetOf(os.platform.smp.CoreData, "sched_stack")))
);
unreachable;
}
/// The vector which switches to the per-task syscall stack
export fn interrupt_syscall_stack() callconv(.Naked) void {
asm volatile (
\\STP X1, X0, [SP, #-0x10]!
\\
\\MRS X0, TPIDR_EL1 // Get the current cpu struct
\\LDR X0, [X0, %[task_offset]] // Get the task
\\LDR X0, [X0, %[syscall_stack_offset]]
\\
\\B handle_interrupt_on_stack
:
: [task_offset] "i" (@as(usize, @offsetOf(os.platform.smp.CoreData, "current_task"))),
[syscall_stack_offset] "i" (@as(usize, @offsetOf(os.thread.Task, "stack")))
);
unreachable;
}
/// The handler for everything else, which should cause some kind
/// of panic or similar.
export fn unhandled_vector() callconv(.Naked) void {
// We don't plan on returning, calling the scheduler
// nor enabling interrupts in this handler one, so
// we can just use any handler here
asm volatile (
\\B interrupt_irq_stack
);
unreachable;
}
comptime {
asm (
\\.section .text.evt
\\.balign 0x800
\\.global exception_vector_table; exception_vector_table:
\\ // Normal IRQs/scheduler calls from within kernel
\\.balign 0x80; B interrupt_sched_stack // curr_el_sp0_sync
\\.balign 0x80; B interrupt_irq_stack // curr_el_sp0_irq
\\.balign 0x80; B interrupt_irq_stack // curr_el_sp0_fiq
\\.balign 0x80; B unhandled_vector // curr_el_sp0_serror
\\ // The following 4 are unsupported as we only use spx with interrupts disabled,
\\ // in a context where a fail probably shouldn't be handled either.
\\.balign 0x80; B unhandled_vector // curr_el_spx_sync
\\.balign 0x80; B unhandled_vector // curr_el_spx_irq
\\.balign 0x80; B unhandled_vector // curr_el_spx_fiq
\\.balign 0x80; B unhandled_vector // curr_el_spx_serror
\\ // Userspace IRQs or syscalls
\\.balign 0x80; B interrupt_syscall_stack // lower_el_aarch64_sync
\\.balign 0x80; B interrupt_irq_stack // lower_el_aarch64_irq
\\.balign 0x80; B interrupt_irq_stack // lower_el_aarch64_fiq
\\.balign 0x80; B interrupt_syscall_stack // lower_el_aarch64_serror
\\ // 32 bit Userspace IRQs or syscalls
\\.balign 0x80; B interrupt_syscall_stack // lower_el_aarch32_sync
\\.balign 0x80; B interrupt_irq_stack // lower_el_aarch32_irq
\\.balign 0x80; B interrupt_irq_stack // lower_el_aarch32_fiq
\\.balign 0x80; B interrupt_syscall_stack // lower_el_aarch32_serror
);
}
extern const exception_vector_table: [0x800]u8;
pub fn install_vector_table() void {
asm volatile (
\\MSR VBAR_EL1, %[evt]
:
: [evt] "r" (&exception_vector_table)
);
}
fn do_stack_call(frame: *InterruptFrame) void {
const fun = @intToPtr(fn (*os.platform.InterruptFrame, usize) void, frame.x2);
const ctx: usize = frame.x1;
fun(frame, ctx);
}
export fn interrupt_handler(frame: *InterruptFrame) callconv(.C) void {
const esr = asm volatile ("MRS %[esr], ESR_EL1"
: [esr] "=r" (-> u64)
);
const ec = (esr >> 26) & 0x3f;
const iss = esr & 0x1ffffff;
const userspace_process = if ((frame.spsr & 0xF) == 0) os.kernel.process.currentProcess() else null;
const far = asm volatile ("MRS %[esr], FAR_EL1"
: [esr] "=r" (-> u64)
);
const wnr = (iss >> 6) & 1;
const dfsc = iss & 0x3f;
// Assume present == !translation fault
const present = (dfsc & 0b111100) != 0b000100;
if (ec == 0b111100) {
log(null, "BRK instruction execution in AArch64 state\n", .{});
os.platform.hang();
}
switch (ec) {
else => {
log(null,
\\EC = 0x{X}
\\Frame dump:
\\{}
, .{ ec, frame });
frame.trace_stack();
@panic("Unknown EC!");
},
0b00000000 => {
log(null, "Frame dump:\n{}", .{frame});
frame.trace_stack();
@panic("Unknown reason in EC!");
},
0b00100100 => { // Data abort from userspace
userspace_process.?.onPageFault(far, present, if (wnr == 1) .Write else .Read, frame);
},
0b00100101 => { // Data abort from kernel
os.platform.page_fault(far, present, if (wnr == 1) .Write else .Read, frame);
},
0b00100000 => { // Instruction fault from userspace
userspace_process.?.onPageFault(far, false, .InstructionFetch, frame);
},
0b00100001 => { // Instruction fault from kernel
os.platform.page_fault(far, false, .InstructionFetch, frame);
},
0b00010101 => { // SVC instruction execution in AArch64 state
if (userspace_process) |p| {
p.handleSyscall(frame);
} else {
// Figure out which call this is
switch (@truncate(u16, iss)) {
else => @panic("Unknown SVC"),
'S' => do_stack_call(frame),
}
}
},
}
}
pub fn set_interrupt_stack(int_stack: usize) void {
const current_stack = asm volatile ("MRS %[res], SPSel"
: [res] "=r" (-> u64)
);
if (current_stack != 0) @panic("Cannot set interrupt stack while using it!");
asm volatile (
\\ MSR SPSel, #1
\\ MOV SP, %[int_stack]
\\ MSR SPSel, #0
:
: [int_stack] "r" (int_stack)
);
} | subprojects/flork/src/platform/aarch64/interrupts.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const math = std.math;
const testing = std.testing;
const util = @import("util.zig");
const Error = util.Error;
/// BinaryFuse8 provides a binary fuse filter with 8-bit fingerprints.
///
/// See `BinaryFuse` for more details.
pub const BinaryFuse8 = BinaryFuse(u8);
/// A binary fuse filter. This is an extension of fuse filters:
///
/// Dietzfelbinger & Walzer's fuse filters, described in "Dense Peelable Random Uniform Hypergraphs",
/// https://arxiv.org/abs/1907.04749, can accomodate fill factors up to 87.9% full, rather than
/// 1 / 1.23 = 81.3%. In the 8-bit case, this reduces the memory usage from 9.84 bits per entry to
/// 9.1 bits.
///
/// An issue with traditional fuse filters is that the algorithm requires a large number of unique
/// keys in order for population to succeed, see [FastFilter/xor_singleheader#21](https://github.com/FastFilter/xor_singleheader/issues/21).
/// If you have few (<~125k consecutive) keys, fuse filter creation would fail.
///
/// By contrast, binary fuse filters, a revision of fuse filters made by <NAME> &
/// <NAME> do not suffer from this issue. See https://github.com/FastFilter/xor_singleheader/issues/21
///
/// Note: We assume that you have a large set of 64-bit integers and you want a data structure to
/// do membership tests using no more than ~8 or ~16 bits per key. If your initial set is made of
/// strings or other types, you first need to hash them to a 64-bit integer.
pub fn BinaryFuse(comptime T: type) type {
return struct {
allocator: Allocator,
seed: u64,
segment_length: u32,
segment_length_mask: u32,
segment_count: u32,
segment_count_length: u32,
fingerprints: []T,
/// probability of success should always be > 0.5 so 100 iterations is highly unlikely
max_iterations: usize = 100,
const Self = @This();
/// initializes a binary fuse filter with enough capacity for a set containing up to `size`
/// elements.
///
/// `deinit()` must be called by the caller to free the memory.
pub fn init(allocator: Allocator, size: usize) !*Self {
const arity: u32 = 3;
var segment_length = calculateSegmentLength(arity, size);
if (segment_length > 262144) {
segment_length = 262144;
}
const segment_length_mask = segment_length - 1;
const size_factor: f64 = if (size == 0) 4 else calculateSizeFactor(arity, size);
const capacity = if (size <= 1) 0 else @floatToInt(u32, math.round(@intToFloat(f64, size) * size_factor));
const init_segment_count: u32 = (capacity + segment_length - 1) / segment_length -% (arity - 1);
var slice_length = (init_segment_count +% arity - 1) * segment_length;
var segment_count = (slice_length + segment_length - 1) / segment_length;
if (segment_count <= arity - 1) {
segment_count = 1;
} else {
segment_count = segment_count - (arity - 1);
}
slice_length = (segment_count + arity - 1) * segment_length;
const segment_count_length = segment_count * segment_length;
const self = try allocator.create(Self);
self.* = Self{
.allocator = allocator,
.seed = undefined,
.segment_length = segment_length,
.segment_length_mask = segment_length_mask,
.segment_count = segment_count,
.segment_count_length = segment_count_length,
.fingerprints = try allocator.alloc(T, slice_length),
};
return self;
}
pub inline fn deinit(self: *Self) void {
self.allocator.free(self.fingerprints);
self.allocator.destroy(self);
}
/// reports the size in bytes of the filter.
pub inline fn sizeInBytes(self: *Self) usize {
return self.fingerprints.len * @sizeOf(T) + @sizeOf(Self);
}
/// populates the filter with the given keys.
///
/// The caller is responsible for ensuring that there are no duplicated keys.
///
/// The inner loop will run up to max_iterations times (default 100) and will never fail,
/// except if there are duplicated keys.
///
/// The provided allocator will be used for creating temporary buffers that do not outlive the
/// function call.
pub fn populate(self: *Self, allocator: Allocator, keys: []u64) Error!void {
const iter = try util.sliceIterator(u64).init(allocator, keys);
defer iter.deinit();
return self.populateIter(allocator, iter);
}
/// Identical to populate, except it takes an iterator of keys so you need not store them
/// in-memory.
///
/// `keys.next()` must return `?u64`, the next key or none if the end of the list has been
/// reached. The iterator must reset after hitting the end of the list, such that the `next()`
/// call leads to the first element again.
///
/// `keys.len()` must return the `usize` length.
pub fn populateIter(self: *Self, allocator: Allocator, keys: anytype) Error!void {
if (keys.len() == 0) {
return;
}
var rng_counter: u64 = 0x726b2b9d438b9d4d;
self.seed = util.rngSplitMix64(&rng_counter);
const size = keys.len();
const reverse_order = try allocator.alloc(u64, size + 1);
defer allocator.free(reverse_order);
std.mem.set(u64, reverse_order, 0);
const capacity = self.fingerprints.len;
const alone = try allocator.alloc(u32, capacity);
defer allocator.free(alone);
const t2count = try allocator.alloc(T, capacity);
defer allocator.free(t2count);
std.mem.set(T, t2count, 0);
const reverse_h = try allocator.alloc(T, size);
defer allocator.free(reverse_h);
const t2hash = try allocator.alloc(u64, capacity);
defer allocator.free(t2hash);
std.mem.set(u64, t2hash, 0);
var block_bits: u5 = 1;
while ((@as(u32, 1) << block_bits) < self.segment_count) {
block_bits += 1;
}
const block: u32 = @as(u32, 1) << block_bits;
const start_pos = try allocator.alloc(u32, @as(usize, 1) << block_bits);
defer allocator.free(start_pos);
var h012: [5]u32 = undefined;
reverse_order[size] = 1;
var loop: usize = 0;
while (true) : (loop += 1) {
if (loop + 1 > self.max_iterations) {
return Error.KeysLikelyNotUnique; // too many iterations, keys are not unique.
}
var i: u32 = 0;
while (i < block) : (i += 1) {
// important : i * size would overflow as a 32-bit number in some
// cases.
start_pos[i] = @truncate(u32, (@intCast(u64, i) * size) >> block_bits);
}
const mask_block: u64 = block - 1;
while (keys.next()) |key| {
const hash: u64 = util.murmur64(key + self.seed);
const shift_count = @as(usize, 64) - @as(usize, block_bits);
var segment_index: u64 = if (shift_count >= 63) 0 else hash >> @truncate(u6, shift_count);
while (reverse_order[start_pos[segment_index]] != 0) {
segment_index += 1;
segment_index &= mask_block;
}
reverse_order[start_pos[segment_index]] = hash;
start_pos[segment_index] += 1;
}
var err = false;
i = 0;
while (i < size) : (i += 1) {
const hash = reverse_order[i];
const h0 = self.fuseHash(0, hash);
t2count[h0] += 4;
t2hash[h0] ^= hash;
const h1 = self.fuseHash(1, hash);
t2count[h1] += 4;
t2count[h1] ^= 1;
t2hash[h1] ^= hash;
const h2 = self.fuseHash(2, hash);
t2count[h2] += 4;
t2hash[h2] ^= hash;
t2count[h2] ^= 2;
err = (t2count[h0] < 4) or err;
err = (t2count[h1] < 4) or err;
err = (t2count[h2] < 4) or err;
}
if (err) continue;
// End of key addition
var Qsize: u32 = 0;
// Add sets with one key to the queue.
i = 0;
while (i < capacity) : (i += 1) {
alone[Qsize] = i;
Qsize += if ((t2count[i] >> 2) == 1) @as(u32, 1) else @as(u32, 0);
}
var stacksize: u32 = 0;
while (Qsize > 0) {
Qsize -= 1;
const index: u32 = alone[Qsize];
if ((t2count[index] >> 2) == 1) {
const hash = t2hash[index];
//h012[0] = self.fuseHash(0, hash);
h012[1] = self.fuseHash(1, hash);
h012[2] = self.fuseHash(2, hash);
h012[3] = self.fuseHash(0, hash); // == h012[0];
h012[4] = h012[1];
const found = t2count[index] & 3;
reverse_h[stacksize] = found;
reverse_order[stacksize] = hash;
stacksize += 1;
const other_index1 = h012[found + 1];
alone[Qsize] = other_index1;
Qsize += if ((t2count[other_index1] >> 2) == 2) @as(u32, 1) else @as(u32, 0);
t2count[other_index1] -= 4;
t2count[other_index1] ^= fuseMod3(T, found + 1);
t2hash[other_index1] ^= hash;
const other_index2 = h012[found + 2];
alone[Qsize] = other_index2;
Qsize += if ((t2count[other_index2] >> 2) == 2) @as(u32, 1) else @as(u32, 0);
t2count[other_index2] -= 4;
t2count[other_index2] ^= fuseMod3(T, found + 2);
t2hash[other_index2] ^= hash;
}
}
if (stacksize == size) {
// success
break;
}
std.mem.set(u64, reverse_order[0..size], 0);
std.mem.set(T, t2count[0..capacity], 0);
std.mem.set(u64, t2hash[0..capacity], 0);
self.seed = util.rngSplitMix64(&rng_counter);
}
var i: u32 = @truncate(u32, size - 1);
while (i < size) : (i -%= 1) {
// the hash of the key we insert next
const hash: u64 = reverse_order[i];
const xor2: T = @truncate(T, util.fingerprint(hash));
const found: T = reverse_h[i];
h012[0] = self.fuseHash(0, hash);
h012[1] = self.fuseHash(1, hash);
h012[2] = self.fuseHash(2, hash);
h012[3] = h012[0];
h012[4] = h012[1];
self.fingerprints[h012[found]] = xor2 ^ self.fingerprints[h012[found + 1]] ^ self.fingerprints[h012[found + 2]];
}
}
/// reports if the specified key is within the set with false-positive rate.
pub inline fn contain(self: *Self, key: u64) bool {
var hash = util.mixSplit(key, self.seed);
var f = @truncate(T, util.fingerprint(hash));
const hashes = self.fuseHashBatch(hash);
f ^= self.fingerprints[hashes.h0] ^ self.fingerprints[hashes.h1] ^ self.fingerprints[hashes.h2];
return f == 0;
}
inline fn fuseHashBatch(self: *Self, hash: u64) Hashes {
const hi: u64 = mulhi(hash, self.segment_count_length);
var ans: Hashes = undefined;
ans.h0 = @truncate(u32, hi);
ans.h1 = ans.h0 + self.segment_length;
ans.h2 = ans.h1 + self.segment_length;
ans.h1 ^= @truncate(u32, hash >> 18) & self.segment_length_mask;
ans.h2 ^= @truncate(u32, hash) & self.segment_length_mask;
return ans;
}
inline fn fuseHash(self: *Self, index: usize, hash: u64) u32 {
var h = mulhi(hash, self.segment_count_length);
h +%= index * self.segment_length;
// keep the lower 36 bits
const hh: u64 = hash & ((@as(u64, 1) << 36) - 1);
// index 0: right shift by 36; index 1: right shift by 18; index 2: no shift
//
// NOTE(slimsag): using u64 here instead of size_it as in upstream C implementation; I think
// that size_t may be incorrect for 32-bit platforms?
const shift_count = (36 - 18 * index);
if (shift_count >= 63) {
h ^= 0 & self.segment_length_mask;
} else {
h ^= (hh >> @truncate(u6, shift_count)) & self.segment_length_mask;
}
return @truncate(u32, h);
}
};
}
inline fn mulhi(a: u64, b: u64) u64 {
return @truncate(u64, (@intCast(u128, a) *% @intCast(u128, b)) >> 64);
}
const Hashes = struct {
h0: u32,
h1: u32,
h2: u32,
};
inline fn calculateSegmentLength(arity: u32, size: usize) u32 {
// These parameters are very sensitive. Replacing `floor` by `round` can substantially affect
// the construction time.
if (arity == 3) {
const shift_count = @truncate(u32, relaxedFloatToInt(usize, math.floor(math.log(f64, math.e, @intToFloat(f64, size)) / math.log(f64, math.e, 3.33) + 2.25)));
return if (shift_count >= 31) 0 else @as(u32, 1) << @truncate(u5, shift_count);
} else if (arity == 4) {
const shift_count = @truncate(u32, relaxedFloatToInt(usize, math.floor(math.log(f64, math.e, @intToFloat(f64, size)) / math.log(f64, math.e, 2.91) - 0.5)));
return if (shift_count >= 31) 0 else @as(u32, 1) << @truncate(u5, shift_count);
}
return 65536;
}
inline fn relaxedFloatToInt(comptime DestType: type, float: anytype) DestType {
if (math.isInf(float) or math.isNegativeInf(float) or math.isNan(float)) {
return 1 << @bitSizeOf(DestType) - 1;
}
return @floatToInt(DestType, float);
}
inline fn max(a: f64, b: f64) f64 {
return if (a < b) b else a;
}
inline fn calculateSizeFactor(arity: u32, size: usize) f64 {
if (arity == 3) {
return max(1.125, 0.875 + 0.25 * math.log(f64, math.e, 1000000.0) / math.log(f64, math.e, @intToFloat(f64, size)));
} else if (arity == 4) {
return max(1.075, 0.77 + 0.305 * math.log(f64, math.e, 600000.0) / math.log(f64, math.e, @intToFloat(f64, size)));
}
return 2.0;
}
inline fn fuseMod3(comptime T: type, x: T) T {
return if (x > 2) x - 3 else x;
}
fn binaryFuseTest(T: anytype, size: usize, size_in_bytes: usize) !void {
const allocator = std.heap.page_allocator;
const filter = try BinaryFuse(T).init(allocator, size);
comptime filter.max_iterations = 100; // proof we can modify max_iterations at comptime.
defer filter.deinit();
var keys = try allocator.alloc(u64, size);
defer allocator.free(keys);
for (keys) |_, i| {
keys[i] = i;
}
try filter.populate(allocator, keys[0..]);
if (size == 0) {
try testing.expect(!filter.contain(0));
try testing.expect(!filter.contain(1));
}
if (size > 0) try testing.expect(filter.contain(0));
if (size > 1) try testing.expect(filter.contain(1));
if (size > 9) {
try testing.expect(filter.contain(1) == true);
try testing.expect(filter.contain(5) == true);
try testing.expect(filter.contain(9) == true);
}
if (size > 1234) try testing.expect(filter.contain(1234) == true);
try testing.expectEqual(@as(usize, size_in_bytes), filter.sizeInBytes());
for (keys) |key| {
try testing.expect(filter.contain(key) == true);
}
var random_matches: u64 = 0;
const trials = 10000000;
var i: u64 = 0;
var rng = std.rand.DefaultPrng.init(0);
const random = rng.random();
while (i < trials) : (i += 1) {
var random_key: u64 = random.uintAtMost(u64, std.math.maxInt(u64));
if (filter.contain(random_key)) {
if (random_key >= keys.len) {
random_matches += 1;
}
}
}
std.debug.print("fpp {d:3.10} (estimated) \n", .{@intToFloat(f64, random_matches) * 1.0 / trials});
std.debug.print("bits per entry {d:3.1}\n", .{@intToFloat(f64, filter.sizeInBytes()) * 8.0 / @intToFloat(f64, size)});
}
test "binaryFuse8_small_input_edge_cases" {
// See https://github.com/FastFilter/xor_singleheader/issues/26
try binaryFuseTest(u8, 0, 67);
try binaryFuseTest(u8, 1, 76);
try binaryFuseTest(u8, 2, 76);
try binaryFuseTest(u8, 3, 88);
}
test "binaryFuse8_zero" {
try binaryFuseTest(u8, 0, 67);
}
test "binaryFuse8_1" {
try binaryFuseTest(u8, 1, 76);
}
test "binaryFuse8_10" {
try binaryFuseTest(u8, 10, 112);
}
test "binaryFuse8" {
try binaryFuseTest(u8, 1_000_000, 1130560);
}
test "binaryFuse8_2m" {
try binaryFuseTest(u8, 2_000_000, 2261056);
}
test "binaryFuse8_5m" {
try binaryFuseTest(u8, 5_000_000, 5636160);
}
test "binaryFuse16" {
try binaryFuseTest(u16, 1_000_000, 2261056);
}
test "binaryFuse32" {
try binaryFuseTest(u32, 1_000_000, 4522048);
} | src/binaryfusefilter.zig |
const std = @import("std");
const Context = @import("Context.zig");
const Node = @import("Node.zig");
const Parser = @import("Parser.zig");
const Scope = @import("Scope.zig");
pub const Opcode = enum {
// Stack operations
pop,
// Predefined constant values
bool_true,
bool_false,
nil,
// Numbers
float,
int,
uint,
// Strings
format,
plain,
string,
raw_str,
// Scopes
scope_in,
scope_out,
// Functions
builtin,
call,
func,
func_return,
// Variables
define,
load,
set,
store,
global,
gstore,
// Infix
add,
sub,
mul,
div,
mod,
lt,
lte,
gt,
gte,
eq,
neq,
concat,
repeat,
match,
matcher,
nomatch,
// Prefix
neg,
not,
// Data structures
list,
map,
range,
subscript,
// Stack ops
jump,
jump_true,
jump_false,
// Record Range
rec_range,
// Output redirection
redir,
// Printing
sprint,
};
const Index = struct {
index: u16,
prev: ?*Index = null,
};
const JumpUpdates = struct {
prev: ?*JumpUpdates = null,
updates: std.ArrayList(usize),
};
allocator: std.mem.Allocator,
ctx: Context,
ctx_stack: std.ArrayList(std.ArrayList(u8)),
current_loop_start: ?*Index = null, // Index of instruction at current loop start; if applicable.
bytecode: *std.ArrayList(u8) = undefined,
jump_updates: ?*JumpUpdates = null, // Indexes of jump instruciton operands that need updating.
const Compiler = @This();
pub fn init(allocator: std.mem.Allocator, ctx: Context) !Compiler {
var self = Compiler{
.allocator = allocator,
.ctx = ctx,
.ctx_stack = std.ArrayList(std.ArrayList(u8)).init(allocator),
};
try self.pushContext();
return self;
}
pub fn compileProgram(self: *Compiler, allocator: std.mem.Allocator, program: Parser.Program) ![5][]const u8 {
var compiled: [5][]const u8 = undefined;
var arena = std.heap.ArenaAllocator.init(self.allocator);
defer arena.deinit();
const arena_allocator = arena.allocator();
var compiler = try init(arena_allocator, self.ctx);
for (compiled) |_, i| {
try compiler.pushContext();
const event = switch (i) {
0 => program.inits,
1 => program.files,
2 => program.recs,
3 => program.rules,
4 => program.exits,
else => unreachable,
};
for (event) |n| try compiler.compile(n);
compiled[i] = try allocator.dupe(u8, compiler.popContext());
}
return compiled;
}
pub fn compile(self: *Compiler, node: Node) anyerror!void {
switch (node.ty) {
// Stack operations
.stmt_end => try self.pushInstruction(.pop),
// Predefined constant values
.boolean => try self.compileBoolean(node),
.nil => try self.compileNil(node),
// Numbers
.float => try self.compileFloat(node),
.int => try self.compileInt(node),
.uint => try self.compileUint(node),
// Strings
.string => try self.compileString(node),
.raw_str => try self.compileRawStr(node),
// Functions
.call => try self.compileCall(node),
.func => try self.compileFunc(node),
.func_return => try self.compileReturn(node),
// Variables
.define => try self.compileDefine(node),
.ident => try self.compileLoad(node),
.assign => try self.compileStore(node),
.global => try self.compileGlobal(node),
// Operators
.infix => try self.compileInfix(node),
.prefix => try self.compilePrefix(node),
// Data structures
.list => try self.compileList(node),
.map => try self.compileMap(node),
.range => try self.compileRange(node),
.subscript => try self.compileSubscript(node),
// Conditionals
.conditional => try self.compileConditional(node),
// Loops
.loop => try self.compileLoop(node),
.loop_break => try self.compileBreak(),
.loop_continue => try self.compileContinue(),
// Record Range
.rec_range => try self.compileRecRange(node),
// Output redirection
.redir => try self.compileRedir(node),
else => unreachable,
}
}
// Compile functions
fn compileBoolean(self: *Compiler, node: Node) !void {
try self.pushInstruction(if (node.ty.boolean) .bool_true else .bool_false);
try self.pushOffset(node.offset);
}
fn compileNil(self: *Compiler, node: Node) !void {
try self.pushInstruction(.nil);
try self.pushOffset(node.offset);
}
fn compileFloat(self: *Compiler, node: Node) !void {
var slice = std.mem.asBytes(&node.ty.float);
try self.pushInstruction(.float);
try self.pushSlice(slice);
}
fn compileInt(self: *Compiler, node: Node) !void {
var slice = std.mem.asBytes(&node.ty.int);
try self.pushInstruction(.int);
try self.pushSlice(slice);
}
fn compileUint(self: *Compiler, node: Node) !void {
var slice = std.mem.asBytes(&node.ty.uint);
try self.pushInstruction(.uint);
try self.pushSlice(slice);
}
fn compileString(self: *Compiler, node: Node) anyerror!void {
const len = node.ty.string.len;
var i: usize = 1;
while (i <= len) : (i += 1) {
const segment = node.ty.string[len - i];
switch (segment) {
.plain => |plain| {
try self.pushInstruction(.plain);
try self.pushSlice(plain);
try self.pushByte(0);
},
.ipol => |ipol| {
try self.pushInstruction(.scope_in);
try self.pushEnum(Scope.Type.block);
for (ipol.nodes) |n| try self.compile(n);
try self.pushInstruction(.scope_out);
try self.pushEnum(Scope.Type.block);
if (ipol.spec) |spec| {
try self.pushInstruction(.format);
try self.pushOffset(ipol.offset);
try self.pushSlice(spec);
try self.pushByte(0);
}
},
}
}
try self.pushInstruction(.string);
try self.pushLen(len);
}
fn compileRawStr(self: *Compiler, node: Node) anyerror!void {
try self.pushInstruction(.raw_str);
try self.pushSlice(node.ty.raw_str);
try self.pushByte(0);
}
fn compileFunc(self: *Compiler, node: Node) anyerror!void {
// Compile function body to bytecode.
try self.pushContext();
for (node.ty.func.body) |n| try self.compile(n);
const func_bytecode = self.popContext();
// Serialize function to bytes.
try self.pushInstruction(.func);
// Skip bytes for cached functions
const skip_bytes_index = try self.pushZeroes();
var skip_bytes: usize = 0;
// Function string for caching.
var buf = std.ArrayList(u8).init(self.allocator);
defer buf.deinit();
_ = try buf.writer().print("{}", .{node.ty.func});
try self.pushSlice(buf.items);
try self.pushByte(0);
// Function name
if (node.ty.func.name.len != 0) try self.pushSlice(node.ty.func.name);
try self.pushByte(0);
skip_bytes += node.ty.func.name.len + 1;
// Function params
try self.pushLen(node.ty.func.params.len);
skip_bytes += 2;
if (node.ty.func.params.len != 0) {
for (node.ty.func.params) |param| {
try self.pushSlice(param);
try self.pushByte(0);
skip_bytes += param.len + 1;
}
}
// Function bytecode
try self.pushLen(func_bytecode.len);
skip_bytes += 2;
if (func_bytecode.len != 0) try self.pushSlice(func_bytecode);
skip_bytes += func_bytecode.len;
const skip_bytes_bytes = std.mem.asBytes(&@intCast(u16, skip_bytes));
self.bytecode.items[skip_bytes_index] = skip_bytes_bytes[0];
self.bytecode.items[skip_bytes_index + 1] = skip_bytes_bytes[1];
}
fn compileReturn(self: *Compiler, node: Node) anyerror!void {
try self.compile(node.ty.func_return.*);
try self.pushInstruction(.func_return);
}
fn compileCall(self: *Compiler, node: Node) anyerror!void {
if (node.ty.call.callee.ty == .builtin) return self.compileBuiltin(node);
var i: usize = 1;
const num_args = node.ty.call.args.len;
while (i <= num_args) : (i += 1) try self.compile(node.ty.call.args[num_args - i]);
try self.compile(node.ty.call.callee.*);
try self.pushInstruction(.call);
try self.pushOffset(node.offset);
try self.pushByte(num_args);
}
fn compileBuiltin(self: *Compiler, node: Node) anyerror!void {
var i: usize = 1;
const num_args = node.ty.call.args.len;
while (i <= num_args) : (i += 1) try self.compile(node.ty.call.args[num_args - i]);
try self.pushInstruction(.builtin);
try self.pushEnum(node.ty.call.callee.ty.builtin);
try self.pushOffset(node.offset);
try self.pushByte(num_args);
}
fn compileDefine(self: *Compiler, node: Node) anyerror!void {
try self.compile(node.ty.define.rvalue.*);
try self.pushInstruction(.define);
try self.pushOffset(node.offset);
try self.pushSlice(node.ty.define.lvalue.ty.ident);
try self.pushByte(0);
}
fn compileLoad(self: *Compiler, node: Node) anyerror!void {
try self.pushInstruction(.load);
try self.pushOffset(node.offset);
try self.pushSlice(node.ty.ident);
try self.pushByte(0);
}
fn compileStore(self: *Compiler, node: Node) anyerror!void {
try self.compile(node.ty.assign.rvalue.*);
if (node.ty.assign.lvalue.ty == .ident) {
try self.pushInstruction(.store);
try self.pushOffset(node.offset);
try self.pushEnum(node.ty.assign.combo);
try self.pushSlice(node.ty.assign.lvalue.ty.ident);
try self.pushByte(0);
} else if (node.ty.assign.lvalue.ty == .global) {
const global = node.ty.assign.lvalue.ty.global;
if (global == .at_file or global == .at_frnum or global == .at_rnum) return self.ctx.err(
"{s} is a read-only global.",
.{@tagName(global)},
error.ReadOnlyGlobal,
node.offset,
);
try self.pushInstruction(.gstore);
try self.pushOffset(node.offset);
try self.pushEnum(node.ty.assign.lvalue.ty.global);
} else {
try self.compile(node.ty.assign.lvalue.ty.subscript.index.*);
try self.compile(node.ty.assign.lvalue.ty.subscript.container.*);
try self.pushInstruction(.set);
try self.pushOffset(node.offset);
try self.pushEnum(node.ty.assign.combo);
}
}
fn compileGlobal(self: *Compiler, node: Node) !void {
try self.pushInstruction(.global);
try self.pushEnum(node.ty.global);
}
fn compileInfix(self: *Compiler, node: Node) anyerror!void {
if (node.ty.infix.op == .kw_and) return self.compileLogicAnd(node);
if (node.ty.infix.op == .kw_or) return self.compileLogicOr(node);
try self.compile(node.ty.infix.left.*);
try self.compile(node.ty.infix.right.*);
switch (node.ty.infix.op) {
.punct_plus => try self.pushInstruction(.add),
.punct_minus => try self.pushInstruction(.sub),
.punct_star => try self.pushInstruction(.mul),
.punct_slash => try self.pushInstruction(.div),
.punct_percent => try self.pushInstruction(.mod),
.punct_lt => try self.pushInstruction(.lt),
.op_lte => try self.pushInstruction(.lte),
.punct_gt => try self.pushInstruction(.gt),
.op_gte => try self.pushInstruction(.gte),
.op_eq => try self.pushInstruction(.eq),
.op_neq => try self.pushInstruction(.neq),
.op_concat => try self.pushInstruction(.concat),
.op_repeat => try self.pushInstruction(.repeat),
.op_match => try self.pushInstruction(.match),
.op_matcher => try self.pushInstruction(.matcher),
.op_nomatch => try self.pushInstruction(.nomatch),
else => unreachable,
}
try self.pushOffset(node.offset);
}
fn compileLogicAnd(self: *Compiler, node: Node) anyerror!void {
// Left
try self.compile(node.ty.infix.left.*);
// Jump if false
try self.pushInstruction(.jump_false);
const jump_false_operand_index = try self.pushZeroes();
// Right
try self.compile(node.ty.infix.right.*);
// Update jump_false index.
self.updateJumpIndex(jump_false_operand_index);
}
fn compileLogicOr(self: *Compiler, node: Node) anyerror!void {
// Left
try self.compile(node.ty.infix.left.*);
// Jump if true
try self.pushInstruction(.jump_true);
const jump_true_operand_index = try self.pushZeroes();
// Right
try self.compile(node.ty.infix.right.*);
// Update jump_false index.
self.updateJumpIndex(jump_true_operand_index);
}
fn compilePrefix(self: *Compiler, node: Node) !void {
try self.compile(node.ty.prefix.operand.*);
switch (node.ty.prefix.op) {
.op_neg => try self.pushInstruction(.neg),
.punct_bang => try self.pushInstruction(.not),
else => unreachable,
}
try self.pushOffset(node.offset);
}
fn compileList(self: *Compiler, node: Node) anyerror!void {
const len = node.ty.list.len;
var i: usize = 1;
while (i <= len) : (i += 1) try self.compile(node.ty.list[len - i]);
try self.pushInstruction(.list);
try self.pushLen(len);
}
fn compileMap(self: *Compiler, node: Node) anyerror!void {
for (node.ty.map) |entry| {
try self.compile(entry.key);
try self.compile(entry.value);
}
try self.pushInstruction(.map);
try self.pushOffset(node.offset);
try self.pushLen(node.ty.map.len);
}
fn compileSubscript(self: *Compiler, node: Node) anyerror!void {
try self.compile(node.ty.subscript.index.*);
try self.compile(node.ty.subscript.container.*);
try self.pushInstruction(.subscript);
try self.pushOffset(node.offset);
}
fn compileConditional(self: *Compiler, node: Node) anyerror!void {
// Condition
try self.compile(node.ty.conditional.condition.*);
// Jump if false
try self.pushInstruction(.jump_false);
const jump_false_operand_index = try self.pushZeroes();
// Then branch
try self.pushInstruction(.scope_in);
try self.pushEnum(Scope.Type.block);
for (node.ty.conditional.then_branch) |n| try self.compile(n);
try self.pushInstruction(.scope_out);
try self.pushEnum(Scope.Type.block);
// Unconditional jump
try self.pushInstruction(.jump);
const jump_operand_index = try self.pushZeroes();
self.updateJumpIndex(jump_false_operand_index);
// Else branch
try self.pushInstruction(.scope_in);
try self.pushEnum(Scope.Type.block);
for (node.ty.conditional.else_branch) |n| try self.compile(n);
try self.pushInstruction(.scope_out);
try self.pushEnum(Scope.Type.block);
self.updateJumpIndex(jump_operand_index);
}
fn compileLoop(self: *Compiler, node: Node) anyerror!void {
if (node.ty.loop.is_do) return self.compileDoWhile(node);
// Breaks
try self.pushJumpUpdates();
defer self.popJumpUpdates();
// Iterate / Continues
try self.pushCurrentLoopIndex();
defer self.popCurrentLoopIndex();
// Condition
try self.compile(node.ty.loop.condition.*);
// Jump if false
try self.pushInstruction(.jump_false);
try self.jump_updates.?.updates.append(try self.pushZeroes());
// Body
try self.pushInstruction(.scope_in);
try self.pushEnum(Scope.Type.loop);
for (node.ty.loop.body) |n| try self.compile(n);
try self.pushInstruction(.scope_out);
try self.pushEnum(Scope.Type.loop);
// Unconditional jump
try self.pushInstruction(.jump);
try self.pushLen(self.current_loop_start.?.index);
// Update break out jumps.
while (self.jump_updates.?.updates.popOrNull()) |index| self.updateJumpIndex(index);
// while loops always return nul.
try self.pushInstruction(.nil);
try self.pushOffset(node.offset);
}
fn compileDoWhile(self: *Compiler, node: Node) anyerror!void {
// Breaks
try self.pushJumpUpdates();
defer self.popJumpUpdates();
// Iterate / Continues
try self.pushCurrentLoopIndex();
defer self.popCurrentLoopIndex();
// Body
try self.pushInstruction(.scope_in);
try self.pushEnum(Scope.Type.loop);
for (node.ty.loop.body) |n| try self.compile(n);
try self.pushInstruction(.scope_out);
try self.pushEnum(Scope.Type.loop);
// Condition
try self.compile(node.ty.loop.condition.*);
// Jump true
try self.pushInstruction(.jump_true);
try self.pushLen(self.current_loop_start.?.index);
// while loops always return nul.
try self.pushInstruction(.nil);
try self.pushOffset(node.offset);
}
fn compileBreak(self: *Compiler) anyerror!void {
try self.pushInstruction(.scope_out);
try self.pushEnum(Scope.Type.loop);
try self.pushInstruction(.jump);
try self.jump_updates.?.updates.append(try self.pushZeroes());
}
fn compileContinue(self: *Compiler) anyerror!void {
try self.pushInstruction(.scope_out);
try self.pushEnum(Scope.Type.loop);
try self.pushInstruction(.jump);
try self.pushLen(self.current_loop_start.?.index);
}
fn compileRange(self: *Compiler, node: Node) anyerror!void {
try self.compile(node.ty.range.from.*);
try self.compile(node.ty.range.to.*);
try self.pushInstruction(.range);
try self.pushOffset(node.offset);
try self.pushByte(@boolToInt(node.ty.range.inclusive));
}
fn compileRecRange(self: *Compiler, node: Node) anyerror!void {
// Action
var action_bytecode: []const u8 = "";
if (node.ty.rec_range.action.len > 0) {
try self.pushContext();
for (node.ty.rec_range.action) |n| try self.compile(n);
action_bytecode = self.popContext();
}
if (node.ty.rec_range.to) |to| {
try self.compile(to.*);
}
if (node.ty.rec_range.from) |from| {
try self.compile(from.*);
}
try self.pushInstruction(.rec_range);
try self.pushByte(node.ty.rec_range.id);
try self.pushByte(@boolToInt(node.ty.rec_range.exclusive));
try self.pushLen(action_bytecode.len);
if (action_bytecode.len != 0) try self.pushSlice(action_bytecode);
try self.pushByte(@boolToInt(node.ty.rec_range.from != null));
try self.pushByte(@boolToInt(node.ty.rec_range.to != null));
}
fn compileRedir(self: *Compiler, node: Node) anyerror!void {
if (node.ty.redir.expr.ty == .call and
node.ty.redir.expr.ty.call.callee.ty == .ident and
std.mem.eql(u8, node.ty.redir.expr.ty.call.callee.ty.ident, "print"))
{
const num_args = node.ty.redir.expr.ty.call.args.len;
var i: usize = 1;
while (i <= num_args) : (i += 1) try self.compile(node.ty.redir.expr.ty.call.args[num_args - i]);
try self.pushInstruction(.sprint);
try self.pushOffset(node.offset);
try self.pushByte(num_args);
} else {
try self.compile(node.ty.redir.expr.*);
}
try self.compile(node.ty.redir.file.*);
try self.pushInstruction(.redir);
try self.pushOffset(node.offset);
try self.pushByte(@boolToInt(node.ty.redir.clobber));
}
// Helpers
fn head(self: Compiler) *std.ArrayList(u8) {
std.debug.assert(self.ctx_stack.items.len != 0);
return &self.ctx_stack.items[self.ctx_stack.items.len - 1];
}
fn pushContext(self: *Compiler) !void {
try self.ctx_stack.append(std.ArrayList(u8).init(self.allocator));
self.bytecode = self.head();
}
fn popContext(self: *Compiler) []const u8 {
std.debug.assert(self.ctx_stack.items.len > 1);
var popped_bytecode = self.ctx_stack.pop();
self.bytecode = self.head();
return popped_bytecode.toOwnedSlice();
}
fn pushInstruction(self: *Compiler, opcode: Opcode) !void {
try self.bytecode.append(@enumToInt(opcode));
}
fn pushOffset(self: *Compiler, offset: u16) !void {
try self.bytecode.appendSlice(std.mem.sliceAsBytes(&[1]u16{offset}));
}
fn pushLen(self: *Compiler, len: usize) !void {
try self.bytecode.appendSlice(std.mem.sliceAsBytes(&[1]u16{@intCast(u16, len)}));
}
fn pushSlice(self: *Compiler, slice: []const u8) !void {
try self.bytecode.appendSlice(slice);
}
fn pushEnum(self: *Compiler, v: anytype) !void {
try self.bytecode.append(@enumToInt(v));
}
fn pushByte(self: *Compiler, n: anytype) !void {
try self.bytecode.append(@intCast(u8, n));
}
// Returns index of first byte pushed.
fn pushZeroes(self: *Compiler) !usize {
try self.bytecode.append(0);
try self.bytecode.append(0);
return self.bytecode.items.len - 2;
}
fn updateJumpIndex(self: *Compiler, index: usize) void {
std.debug.assert(index < self.bytecode.items.len);
var jump_index_bytes = std.mem.sliceAsBytes(&[_]u16{@intCast(u16, self.bytecode.items.len)});
self.bytecode.items[index] = jump_index_bytes[0];
self.bytecode.items[index + 1] = jump_index_bytes[1];
}
fn pushJumpUpdates(self: *Compiler) anyerror!void {
var jump_updates_ptr = try self.allocator.create(JumpUpdates);
jump_updates_ptr.* = .{ .prev = self.jump_updates, .updates = std.ArrayList(usize).init(self.allocator) };
self.jump_updates = jump_updates_ptr;
}
fn popJumpUpdates(self: *Compiler) void {
std.debug.assert(self.jump_updates != null);
self.jump_updates = self.jump_updates.?.prev;
}
fn pushCurrentLoopIndex(self: *Compiler) anyerror!void {
var current_loop_start_ptr = try self.allocator.create(Index);
current_loop_start_ptr.* = .{ .index = @intCast(u16, self.bytecode.items.len), .prev = self.current_loop_start };
self.current_loop_start = current_loop_start_ptr;
}
fn popCurrentLoopIndex(self: *Compiler) void {
std.debug.assert(self.current_loop_start != null);
self.current_loop_start = self.current_loop_start.?.prev;
}
// Tests
test "Compiler predefined constant values" {
const Lexer = @import("Lexer.zig");
const allocator = std.testing.allocator;
var arena = std.heap.ArenaAllocator.init(allocator);
defer arena.deinit();
const ctx = Context{ .filename = "inline", .src = "true false nil" };
var lexer = Lexer{
.allocator = arena.allocator(),
.ctx = ctx,
};
var tokens = try lexer.lex();
var parser = Parser{
.allocator = arena.allocator(),
.ctx = ctx,
.tokens = tokens,
};
const program = try parser.parse();
var compiler = try init(arena.allocator(), ctx);
for (program.rules) |n| try compiler.compile(n);
try std.testing.expectEqual(@as(usize, 12), compiler.bytecode.items.len);
try std.testing.expectEqual(Opcode.bool_true, @intToEnum(Opcode, compiler.bytecode.items[0]));
try std.testing.expectEqual(@as(u16, 0), std.mem.bytesAsSlice(u16, compiler.bytecode.items[1..3])[0]);
try std.testing.expectEqual(Opcode.pop, @intToEnum(Opcode, compiler.bytecode.items[3]));
try std.testing.expectEqual(Opcode.bool_false, @intToEnum(Opcode, compiler.bytecode.items[4]));
try std.testing.expectEqual(@as(u16, 5), std.mem.bytesAsSlice(u16, compiler.bytecode.items[5..7])[0]);
try std.testing.expectEqual(Opcode.pop, @intToEnum(Opcode, compiler.bytecode.items[7]));
try std.testing.expectEqual(Opcode.nil, @intToEnum(Opcode, compiler.bytecode.items[8]));
try std.testing.expectEqual(@as(u16, 11), std.mem.bytesAsSlice(u16, compiler.bytecode.items[9..11])[0]);
try std.testing.expectEqual(Opcode.pop, @intToEnum(Opcode, compiler.bytecode.items[11]));
} | src/Compiler.zig |
const std = @import("std");
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
const Tag = std.meta.Tag;
const MultipleChoice2 = union(enum(u32)) {
Unspecified1: i32,
A: f32 = 20,
Unspecified2: void,
B: bool = 40,
Unspecified3: i32,
C: i8 = 60,
Unspecified4: void,
D: void = 1000,
Unspecified5: i32,
};
test "union(enum(u32)) with specified and unspecified tag values" {
comptime try expect(Tag(Tag(MultipleChoice2)) == u32);
try testEnumWithSpecifiedAndUnspecifiedTagValues(MultipleChoice2{ .C = 123 });
comptime try testEnumWithSpecifiedAndUnspecifiedTagValues(MultipleChoice2{ .C = 123 });
}
fn testEnumWithSpecifiedAndUnspecifiedTagValues(x: MultipleChoice2) !void {
try expect(@enumToInt(@as(Tag(MultipleChoice2), x)) == 60);
try expect(1123 == switch (x) {
MultipleChoice2.A => 1,
MultipleChoice2.B => 2,
MultipleChoice2.C => |v| @as(i32, 1000) + v,
MultipleChoice2.D => 4,
MultipleChoice2.Unspecified1 => 5,
MultipleChoice2.Unspecified2 => 6,
MultipleChoice2.Unspecified3 => 7,
MultipleChoice2.Unspecified4 => 8,
MultipleChoice2.Unspecified5 => 9,
});
}
test "switch on union with only 1 field" {
var r: PartialInst = undefined;
r = PartialInst.Compiled;
switch (r) {
PartialInst.Compiled => {
var z: PartialInstWithPayload = undefined;
z = PartialInstWithPayload{ .Compiled = 1234 };
switch (z) {
PartialInstWithPayload.Compiled => |x| {
try expect(x == 1234);
return;
},
}
},
}
unreachable;
}
const PartialInst = union(enum) {
Compiled,
};
const PartialInstWithPayload = union(enum) {
Compiled: i32,
};
test "union with only 1 field casted to its enum type which has enum value specified" {
const Literal = union(enum) {
Number: f64,
Bool: bool,
};
const ExprTag = enum(comptime_int) {
Literal = 33,
};
const Expr = union(ExprTag) {
Literal: Literal,
};
var e = Expr{ .Literal = Literal{ .Bool = true } };
comptime try expect(Tag(ExprTag) == comptime_int);
var t = @as(ExprTag, e);
try expect(t == Expr.Literal);
try expect(@enumToInt(t) == 33);
comptime try expect(@enumToInt(t) == 33);
}
test "@enumToInt works on unions" {
const Bar = union(enum) {
A: bool,
B: u8,
C,
};
const a = Bar{ .A = true };
var b = Bar{ .B = undefined };
var c = Bar.C;
try expect(@enumToInt(a) == 0);
try expect(@enumToInt(b) == 1);
try expect(@enumToInt(c) == 2);
}
const Attribute = union(enum) {
A: bool,
B: u8,
};
fn setAttribute(attr: Attribute) void {
_ = attr;
}
fn Setter(attr: Attribute) type {
return struct {
fn set() void {
setAttribute(attr);
}
};
}
test "comptime union field value equality" {
const a0 = Setter(Attribute{ .A = false });
const a1 = Setter(Attribute{ .A = true });
const a2 = Setter(Attribute{ .A = false });
const b0 = Setter(Attribute{ .B = 5 });
const b1 = Setter(Attribute{ .B = 9 });
const b2 = Setter(Attribute{ .B = 5 });
try expect(a0 == a0);
try expect(a1 == a1);
try expect(a0 == a2);
try expect(b0 == b0);
try expect(b1 == b1);
try expect(b0 == b2);
try expect(a0 != b0);
try expect(a0 != a1);
try expect(b0 != b1);
}
test "return union init with void payload" {
const S = struct {
fn entry() !void {
try expect(func().state == State.one);
}
const Outer = union(enum) {
state: State,
};
const State = union(enum) {
one: void,
two: u32,
};
fn func() Outer {
return Outer{ .state = State{ .one = {} } };
}
};
try S.entry();
comptime try S.entry();
}
test "@unionInit can modify a union type" {
const UnionInitEnum = union(enum) {
Boolean: bool,
Byte: u8,
};
var value: UnionInitEnum = undefined;
value = @unionInit(UnionInitEnum, "Boolean", true);
try expect(value.Boolean == true);
value.Boolean = false;
try expect(value.Boolean == false);
value = @unionInit(UnionInitEnum, "Byte", 2);
try expect(value.Byte == 2);
value.Byte = 3;
try expect(value.Byte == 3);
}
test "@unionInit can modify a pointer value" {
const UnionInitEnum = union(enum) {
Boolean: bool,
Byte: u8,
};
var value: UnionInitEnum = undefined;
var value_ptr = &value;
value_ptr.* = @unionInit(UnionInitEnum, "Boolean", true);
try expect(value.Boolean == true);
value_ptr.* = @unionInit(UnionInitEnum, "Byte", 2);
try expect(value.Byte == 2);
}
test "union no tag with struct member" {
const Struct = struct {};
const Union = union {
s: Struct,
pub fn foo(self: *@This()) void {
_ = self;
}
};
var u = Union{ .s = Struct{} };
u.foo();
}
test "union with comptime_int tag" {
const Union = union(enum(comptime_int)) {
X: u32,
Y: u16,
Z: u8,
};
comptime try expect(Tag(Tag(Union)) == comptime_int);
}
test "extern union doesn't trigger field check at comptime" {
const U = extern union {
x: u32,
y: u8,
};
const x = U{ .x = 0x55AAAA55 };
comptime try expect(x.y == 0x55);
}
test "anonymous union literal syntax" {
const S = struct {
const Number = union {
int: i32,
float: f64,
};
fn doTheTest() !void {
var i: Number = .{ .int = 42 };
var f = makeNumber();
try expect(i.int == 42);
try expect(f.float == 12.34);
}
fn makeNumber() Number {
return .{ .float = 12.34 };
}
};
try S.doTheTest();
comptime try S.doTheTest();
}
test "function call result coerces from tagged union to the tag" {
const S = struct {
const Arch = union(enum) {
One,
Two: usize,
};
const ArchTag = Tag(Arch);
fn doTheTest() !void {
var x: ArchTag = getArch1();
try expect(x == .One);
var y: ArchTag = getArch2();
try expect(y == .Two);
}
pub fn getArch1() Arch {
return .One;
}
pub fn getArch2() Arch {
return .{ .Two = 99 };
}
};
try S.doTheTest();
comptime try S.doTheTest();
}
test "cast from anonymous struct to union" {
const S = struct {
const U = union(enum) {
A: u32,
B: []const u8,
C: void,
};
fn doTheTest() !void {
var y: u32 = 42;
const t0 = .{ .A = 123 };
const t1 = .{ .B = "foo" };
const t2 = .{ .C = {} };
const t3 = .{ .A = y };
const x0: U = t0;
var x1: U = t1;
const x2: U = t2;
var x3: U = t3;
try expect(x0.A == 123);
try expect(std.mem.eql(u8, x1.B, "foo"));
try expect(x2 == .C);
try expect(x3.A == y);
}
};
try S.doTheTest();
comptime try S.doTheTest();
}
test "cast from pointer to anonymous struct to pointer to union" {
const S = struct {
const U = union(enum) {
A: u32,
B: []const u8,
C: void,
};
fn doTheTest() !void {
var y: u32 = 42;
const t0 = &.{ .A = 123 };
const t1 = &.{ .B = "foo" };
const t2 = &.{ .C = {} };
const t3 = &.{ .A = y };
const x0: *const U = t0;
var x1: *const U = t1;
const x2: *const U = t2;
var x3: *const U = t3;
try expect(x0.A == 123);
try expect(std.mem.eql(u8, x1.B, "foo"));
try expect(x2.* == .C);
try expect(x3.A == y);
}
};
try S.doTheTest();
comptime try S.doTheTest();
}
test "switching on non exhaustive union" {
const S = struct {
const E = enum(u8) {
a,
b,
_,
};
const U = union(E) {
a: i32,
b: u32,
};
fn doTheTest() !void {
var a = U{ .a = 2 };
switch (a) {
.a => |val| try expect(val == 2),
.b => unreachable,
}
}
};
try S.doTheTest();
comptime try S.doTheTest();
}
test "containers with single-field enums" {
const S = struct {
const A = union(enum) { f1 };
const B = union(enum) { f1: void };
const C = struct { a: A };
const D = struct { a: B };
fn doTheTest() !void {
var array1 = [1]A{A{ .f1 = {} }};
var array2 = [1]B{B{ .f1 = {} }};
try expect(array1[0] == .f1);
try expect(array2[0] == .f1);
var struct1 = C{ .a = A{ .f1 = {} } };
var struct2 = D{ .a = B{ .f1 = {} } };
try expect(struct1.a == .f1);
try expect(struct2.a == .f1);
}
};
try S.doTheTest();
comptime try S.doTheTest();
}
test "@unionInit on union w/ tag but no fields" {
const S = struct {
const Type = enum(u8) { no_op = 105 };
const Data = union(Type) {
no_op: void,
pub fn decode(buf: []const u8) Data {
_ = buf;
return @unionInit(Data, "no_op", {});
}
};
comptime {
std.debug.assert(@sizeOf(Data) != 0);
}
fn doTheTest() !void {
var data: Data = .{ .no_op = .{} };
_ = data;
var o = Data.decode(&[_]u8{});
try expectEqual(Type.no_op, o);
}
};
try S.doTheTest();
comptime try S.doTheTest();
}
test "union enum type gets a separate scope" {
const S = struct {
const U = union(enum) {
a: u8,
const foo = 1;
};
fn doTheTest() !void {
try expect(!@hasDecl(Tag(U), "foo"));
}
};
try S.doTheTest();
}
test "anytype union field: issue #9233" {
const Quux = union(enum) { bar: anytype };
_ = Quux;
} | test/behavior/union_stage1.zig |
const aoc = @import("../aoc.zig");
const std = @import("std");
const Map = std.AutoHashMap(aoc.Coord, void);
pub fn run(problem: *aoc.Problem) !aoc.Solution {
var image_enhancement_algorithm = problem.line().?;
var map = Map.init(problem.allocator);
defer map.deinit();
var last_coord = aoc.Coord.init(.{0, 0});
while (problem.line()) |line| {
last_coord.col = 0;
for (line) |c| {
if (c == '#') {
try map.putNoClobber(last_coord, {});
}
last_coord.col += 1;
}
last_coord.row += 1;
}
var two_iters: usize = undefined;
const fifty_iters = blk: {
var first_coord = aoc.Coord.init(.{-1, -1});
var out_of_bounds_pixel: u1 = 0;
var iterations: u8 = 0;
while (iterations < 50) : ({
iterations += 1;
first_coord.row -= 1; first_coord.col -= 1;
last_coord.row += 1; last_coord.col += 1;
out_of_bounds_pixel ^= @boolToInt(image_enhancement_algorithm[0] == '#');
}) {
if (iterations == 2) {
two_iters = map.count();
}
var new_map = Map.init(problem.allocator);
var iter = aoc.CoordRangeIterator.init(first_coord, last_coord);
while (iter.next()) |coord| {
var iea_idx: u9 = 0;
var neighbors = coord.neighbors(true);
while (neighbors.next()) |neighbor| {
const pixel =
if (map.contains(neighbor))
1
else if (neighbor.row <= first_coord.row or neighbor.col <= first_coord.col or neighbor.row >= last_coord.row or neighbor.col >= last_coord.col)
out_of_bounds_pixel
else
0
;
iea_idx = (iea_idx << 1) | pixel;
}
if (image_enhancement_algorithm[iea_idx] == '#') {
try new_map.putNoClobber(coord, {});
}
}
map.deinit();
map = new_map;
}
break :blk map.count();
};
return problem.solution(two_iters, fifty_iters);
} | src/main/zig/2021/day20.zig |
pub const Flexcomm = struct {
base: usize,
const Self = @This();
/// Peripheral Select and Flexcomm Interface ID register
pub fn regPselid(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0xff8);
}
pub const PSELID_PERSEL_USART = 0x1;
/// USART Configuration register. Basic USART configuration settings that
/// typically are not changed during operation.
pub fn regUsartCfg(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x000);
}
pub const USART_CFG_ENABLE: u32 = 1 << 0;
pub const USART_CFG_DATALEN_8BIT: u32 = 0x1 << 2;
/// USART Baud Rate Generator register. 16-bit integer baud rate divisor value.
pub fn regUsartBrg(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x020);
}
/// FIFO configuration and enable register.
pub fn regFifoCfg(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0xe00);
}
pub const FIFO_CFG_ENABLETX: u32 = 1 << 0;
pub const FIFO_CFG_ENABLERX: u32 = 1 << 1;
/// FIFO status register.
pub fn regFifoStat(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0xe04);
}
pub const FIFO_STAT_TXNOTFULL: u32 = 1 << 5;
/// FIFO trigger settings for interrupt and DMA request.
pub fn regFifoTrig(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0xe08);
}
/// FIFO write data.
pub fn regFifoWr(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0xe20);
}
pub fn tryWrite(self: Self, data: u8) bool {
if ((self.regFifoStat().* & FIFO_STAT_TXNOTFULL) == 0) {
return false;
}
self.regFifoWr().* = data;
return true;
}
pub fn write(self: Self, data: u8) void {
while (!self.tryWrite(data)) {}
}
pub fn writeSlice(self: Self, data: []const u8) void {
for (data) |b| {
self.write(b);
}
}
}; | examples/drivers/flexcomm.zig |
const std = @import("std");
const testing = std.testing;
// Supported, IANA-registered status codes available
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
pub const Status = struct {
code: u16,
phrase: []const u8,
description: []const u8,
pub fn create(code: u16, phrase: []const u8, desc: []const u8) Status {
return Status{
.code = code,
.phrase = phrase,
.description = desc,
};
}
};
pub const create = Status.create;
// Informational
pub const CONTINUE = create(100, "Continue", "Request received, please continue");
pub const SWITCHING_PROTOCOLS = create(101, "Switching Protocols",
"Switching to new protocol; obey Upgrade header");
pub const PROCESSING = create(102, "Processing", "");
pub const EARLY_HINTS = create(103, "Early Hints", "");
// Success
pub const OK = create(200, "OK", "Request fulfilled, document follows");
pub const CREATED = create(201, "Created", "Document created, URL follows");
pub const ACCEPTED = create(202, "Accepted", "Request accepted, processing continues off-line");
pub const NON_AUTHORITATIVE_INFORMATION = create(203, "Non-Authoritative Information", "Request fulfilled from cache");
pub const NO_CONTENT = create(204, "No Content", "Request fulfilled, nothing follows");
pub const RESET_CONTENT = create(205, "Reset Content", "Clear input form for further input");
pub const PARTIAL_CONTENT = create(206, "Partial Content", "Partial content follows");
pub const MULTI_STATUS = create(207, "Multi-Status", "");
pub const ALREADY_REPORTED = create(208, "Already Reported", "");
pub const IM_USED = create(226, "IM Used", "");
// Redirection
pub const MULTIPLE_CHOICES = create(300, "Multiple Choices", "Object has several resources -- see URI list");
pub const MOVED_PERMANENTLY = create(301, "Moved Permanently", "Object moved permanently -- see URI list");
pub const FOUND = create(302, "Found", "Object moved temporarily -- see URI list");
pub const SEE_OTHER = create(303, "See Other", "Object moved -- see Method and URL list");
pub const NOT_MODIFIED = create(304, "Not Modified", "Document has not changed since given time");
pub const USE_PROXY = create(305, "Use Proxy", "You must use proxy specified in Location to access this resource");
pub const TEMPORARY_REDIRECT = create(307, "Temporary Redirect", "Object moved temporarily -- see URI list");
pub const PERMANENT_REDIRECT = create(308, "Permanent Redirect", "Object moved permanently -- see URI list");
// Client error
pub const BAD_REQUEST = create(400, "Bad Request", "Bad request syntax or unsupported method");
pub const UNAUTHORIZED = create(401, "Unauthorized", "No permission -- see authorization schemes");
pub const PAYMENT_REQUIRED = create(402, "Payment Required", "No payment -- see charging schemes");
pub const FORBIDDEN = create(403, "Forbidden", "Request forbidden -- authorization will not help");
pub const NOT_FOUND = create(404, "Not Found", "Nothing matches the given URI");
pub const METHOD_NOT_ALLOWED = create(405, "Method Not Allowed", "Specified method is invalid for this resource");
pub const NOT_ACCEPTABLE = create(406, "Not Acceptable", "URI not available in preferred format");
pub const PROXY_AUTHENTICATION_REQUIRED = create(407, "Proxy Authentication Required", "You must authenticate with this proxy before proceeding");
pub const REQUEST_TIMEOUT = create(408, "Request Timeout", "Request timed out; try again later");
pub const CONFLICT = create(409, "Conflict", "Request conflict");
pub const GONE = create(410, "Gone", "URI no longer exists and has been permanently removed");
pub const LENGTH_REQUIRED = create(411, "Length Required", "Client must specify Content-Length");
pub const PRECONDITION_FAILED = create(412, "Precondition Failed", "Precondition in headers is false");
pub const REQUEST_ENTITY_TOO_LARGE = create(413, "Request Entity Too Large", "Entity is too large");
pub const REQUEST_URI_TOO_LONG = create(414, "Request-URI Too Long", "URI is too long");
pub const UNSUPPORTED_MEDIA_TYPE = create(415, "Unsupported Media Type", "Entity body in unsupported format");
pub const REQUESTED_RANGE_NOT_SATISFIABLE = create(416, "Requested Range Not Satisfiable", "Cannot satisfy request range");
pub const EXPECTATION_FAILED = create(417, "Expectation Failed", "Expect condition could not be satisfied");
pub const MISDIRECTED_REQUEST = create(421, "Misdirected Request", "Server is not able to produce a response");
pub const UNPROCESSABLE_ENTITY = create(422, "Unprocessable Entity", "");
pub const LOCKED = create(423, "Locked", "");
pub const FAILED_DEPENDENCY = create(424, "Failed Dependency", "");
pub const TOO_EARLY = create(425, "Too Early", "");
pub const UPGRADE_REQUIRED = create(426, "Upgrade Required", "");
pub const PRECONDITION_REQUIRED = create(428, "Precondition Required", "The origin server requires the request to be conditional");
pub const TOO_MANY_REQUESTS = create(429, "Too Many Requests", "The user has sent too many requests in a given amount of time (\"rate limiting\")");
pub const REQUEST_HEADER_FIELDS_TOO_LARGE = create(431, "Request Header Fields Too Large", "The server is unwilling to process the request because its header fields are too large");
pub const UNAVAILABLE_FOR_LEGAL_REASONS = create(451, "Unavailable For Legal Reasons", "The server is denying access to the resource as a consequence of a legal demand");
// server errors
pub const INTERNAL_SERVER_ERROR = create(500, "Internal Server Error", "Server got itself in trouble");
pub const NOT_IMPLEMENTED = create(501, "Not Implemented", "Server does not support this operation");
pub const BAD_GATEWAY = create(502, "Bad Gateway", "Invalid responses from another server/proxy");
pub const SERVICE_UNAVAILABLE = create(503, "Service Unavailable", "The server cannot process the request due to a high load");
pub const GATEWAY_TIMEOUT = create(504, "Gateway Timeout", "The gateway server did not receive a timely response");
pub const HTTP_VERSION_NOT_SUPPORTED = create(505, "HTTP Version Not Supported", "Cannot fulfill request");
pub const VARIANT_ALSO_NEGOTIATES = create(506, "Variant Also Negotiates", "");
pub const INSUFFICIENT_STORAGE = create(507, "Insufficient Storage", "");
pub const LOOP_DETECTED = create(508, "Loop Detected", "");
pub const NOT_EXTENDED = create(510, "Not Extended", "");
pub const NETWORK_AUTHENTICATION_REQUIRED = create(511, "Network Authentication Required", "The client needs to authenticate to gain network access");
/// Lookup the status for the given code
pub fn get(status_code: u16) ?Status {
return switch (status_code) {
100 => CONTINUE,
101 => SWITCHING_PROTOCOLS,
102 => PROCESSING,
103 => EARLY_HINTS,
200 => OK,
201 => CREATED,
202 => ACCEPTED,
203 => NON_AUTHORITATIVE_INFORMATION,
204 => NO_CONTENT,
205 => RESET_CONTENT,
206 => PARTIAL_CONTENT,
207 => MULTI_STATUS,
208 => ALREADY_REPORTED,
226 => IM_USED,
300 => MULTIPLE_CHOICES,
301 => MOVED_PERMANENTLY,
302 => FOUND,
303 => SEE_OTHER,
304 => NOT_MODIFIED,
305 => USE_PROXY,
307 => TEMPORARY_REDIRECT,
308 => PERMANENT_REDIRECT,
400 => BAD_REQUEST,
401 => UNAUTHORIZED,
402 => PAYMENT_REQUIRED,
403 => FORBIDDEN,
404 => NOT_FOUND,
405 => METHOD_NOT_ALLOWED,
406 => NOT_ACCEPTABLE,
407 => PROXY_AUTHENTICATION_REQUIRED,
408 => REQUEST_TIMEOUT,
409 => CONFLICT,
410 => GONE,
411 => LENGTH_REQUIRED,
412 => PRECONDITION_FAILED,
413 => REQUEST_ENTITY_TOO_LARGE,
414 => REQUEST_URI_TOO_LONG,
415 => UNSUPPORTED_MEDIA_TYPE,
416 => REQUESTED_RANGE_NOT_SATISFIABLE,
417 => EXPECTATION_FAILED,
422 => UNPROCESSABLE_ENTITY,
423 => LOCKED,
424 => FAILED_DEPENDENCY,
425 => TOO_EARLY,
426 => UPGRADE_REQUIRED,
428 => PRECONDITION_REQUIRED,
429 => TOO_MANY_REQUESTS,
431 => REQUEST_HEADER_FIELDS_TOO_LARGE,
500 => INTERNAL_SERVER_ERROR,
501 => NOT_IMPLEMENTED,
502 => BAD_GATEWAY,
503 => SERVICE_UNAVAILABLE,
504 => GATEWAY_TIMEOUT,
505 => HTTP_VERSION_NOT_SUPPORTED,
506 => VARIANT_ALSO_NEGOTIATES,
507 => INSUFFICIENT_STORAGE,
508 => LOOP_DETECTED,
510 => NOT_EXTENDED,
511 => NETWORK_AUTHENTICATION_REQUIRED,
else => null,
};
}
/// Lookup the status for the given code or create one with the given phrase
pub fn getOrCreate(status_code: u16, phrase: []const u8) Status {
return get(status_code) orelse create(status_code, phrase, "");
}
test "Status.create" {
const status = create(200, "OK", "Request fulfilled, document follows");
testing.expectEqual(status.code, OK.code);
testing.expectEqualSlices(u8, status.phrase, OK.phrase);
testing.expectEqualSlices(u8, status.description, OK.description);
}
test "Status.get" {
testing.expectEqual(get(200).?, OK);
testing.expectEqual(get(600), null);
const status = getOrCreate(600, "Unknown");
testing.expectEqual(status.code, 600);
testing.expectEqualSlices(u8, status.phrase, "Unknown");
} | src/status.zig |
const fmath = @import("index.zig");
pub fn sqrt(x: var) -> @typeOf(x) {
const T = @typeOf(x);
switch (T) {
f32 => @inlineCall(sqrt32, x),
f64 => @inlineCall(sqrt64, x),
else => @compileError("sqrt not implemented for " ++ @typeName(T)),
}
}
fn sqrt32(x: f32) -> f32 {
const tiny: f32 = 1.0e-30;
const sign: i32 = @bitCast(i32, u32(0x80000000));
var ix: i32 = @bitCast(i32, x);
if ((ix & 0x7F800000) == 0x7F800000) {
return x * x + x; // sqrt(nan) = nan, sqrt(+inf) = +inf, sqrt(-inf) = snan
}
// zero
if (ix <= 0) {
if (ix & ~sign == 0) {
return x; // sqrt (+-0) = +-0
}
if (ix < 0) {
return (x - x) / (x - x); // sqrt(-ve) = snan
}
}
// normalize
var m = ix >> 23;
if (m == 0) {
// subnormal
var i: i32 = 0;
while (ix & 0x00800000 == 0) : (i += 1) {
ix <<= 1
}
m -= i - 1;
}
m -= 127; // unbias exponent
ix = (ix & 0x007FFFFF) | 0x00800000;
if (m & 1 != 0) { // odd m, double x to even
ix += ix;
}
m >>= 1; // m = [m / 2]
// sqrt(x) bit by bit
ix += ix;
var q: i32 = 0; // q = sqrt(x)
var s: i32 = 0;
var r: i32 = 0x01000000; // r = moving bit right -> left
while (r != 0) {
const t = s + r;
if (t <= ix) {
s = t + r;
ix -= t;
q += r;
}
ix += ix;
r >>= 1;
}
// floating add to find rounding direction
if (ix != 0) {
var z = 1.0 - tiny; // inexact
if (z >= 1.0) {
z = 1.0 + tiny;
if (z > 1.0) {
q += 2;
} else {
if (q & 1 != 0) {
q += 1;
}
}
}
}
ix = (q >> 1) + 0x3f000000;
ix += m << 23;
@bitCast(f32, ix)
}
// NOTE: The original code is full of implicit signed -> unsigned assumptions and u32 wraparound
// behaviour. Most intermediate i32 values are changed to u32 where appropriate but there are
// potentially some edge cases remaining that are not handled in the same way.
fn sqrt64(x: f64) -> f64 {
const tiny: f64 = 1.0e-300;
const sign: u32 = 0x80000000;
const u = @bitCast(u64, x);
var ix0 = u32(u >> 32);
var ix1 = u32(u & 0xFFFFFFFF);
// sqrt(nan) = nan, sqrt(+inf) = +inf, sqrt(-inf) = nan
if (ix0 & 0x7FF00000 == 0x7FF00000) {
return x * x + x;
}
// sqrt(+-0) = +-0
if ((ix0 & ~sign) | ix0 == 0) {
return x;
}
// sqrt(-ve) = snan
if (ix0 & sign != 0) {
return (x - x) / (x - x);
}
// normalize x
var m = i32(ix0 >> 20);
if (m == 0) {
// subnormal
while (ix0 == 0) {
m -= 21;
ix0 |= ix1 >> 11;
ix1 <<= 21;
}
// subnormal
var i: u32 = 0;
while (ix0 & 0x00100000 == 0) : (i += 1) {
ix0 <<= 1
}
m -= i32(i) - 1;
ix0 |= ix1 >> (32 - i);
ix1 <<= i;
}
// unbias exponent
m -= 1023;
ix0 = (ix0 & 0x000FFFFF) | 0x00100000;
if (m & 1 != 0) {
ix0 += ix0 + (ix1 >> 31);
ix1 = ix1 +% ix1;
}
m >>= 1;
// sqrt(x) bit by bit
ix0 += ix0 + (ix1 >> 31);
ix1 = ix1 +% ix1;
var q: u32 = 0;
var q1: u32 = 0;
var s0: u32 = 0;
var s1: u32 = 0;
var r: u32 = 0x00200000;
var t: u32 = undefined;
var t1: u32 = undefined;
while (r != 0) {
t = s0 +% r;
if (t <= ix0) {
s0 = t + r;
ix0 -= t;
q += r;
}
ix0 = ix0 +% ix0 +% (ix1 >> 31);
ix1 = ix1 +% ix1;
r >>= 1;
}
r = sign;
while (r != 0) {
t = s1 +% r;
t = s0;
if (t < ix0 or (t == ix0 and t1 <= ix1)) {
s1 = t1 +% r;
if (t1 & sign == sign and s1 & sign == 0) {
s0 += 1;
}
ix0 -= t;
if (ix1 < t1) {
ix0 -= 1;
}
ix1 = ix1 -% t1;
q1 += r;
}
ix0 = ix0 +% ix0 +% (ix1 >> 31);
ix1 = ix1 +% ix1;
r >>= 1;
}
// rounding direction
if (ix0 | ix1 != 0) {
var z = 1.0 - tiny; // raise inexact
if (z >= 1.0) {
z = 1.0 + tiny;
if (q1 == 0xFFFFFFFF) {
q1 = 0;
q += 1;
} else if (z > 1.0) {
if (q1 == 0xFFFFFFFE) {
q += 1;
}
q1 += 2;
} else {
q1 += q1 & 1;
}
}
}
ix0 = (q >> 1) + 0x3FE00000;
ix1 = q1 >> 1;
if (q & 1 != 0) {
ix1 |= 0x80000000;
}
// NOTE: musl here appears to rely on signed twos-complement wraparound. +% has the same
// behaviour at least.
var iix0 = i32(ix0);
iix0 = iix0 +% (m << 20);
const uz = (u64(iix0) << 32) | ix1;
@bitCast(f64, uz)
}
test "sqrt" {
fmath.assert(sqrt(f32(0.0)) == sqrt32(0.0));
fmath.assert(sqrt(f64(0.0)) == sqrt64(0.0));
}
test "sqrt32" {
const epsilon = 0.000001;
fmath.assert(sqrt32(0.0) == 0.0);
fmath.assert(fmath.approxEq(f32, sqrt32(2.0), 1.414214, epsilon));
fmath.assert(fmath.approxEq(f32, sqrt32(3.6), 1.897367, epsilon));
fmath.assert(sqrt32(4.0) == 2.0);
fmath.assert(fmath.approxEq(f32, sqrt32(7.539840), 2.745877, epsilon));
fmath.assert(fmath.approxEq(f32, sqrt32(19.230934), 4.385309, epsilon));
fmath.assert(sqrt32(64.0) == 8.0);
fmath.assert(fmath.approxEq(f32, sqrt32(64.1), 8.006248, epsilon));
fmath.assert(fmath.approxEq(f32, sqrt32(8942.230469), 94.563370, epsilon));
}
test "sqrt64" {
const epsilon = 0.000001;
fmath.assert(sqrt64(0.0) == 0.0);
fmath.assert(fmath.approxEq(f64, sqrt64(2.0), 1.414214, epsilon));
fmath.assert(fmath.approxEq(f64, sqrt64(3.6), 1.897367, epsilon));
fmath.assert(sqrt64(4.0) == 2.0);
fmath.assert(fmath.approxEq(f64, sqrt64(7.539840), 2.745877, epsilon));
fmath.assert(fmath.approxEq(f64, sqrt64(19.230934), 4.385309, epsilon));
fmath.assert(sqrt64(64.0) == 8.0);
fmath.assert(fmath.approxEq(f64, sqrt64(64.1), 8.006248, epsilon));
fmath.assert(fmath.approxEq(f64, sqrt64(8942.230469), 94.563367, epsilon));
} | src/sqrt.zig |
const std = @import("std");
const vk = @import("../../vk.zig");
const vkctxt = @import("../../vulkan_wrapper/vulkan_context.zig");
const printError = @import("../../application/print_error.zig").printError;
const RGPass = @import("render_graph_pass.zig").RGPass;
const PassList = std.ArrayList(*RGPass);
const RGResource = @import("render_graph_resource.zig").RGResource;
const ResourceList = std.ArrayList(*RGResource);
const SyncPass = @import("passes/sync_pass.zig").SyncPass;
const Swapchain = @import("resources/swapchain.zig").Swapchain;
const Texture = @import("resources/texture.zig").Texture;
const ViewportTexture = @import("resources/viewport_texture.zig").ViewportTexture;
pub var global_render_graph: RenderGraph = undefined;
pub const RenderGraph = struct {
pub const ResourceChangeFn = struct {
res: *RGResource,
change_fn: fn (res: *RGResource) void,
};
allocator: std.mem.Allocator,
final_swapchain: Swapchain,
needs_rebuilding: bool,
command_pool: vk.CommandPool,
compute_command_pool: vk.CommandPool,
command_buffers: []vk.CommandBuffer,
frame_index: u32,
image_index: u32,
in_flight: u32,
passes: PassList,
resources: ResourceList,
culled_passes: PassList,
culled_resources: ResourceList,
sorted_passes: PassList,
sync_passes: std.ArrayList(*SyncPass),
resource_changes: std.ArrayList(ResourceChangeFn),
textures: std.ArrayList(*Texture),
viewport_textures: std.ArrayList(*ViewportTexture),
pub fn init(self: *RenderGraph, allocator: std.mem.Allocator) void {
self.allocator = allocator;
self.passes = PassList.init(allocator);
self.resources = ResourceList.init(allocator);
self.culled_passes = PassList.init(allocator);
self.culled_resources = ResourceList.init(allocator);
self.sorted_passes = PassList.init(allocator);
self.sync_passes = std.ArrayList(*SyncPass).init(allocator);
self.resource_changes = std.ArrayList(ResourceChangeFn).init(allocator);
self.textures = std.ArrayList(*Texture).init(allocator);
self.viewport_textures = std.ArrayList(*ViewportTexture).init(allocator);
self.frame_index = 0;
self.image_index = 0;
self.needs_rebuilding = false;
}
pub fn initVulkan(self: *RenderGraph, in_flight: u32) void {
self.in_flight = in_flight;
var pool_info: vk.CommandPoolCreateInfo = .{
.queue_family_index = vkctxt.vkc.family_indices.graphics_family,
.flags = .{
.reset_command_buffer_bit = true,
},
};
self.command_pool = vkctxt.vkd.createCommandPool(vkctxt.vkc.device, pool_info, null) catch |err| {
vkctxt.printVulkanError("Can't create command pool for render graph", err, vkctxt.vkc.allocator);
return;
};
pool_info.queue_family_index = vkctxt.vkc.family_indices.compute_family;
self.compute_command_pool = vkctxt.vkd.createCommandPool(vkctxt.vkc.device, pool_info, null) catch |err| {
vkctxt.printVulkanError("Can't create compute command pool for render graph", err, vkctxt.vkc.allocator);
return;
};
const command_buffer_info: vk.CommandBufferAllocateInfo = .{
.level = .primary,
.command_pool = self.command_pool,
.command_buffer_count = self.in_flight,
};
self.command_buffers = self.allocator.alloc(vk.CommandBuffer, self.in_flight) catch unreachable;
vkctxt.vkd.allocateCommandBuffers(vkctxt.vkc.device, command_buffer_info, self.command_buffers.ptr) catch |err| {
vkctxt.printVulkanError("Can't allocate primary command buffers", err, vkctxt.vkc.allocator);
};
}
pub fn deinitCommandBuffers(self: *RenderGraph) void {
vkctxt.vkd.deviceWaitIdle(vkctxt.vkc.device) catch |err| {
vkctxt.printVulkanError("Can't wait for device idle while destruction of command buffers", err, self.allocator);
};
vkctxt.vkd.freeCommandBuffers(vkctxt.vkc.device, self.command_pool, self.in_flight, self.command_buffers.ptr);
vkctxt.vkd.destroyCommandPool(vkctxt.vkc.device, self.command_pool, null);
}
pub fn deinit(self: *RenderGraph) void {
self.passes.deinit();
self.resources.deinit();
self.culled_passes.deinit();
self.culled_resources.deinit();
self.sorted_passes.deinit();
self.sync_passes.deinit();
self.allocator.free(self.command_buffers);
}
pub fn addTexture(self: *RenderGraph, tex: *Texture) void {
self.textures.append(tex) catch unreachable;
self.resources.append(&tex.rg_resource) catch unreachable;
}
pub fn addViewportTexture(self: *RenderGraph, tex: *ViewportTexture) void {
self.viewport_textures.append(tex) catch unreachable;
self.resources.append(&tex.rg_resource) catch unreachable;
}
pub fn removeTexture(self: *RenderGraph, tex: *Texture) void {
_ = self;
_ = tex;
}
pub fn changeResourceBetweenFrames(self: *RenderGraph, res: *RGResource, change_fn: fn (res: *RGResource) void) void {
const fn_cxt: ResourceChangeFn = .{
.res = res,
.change_fn = change_fn,
};
self.resource_changes.append(fn_cxt) catch unreachable;
}
pub fn executeResourceChanges(self: *RenderGraph) void {
if (self.resource_changes.items.len == 0)
return;
vkctxt.vkd.deviceWaitIdle(vkctxt.vkc.device) catch |err| {
vkctxt.printVulkanError("Can't wait for device idle in order to change resources", err, vkctxt.vkc.allocator);
return;
};
for (self.resource_changes.items) |ctx|
ctx.change_fn(ctx.res);
for (self.resource_changes.items) |ctx|
for (ctx.res.on_change_callbacks.items) |cb|
cb.callback(cb.pass);
self.resource_changes.clearRetainingCapacity();
}
pub fn build(self: *RenderGraph) void {
self.cull();
updateSyncPasses(self.culled_passes, self.culled_resources, &self.sync_passes);
self.topology_sort();
self.needs_rebuilding = false;
}
fn cull(self: *RenderGraph) void {
self.culled_passes.clearRetainingCapacity();
self.culled_resources.clearRetainingCapacity();
var queue_passes: std.ArrayList(*RGPass) = std.ArrayList(*RGPass).init(self.allocator);
defer queue_passes.deinit();
var queue_resources: std.ArrayList(*RGResource) = std.ArrayList(*RGResource).init(self.allocator);
defer queue_resources.deinit();
var visited: std.AutoHashMap(*RGPass, bool) = std.AutoHashMap(*RGPass, bool).init(self.allocator);
defer visited.deinit();
queue_resources.append(&self.final_swapchain.rg_resource) catch unreachable;
while (queue_resources.items.len > 0 or queue_passes.items.len > 0) {
if (queue_resources.items.len > 0) {
const res: *RGResource = queue_resources.pop();
for (res.writers.items) |w| {
if (visited.get(w) != null) {
continue;
}
queue_passes.append(w) catch unreachable;
self.culled_passes.append(w) catch unreachable;
visited.put(w, true) catch unreachable;
}
continue;
}
const pass: *RGPass = queue_passes.pop();
for (pass.reads_from.items) |r| {
queue_resources.append(r) catch unreachable;
self.culled_resources.append(r) catch unreachable;
}
}
}
fn updateSyncPasses(passes: PassList, resources: ResourceList, sync_passes: *std.ArrayList(*SyncPass)) void {
for (passes.items) |pass| {
const is_culled: bool = !(for (resources.items) |res| {
if (res == &pass.sync_point.rg_resource) break true;
} else false);
if (is_culled)
continue;
const sync_pass: ?*SyncPass = for (sync_passes.items) |sp| {
if (&sp.rg_pass == pass)
break sp;
} else null;
if (sync_pass == null)
continue;
var barrier_start: u32 = vk.PipelineStageFlags.toInt(.{ .top_of_pipe_bit = true });
var barrier_end: u32 = vk.PipelineStageFlags.toInt(.{ .bottom_of_pipe_bit = true });
for (sync_pass.?.input_sync_point.rg_resource.writers.items) |synced_pass|
barrier_end = @maximum(barrier_end, vk.PipelineStageFlags.toInt(synced_pass.pipeline_end));
for (sync_pass.?.output_sync_point.rg_resource.readers.items) |synced_pass|
barrier_end = @minimum(barrier_end, vk.PipelineStageFlags.toInt(synced_pass.pipeline_start));
sync_pass.?.rg_pass.pipeline_start = vk.PipelineStageFlags.fromInt(barrier_start);
sync_pass.?.rg_pass.pipeline_end = vk.PipelineStageFlags.fromInt(barrier_end);
}
}
// Uses culled lists
fn topology_sort(self: *RenderGraph) void {
self.sorted_passes.clearRetainingCapacity();
var unready_passes: std.AutoArrayHashMap(*RGPass, usize) = std.AutoArrayHashMap(*RGPass, usize).init(self.allocator);
defer unready_passes.deinit();
unready_passes.ensureTotalCapacity(self.culled_passes.items.len) catch unreachable;
for (self.culled_passes.items) |p| {
var passes_before_count: usize = 0;
for (p.reads_from.items) |r|
passes_before_count += r.writers.items.len;
unready_passes.putAssumeCapacity(p, passes_before_count);
}
while (unready_passes.count() > 0) {
var it = unready_passes.iterator();
const pass: *RGPass = while (it.next()) |kv| {
if (kv.value_ptr.* == 0) {
break kv.key_ptr.*;
}
} else {
printError("Render Graph", "Can't build graph: Cycle in graph");
return;
};
self.sorted_passes.append(pass) catch unreachable;
_ = unready_passes.swapRemove(pass);
for (pass.writes_to.items) |res| {
for (res.readers.items) |r| {
unready_passes.getPtr(r).?.* -= 1;
}
}
}
}
pub fn render(self: *RenderGraph, command_buffer: vk.CommandBuffer) void {
for (self.sorted_passes.items) |rp|
rp.renderFn(rp, command_buffer, self.frame_index);
}
pub fn beginSingleTimeCommands(command_buffer: vk.CommandBuffer) void {
const begin_info: vk.CommandBufferBeginInfo = .{
.flags = .{
.one_time_submit_bit = true,
},
.p_inheritance_info = undefined,
};
vkctxt.vkd.beginCommandBuffer(command_buffer, begin_info) catch |err| {
vkctxt.printVulkanError("Can't begin command buffer", err, vkctxt.vkc.allocator);
};
}
pub fn endSingleTimeCommands(command_buffer: vk.CommandBuffer) void {
vkctxt.vkd.endCommandBuffer(command_buffer) catch |err| {
vkctxt.printVulkanError("Can't end command buffer", err, vkctxt.vkc.allocator);
return;
};
}
// Pls don't use, created for special cases
pub fn allocateCommandBuffer(self: *RenderGraph) vk.CommandBuffer {
const alloc_info: vk.CommandBufferAllocateInfo = .{
.level = .primary,
.command_pool = self.command_pool,
.command_buffer_count = 1,
};
var command_buffer: vk.CommandBuffer = undefined;
vkctxt.vkd.allocateCommandBuffers(vkctxt.vkc.device, alloc_info, @ptrCast([*]vk.CommandBuffer, &command_buffer)) catch |err| {
vkctxt.printVulkanError("Can't allocate command buffer", err, vkctxt.vkc.allocator);
};
return command_buffer;
}
// Pls don't use, created for special cases
pub fn allocateComputeCommandBuffer(self: *RenderGraph) vk.CommandBuffer {
const alloc_info: vk.CommandBufferAllocateInfo = .{
.level = .primary,
.command_pool = self.compute_command_pool,
.command_buffer_count = 1,
};
var command_buffer: vk.CommandBuffer = undefined;
vkctxt.vkd.allocateCommandBuffers(vkctxt.vkc.device, alloc_info, @ptrCast([*]vk.CommandBuffer, &command_buffer)) catch |err| {
vkctxt.printVulkanError("Can't allocate command buffer", err, vkctxt.vkc.allocator);
};
return command_buffer;
}
// Pls don't use, created for special cases
pub fn submitCommandBuffer(self: *RenderGraph, command_buffer: vk.CommandBuffer) void {
const submit_info: vk.SubmitInfo = .{
.command_buffer_count = 1,
.p_command_buffers = @ptrCast([*]const vk.CommandBuffer, &command_buffer),
.wait_semaphore_count = 0,
.p_wait_semaphores = undefined,
.p_wait_dst_stage_mask = undefined,
.signal_semaphore_count = 0,
.p_signal_semaphores = undefined,
};
vkctxt.vkd.queueSubmit(vkctxt.vkc.graphics_queue, 1, @ptrCast([*]const vk.SubmitInfo, &submit_info), .null_handle) catch |err| {
vkctxt.printVulkanError("Can't submit queue", err, vkctxt.vkc.allocator);
};
vkctxt.vkd.queueWaitIdle(vkctxt.vkc.graphics_queue) catch |err| {
vkctxt.printVulkanError("Can't wait for queue", err, vkctxt.vkc.allocator);
};
vkctxt.vkd.freeCommandBuffers(vkctxt.vkc.device, self.command_pool, 1, @ptrCast([*]const vk.CommandBuffer, &command_buffer));
}
pub fn initPasses(self: *RenderGraph) void {
for (self.passes.items) |pass|
pass.initFn(pass);
self.build();
}
}; | src/renderer/render_graph/render_graph.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const panic = std.debug.panic;
const vk = @import("vulkan");
const VK_API_VERSION_1_2 = vk.makeApiVersion(0, 1, 2, 0);
pub const AppVersion = vk.makeApiVersion;
const glfw = @import("glfw");
const saturn_name = "Saturn Engine";
const saturn_version = vk.makeApiVersion(0, 0, 0, 0);
pub const Instance = struct {
const Self = @This();
allocator: *Allocator,
handle: vk.Instance,
dispatch: InstanceDispatch,
debug_callback: DebugCallback,
pdevices: []vk.PhysicalDevice,
pub fn init(
allocator: *Allocator,
app_name: [*:0]const u8,
app_version: u32,
) !Self {
const vk_proc = @ptrCast(fn (instance: vk.Instance, procname: [*:0]const u8) vk.PfnVoidFunction, glfw.getInstanceProcAddress);
var base_dispatch = try BaseDispatch.load(vk_proc);
const app_info = vk.ApplicationInfo{
.p_application_name = app_name,
.application_version = app_version,
.p_engine_name = saturn_name,
.engine_version = saturn_version,
.api_version = VK_API_VERSION_1_2,
};
const glfw_exts = try glfw.getRequiredInstanceExtensions();
var extensions = std.ArrayList([*:0]const u8).init(allocator);
defer extensions.deinit();
for (glfw_exts) |extension| {
try extensions.append(extension);
}
var layers = std.ArrayList([*:0]const u8).init(allocator);
defer layers.deinit();
//Validation
try extensions.append(vk.extension_info.ext_debug_utils.name);
try extensions.append(vk.extension_info.ext_debug_report.name);
try layers.append("VK_LAYER_KHRONOS_validation");
var handle = try base_dispatch.createInstance(.{
.flags = .{},
.p_application_info = &app_info,
.enabled_layer_count = @intCast(u32, layers.items.len),
.pp_enabled_layer_names = @ptrCast([*]const [*:0]const u8, layers.items),
.enabled_extension_count = @intCast(u32, extensions.items.len),
.pp_enabled_extension_names = @ptrCast([*]const [*:0]const u8, extensions.items),
}, null);
var dispatch = try InstanceDispatch.load(handle, vk_proc);
var debug_callback = try DebugCallback.init(handle, dispatch);
var device_count: u32 = undefined;
_ = try dispatch.enumeratePhysicalDevices(handle, &device_count, null);
var pdevices: []vk.PhysicalDevice = try allocator.alloc(vk.PhysicalDevice, device_count);
_ = try dispatch.enumeratePhysicalDevices(handle, &device_count, pdevices.ptr);
return Self{
.allocator = allocator,
.handle = handle,
.dispatch = dispatch,
.debug_callback = debug_callback,
.pdevices = pdevices,
};
}
pub fn deinit(self: *Self) void {
self.allocator.free(self.pdevices);
self.debug_callback.deinit();
self.dispatch.destroyInstance(self.handle, null);
}
};
const DebugCallback = struct {
const Self = @This();
instance: vk.Instance,
dispatch: InstanceDispatch,
debug_messenger: vk.DebugUtilsMessengerEXT,
fn init(
instance: vk.Instance,
dispatch: InstanceDispatch,
) !Self {
var debug_callback_info = vk.DebugUtilsMessengerCreateInfoEXT{
.flags = .{},
.message_severity = vk.DebugUtilsMessageSeverityFlagsEXT{
//.verbose_bit_ext = true,
//.info_bit_ext = true,
.warning_bit_ext = true,
.error_bit_ext = true,
},
.message_type = vk.DebugUtilsMessageTypeFlagsEXT{
.general_bit_ext = true,
.validation_bit_ext = true,
.performance_bit_ext = true,
},
.pfn_user_callback = debugCallback,
.p_user_data = null,
};
var debug_messenger = try dispatch.createDebugUtilsMessengerEXT(instance, debug_callback_info, null);
return Self{
.instance = instance,
.dispatch = dispatch,
.debug_messenger = debug_messenger,
};
}
fn deinit(self: Self) void {
self.dispatch.destroyDebugUtilsMessengerEXT(self.instance, self.debug_messenger, null);
}
};
fn debugCallback(
message_severity: vk.DebugUtilsMessageSeverityFlagsEXT.IntType,
message_types: vk.DebugUtilsMessageTypeFlagsEXT.IntType,
p_callback_data: *const vk.DebugUtilsMessengerCallbackDataEXT,
p_user_data: *c_void,
) callconv(.C) vk.Bool32 {
//TODO log levels
std.log.warn("{s}", .{p_callback_data.p_message});
return 0;
}
pub const BaseDispatch = vk.BaseWrapper(&.{
.createInstance,
});
pub const InstanceDispatch = vk.InstanceWrapper(&.{
.destroyInstance,
.createDevice,
.destroySurfaceKHR,
.enumeratePhysicalDevices,
.getPhysicalDeviceProperties,
.enumerateDeviceExtensionProperties,
.getPhysicalDeviceSurfaceFormatsKHR,
.getPhysicalDeviceSurfacePresentModesKHR,
.getPhysicalDeviceSurfaceCapabilitiesKHR,
.getPhysicalDeviceQueueFamilyProperties,
.getPhysicalDeviceSurfaceSupportKHR,
.getPhysicalDeviceMemoryProperties,
.getDeviceProcAddr,
.createDebugUtilsMessengerEXT,
.destroyDebugUtilsMessengerEXT,
}); | src/vulkan/instance.zig |
const std = @import("std");
const root = @import("main.zig");
const math = std.math;
const testing = std.testing;
pub const vec4 = Vec4(f32);
pub const vec4_f64 = Vec4(f64);
pub const vec4_i32 = Vec4(i32);
/// A 4 dimensional vector.
pub fn Vec4(comptime T: type) type {
if (@typeInfo(T) != .Float and @typeInfo(T) != .Int) {
@compileError("Vec4 not implemented for " ++ @typeName(T));
}
return packed struct {
x: T,
y: T,
z: T,
w: T,
const Self = @This();
/// Constract vector from given 3 components.
pub fn new(x: T, y: T, z: T, w: T) Self {
return Self{
.x = x,
.y = y,
.z = z,
.w = w,
};
}
/// Set all components to the same given value.
pub fn set(val: T) Self {
return Self.new(val, val, val, val);
}
pub fn zero() Self {
return Self.new(0., 0., 0., 0.);
}
/// Cast a type to another type. Only for integers and floats.
/// It's like builtins: @intCast, @floatCast, @intToFloat, @floatToInt
pub fn cast(self: Self, dest: anytype) Vec4(dest) {
const source_info = @typeInfo(T);
const dest_info = @typeInfo(dest);
if (source_info == .Float and dest_info == .Int) {
const x = @floatToInt(dest, self.x);
const y = @floatToInt(dest, self.y);
const z = @floatToInt(dest, self.z);
const w = @floatToInt(dest, self.w);
return Vec4(dest).new(x, y, z, w);
}
if (source_info == .Int and dest_info == .Float) {
const x = @intToFloat(dest, self.x);
const y = @intToFloat(dest, self.y);
const z = @intToFloat(dest, self.z);
const w = @intToFloat(dest, self.w);
return Vec4(dest).new(x, y, z, w);
}
return switch (dest_info) {
.Float => {
const x = @floatCast(dest, self.x);
const y = @floatCast(dest, self.y);
const z = @floatCast(dest, self.z);
const w = @floatCast(dest, self.w);
return Vec4(dest).new(x, y, z, w);
},
.Int => {
const x = @intCast(dest, self.x);
const y = @intCast(dest, self.y);
const z = @intCast(dest, self.z);
const w = @intCast(dest, self.w);
return Vec4(dest).new(x, y, z, w);
},
else => panic(
"Error, given type should be integers or float.\n",
.{},
),
};
}
/// Construct new vector from slice.
pub fn from_slice(slice: []const T) Self {
return Self.new(slice[0], slice[1], slice[2], slice[3]);
}
/// Transform vector to array.
pub fn to_array(self: Self) [4]T {
return .{ self.x, self.y, self.z, self.w };
}
/// Compute the length (magnitude) of given vector |a|.
pub fn length(self: Self) T {
return math.sqrt((self.x * self.x) + (self.y * self.y) + (self.z * self.z) + (self.w * self.w));
}
/// Construct new normalized vector from a given vector.
pub fn norm(self: Self) Self {
var l = length(self);
return Self.new(self.x / l, self.y / l, self.z / l, self.w / l);
}
pub fn is_eq(left: Self, right: Self) bool {
return left.x == right.x and left.y == right.y and left.z == right.z and left.w == right.w;
}
/// Substraction between two given vector.
pub fn sub(left: Self, right: Self) Self {
return Self.new(left.x - right.x, left.y - right.y, left.z - right.z, left.w - right.w);
}
/// Addition betwen two given vector.
pub fn add(left: Self, right: Self) Self {
return Self.new(left.x + right.x, left.y + right.y, left.z + right.z, left.w + right.w);
}
/// Multiply each components by the given scalar.
pub fn scale(v: Self, scalar: T) Self {
return Self.new(v.x * scalar, v.y * scalar, v.z * scalar, v.w * scalar);
}
/// Return the dot product between two given vector.
pub fn dot(left: Self, right: Self) T {
return (left.x * right.x) + (left.y * right.y) + (left.z * right.z) + (left.w * right.w);
}
/// Lerp between two vectors.
pub fn lerp(left: Self, right: Self, t: T) Self {
const x = root.lerp(T, left.x, right.x, t);
const y = root.lerp(T, left.y, right.y, t);
const z = root.lerp(T, left.z, right.z, t);
const w = root.lerp(T, left.w, right.w, t);
return Self.new(x, y, z, w);
}
/// Construct a new vector from the min components between two vectors.
pub fn min(left: Self, right: Self) Self {
return Self.new(
math.min(left.x, right.x),
math.min(left.y, right.y),
math.min(left.z, right.z),
math.min(left.w, right.w),
);
}
/// Construct a new vector from the max components between two vectors.
pub fn max(left: Self, right: Self) Self {
return Self.new(
math.max(left.x, right.x),
math.max(left.y, right.y),
math.max(left.z, right.z),
math.max(left.w, right.w),
);
}
};
}
test "zalgebra.Vec4.init" {
var _vec_0 = vec4.new(1.5, 2.6, 3.7, 4.7);
testing.expectEqual(_vec_0.x, 1.5);
testing.expectEqual(_vec_0.y, 2.6);
testing.expectEqual(_vec_0.z, 3.7);
testing.expectEqual(_vec_0.w, 4.7);
}
test "zalgebra.Vec4.is_eq" {
var _vec_0 = vec4.new(1., 2., 3., 4.);
var _vec_1 = vec4.new(1., 2., 3., 4.);
var _vec_2 = vec4.new(1., 2., 3., 5.);
testing.expectEqual(vec4.is_eq(_vec_0, _vec_1), true);
testing.expectEqual(vec4.is_eq(_vec_0, _vec_2), false);
}
test "zalgebra.Vec4.set" {
var _vec_0 = vec4.new(2.5, 2.5, 2.5, 2.5);
var _vec_1 = vec4.set(2.5);
testing.expectEqual(vec4.is_eq(_vec_0, _vec_1), true);
}
test "zalgebra.Vec2.to_array" {
const _vec_0 = vec4.new(0, 1, 0, 1).to_array();
const _vec_1 = [_]f32{ 0, 1, 0, 1 };
testing.expectEqual(std.mem.eql(f32, &_vec_0, &_vec_1), true);
}
test "zalgebra.Vec4.length" {
var _vec_0 = vec4.new(1.5, 2.6, 3.7, 4.7);
testing.expectEqual(_vec_0.length(), 6.69253301);
}
test "zalgebra.Vec4.normalize" {
var _vec_0 = vec4.new(1.5, 2.6, 3.7, 4.0);
testing.expectEqual(vec4.is_eq(_vec_0.norm(), vec4.new(0.241121411, 0.417943745, 0.594766139, 0.642990410)), true);
}
test "zalgebra.Vec4.sub" {
var _vec_0 = vec4.new(1., 2., 3., 6.);
var _vec_1 = vec4.new(2., 2., 3., 5.);
testing.expectEqual(vec4.is_eq(vec4.sub(_vec_0, _vec_1), vec4.new(-1., 0., 0., 1.)), true);
}
test "zalgebra.Vec4.add" {
var _vec_0 = vec4.new(1., 2., 3., 5.);
var _vec_1 = vec4.new(2., 2., 3., 6.);
testing.expectEqual(vec4.is_eq(vec4.add(_vec_0, _vec_1), vec4.new(3., 4., 6., 11.)), true);
}
test "zalgebra.Vec4.scale" {
var _vec_0 = vec4.new(1., 2., 3., 4.);
testing.expectEqual(vec4.is_eq(vec4.scale(_vec_0, 5.), vec4.new(5., 10., 15., 20.)), true);
}
test "zalgebra.Vec4.dot" {
var _vec_0 = vec4.new(1.5, 2.6, 3.7, 5.);
var _vec_1 = vec4.new(2.5, 3.45, 1.0, 1.);
testing.expectEqual(vec4.dot(_vec_0, _vec_1), 21.4200000);
}
test "zalgebra.Vec4.lerp" {
var _vec_0 = vec4.new(-10.0, 0.0, -10.0, -10.0);
var _vec_1 = vec4.new(10.0, 10.0, 10.0, 10.0);
testing.expectEqual(vec4.is_eq(vec4.lerp(_vec_0, _vec_1, 0.5), vec4.new(0.0, 5.0, 0.0, 0.0)), true);
}
test "zalgebra.Vec4.min" {
var _vec_0 = vec4.new(10.0, -2.0, 0.0, 1.0);
var _vec_1 = vec4.new(-10.0, 5.0, 0.0, 1.01);
testing.expectEqual(vec4.is_eq(vec4.min(_vec_0, _vec_1), vec4.new(-10.0, -2.0, 0.0, 1.0)), true);
}
test "zalgebra.Vec4.max" {
var _vec_0 = vec4.new(10.0, -2.0, 0.0, 1.0);
var _vec_1 = vec4.new(-10.0, 5.0, 0.0, 1.01);
testing.expectEqual(vec4.is_eq(vec4.max(_vec_0, _vec_1), vec4.new(10.0, 5.0, 0.0, 1.01)), true);
}
test "zalgebra.Vec2.from_slice" {
const array = [4]f32{ 2, 4, 3, 6 };
testing.expectEqual(vec4.is_eq(vec4.from_slice(&array), vec4.new(2, 4, 3, 6)), true);
}
test "zalgebra.Vec4.cast" {
const a = vec4_i32.new(3, 6, 2, 0);
const b = Vec4(usize).new(3, 6, 2, 0);
testing.expectEqual(
Vec4(usize).is_eq(a.cast(usize), b),
true,
);
const c = vec4.new(3.5, 6.5, 2.0, 0);
const d = vec4_f64.new(3.5, 6.5, 2, 0.0);
testing.expectEqual(
vec4_f64.is_eq(c.cast(f64), d),
true,
);
const e = vec4_i32.new(3, 6, 2, 0);
const f = vec4.new(3.0, 6.0, 2.0, 0.0);
testing.expectEqual(
vec4.is_eq(e.cast(f32), f),
true,
);
const g = vec4.new(3.0, 6.0, 2.0, 0.0);
const h = vec4_i32.new(3, 6, 2, 0);
testing.expectEqual(
vec4_i32.is_eq(g.cast(i32), h),
true,
);
} | src/vec4.zig |
pub const VDS_NF_VOLUME_ARRIVE = @as(u32, 4);
pub const VDS_NF_VOLUME_DEPART = @as(u32, 5);
pub const VDS_NF_VOLUME_MODIFY = @as(u32, 6);
pub const VDS_NF_VOLUME_REBUILDING_PROGRESS = @as(u32, 7);
pub const VDS_NF_PARTITION_ARRIVE = @as(u32, 11);
pub const VDS_NF_PARTITION_DEPART = @as(u32, 12);
pub const VDS_NF_PARTITION_MODIFY = @as(u32, 13);
pub const VDS_NF_SUB_SYSTEM_ARRIVE = @as(u32, 101);
pub const VDS_NF_SUB_SYSTEM_DEPART = @as(u32, 102);
pub const VDS_NF_PORTAL_ARRIVE = @as(u32, 123);
pub const VDS_NF_PORTAL_DEPART = @as(u32, 124);
pub const VDS_NF_PORTAL_MODIFY = @as(u32, 125);
pub const VDS_NF_TARGET_ARRIVE = @as(u32, 126);
pub const VDS_NF_TARGET_DEPART = @as(u32, 127);
pub const VDS_NF_TARGET_MODIFY = @as(u32, 128);
pub const VDS_NF_PORTAL_GROUP_ARRIVE = @as(u32, 129);
pub const VDS_NF_PORTAL_GROUP_DEPART = @as(u32, 130);
pub const VDS_NF_PORTAL_GROUP_MODIFY = @as(u32, 131);
pub const VDS_NF_SUB_SYSTEM_MODIFY = @as(u32, 151);
pub const VDS_NF_DRIVE_LETTER_FREE = @as(u32, 201);
pub const VDS_NF_DRIVE_LETTER_ASSIGN = @as(u32, 202);
pub const VDS_NF_MOUNT_POINTS_CHANGE = @as(u32, 205);
pub const VDS_NF_FILE_SYSTEM_SHRINKING_PROGRESS = @as(u32, 206);
pub const VDS_NF_SERVICE_OUT_OF_SYNC = @as(u32, 301);
pub const GPT_PARTITION_NAME_LENGTH = @as(u32, 36);
pub const VDS_HINT_FASTCRASHRECOVERYREQUIRED = @as(i32, 1);
pub const VDS_HINT_MOSTLYREADS = @as(i32, 2);
pub const VDS_HINT_OPTIMIZEFORSEQUENTIALREADS = @as(i32, 4);
pub const VDS_HINT_OPTIMIZEFORSEQUENTIALWRITES = @as(i32, 8);
pub const VDS_HINT_READBACKVERIFYENABLED = @as(i32, 16);
pub const VDS_HINT_REMAPENABLED = @as(i32, 32);
pub const VDS_HINT_WRITETHROUGHCACHINGENABLED = @as(i32, 64);
pub const VDS_HINT_HARDWARECHECKSUMENABLED = @as(i32, 128);
pub const VDS_HINT_ISYANKABLE = @as(i32, 256);
pub const VDS_HINT_ALLOCATEHOTSPARE = @as(i32, 512);
pub const VDS_HINT_BUSTYPE = @as(i32, 1024);
pub const VDS_HINT_USEMIRROREDCACHE = @as(i32, 2048);
pub const VDS_HINT_READCACHINGENABLED = @as(i32, 4096);
pub const VDS_HINT_WRITECACHINGENABLED = @as(i32, 8192);
pub const VDS_HINT_MEDIASCANENABLED = @as(i32, 16384);
pub const VDS_HINT_CONSISTENCYCHECKENABLED = @as(i32, 32768);
pub const VDS_REBUILD_PRIORITY_MIN = @as(u32, 0);
pub const VDS_REBUILD_PRIORITY_MAX = @as(u32, 16);
pub const VDS_POOL_ATTRIB_RAIDTYPE = @as(i32, 1);
pub const VDS_POOL_ATTRIB_BUSTYPE = @as(i32, 2);
pub const VDS_POOL_ATTRIB_ALLOW_SPINDOWN = @as(i32, 4);
pub const VDS_POOL_ATTRIB_THIN_PROVISION = @as(i32, 8);
pub const VDS_POOL_ATTRIB_NO_SINGLE_POF = @as(i32, 16);
pub const VDS_POOL_ATTRIB_DATA_RDNCY_MAX = @as(i32, 32);
pub const VDS_POOL_ATTRIB_DATA_RDNCY_MIN = @as(i32, 64);
pub const VDS_POOL_ATTRIB_DATA_RDNCY_DEF = @as(i32, 128);
pub const VDS_POOL_ATTRIB_PKG_RDNCY_MAX = @as(i32, 256);
pub const VDS_POOL_ATTRIB_PKG_RDNCY_MIN = @as(i32, 512);
pub const VDS_POOL_ATTRIB_PKG_RDNCY_DEF = @as(i32, 1024);
pub const VDS_POOL_ATTRIB_STRIPE_SIZE = @as(i32, 2048);
pub const VDS_POOL_ATTRIB_STRIPE_SIZE_MAX = @as(i32, 4096);
pub const VDS_POOL_ATTRIB_STRIPE_SIZE_MIN = @as(i32, 8192);
pub const VDS_POOL_ATTRIB_STRIPE_SIZE_DEF = @as(i32, 16384);
pub const VDS_POOL_ATTRIB_NUM_CLMNS = @as(i32, 32768);
pub const VDS_POOL_ATTRIB_NUM_CLMNS_MAX = @as(i32, 65536);
pub const VDS_POOL_ATTRIB_NUM_CLMNS_MIN = @as(i32, 131072);
pub const VDS_POOL_ATTRIB_NUM_CLMNS_DEF = @as(i32, 262144);
pub const VDS_POOL_ATTRIB_DATA_AVL_HINT = @as(i32, 524288);
pub const VDS_POOL_ATTRIB_ACCS_RNDM_HINT = @as(i32, 1048576);
pub const VDS_POOL_ATTRIB_ACCS_DIR_HINT = @as(i32, 2097152);
pub const VDS_POOL_ATTRIB_ACCS_SIZE_HINT = @as(i32, 4194304);
pub const VDS_POOL_ATTRIB_ACCS_LTNCY_HINT = @as(i32, 8388608);
pub const VDS_POOL_ATTRIB_ACCS_BDW_WT_HINT = @as(i32, 16777216);
pub const VDS_POOL_ATTRIB_STOR_COST_HINT = @as(i32, 33554432);
pub const VDS_POOL_ATTRIB_STOR_EFFCY_HINT = @as(i32, 67108864);
pub const VDS_POOL_ATTRIB_CUSTOM_ATTRIB = @as(i32, 134217728);
pub const VDS_ATTACH_VIRTUAL_DISK_FLAG_USE_FILE_ACL = @as(u32, 1);
pub const CLSID_VdsLoader = Guid.initString("9c38ed61-d565-4728-aeee-c80952f0ecde");
pub const CLSID_VdsService = Guid.initString("7d1933cb-86f6-4a98-8628-01be94c9a575");
pub const MAX_FS_NAME_SIZE = @as(u32, 8);
pub const MAX_FS_FORMAT_SUPPORT_NAME_SIZE = @as(u32, 32);
pub const MAX_FS_ALLOWED_CLUSTER_SIZES_SIZE = @as(u32, 32);
pub const VER_VDS_LUN_INFORMATION = @as(u32, 1);
pub const VDS_E_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212288));
pub const VDS_E_INITIALIZED_FAILED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212287));
pub const VDS_E_INITIALIZE_NOT_CALLED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212286));
pub const VDS_E_ALREADY_REGISTERED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212285));
pub const VDS_E_ANOTHER_CALL_IN_PROGRESS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212284));
pub const VDS_E_OBJECT_NOT_FOUND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212283));
pub const VDS_E_INVALID_SPACE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212282));
pub const VDS_E_PARTITION_LIMIT_REACHED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212281));
pub const VDS_E_PARTITION_NOT_EMPTY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212280));
pub const VDS_E_OPERATION_PENDING = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212279));
pub const VDS_E_OPERATION_DENIED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212278));
pub const VDS_E_OBJECT_DELETED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212277));
pub const VDS_E_CANCEL_TOO_LATE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212276));
pub const VDS_E_OPERATION_CANCELED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212275));
pub const VDS_E_CANNOT_EXTEND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212274));
pub const VDS_E_NOT_ENOUGH_SPACE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212273));
pub const VDS_E_NOT_ENOUGH_DRIVE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212272));
pub const VDS_E_BAD_COOKIE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212271));
pub const VDS_E_NO_MEDIA = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212270));
pub const VDS_E_DEVICE_IN_USE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212269));
pub const VDS_E_DISK_NOT_EMPTY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212268));
pub const VDS_E_INVALID_OPERATION = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212267));
pub const VDS_E_PATH_NOT_FOUND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212266));
pub const VDS_E_DISK_NOT_INITIALIZED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212265));
pub const VDS_E_NOT_AN_UNALLOCATED_DISK = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212264));
pub const VDS_E_UNRECOVERABLE_ERROR = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212263));
pub const VDS_S_DISK_PARTIALLY_CLEANED = @import("../zig.zig").typedConst(HRESULT, @as(i32, 271386));
pub const VDS_E_DMADMIN_SERVICE_CONNECTION_FAILED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212261));
pub const VDS_E_PROVIDER_INITIALIZATION_FAILED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212260));
pub const VDS_E_OBJECT_EXISTS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212259));
pub const VDS_E_NO_DISKS_FOUND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212258));
pub const VDS_E_PROVIDER_CACHE_CORRUPT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212257));
pub const VDS_E_DMADMIN_METHOD_CALL_FAILED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212256));
pub const VDS_S_PROVIDER_ERROR_LOADING_CACHE = @import("../zig.zig").typedConst(HRESULT, @as(i32, 271393));
pub const VDS_E_PROVIDER_VOL_DEVICE_NAME_NOT_FOUND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212254));
pub const VDS_E_PROVIDER_VOL_OPEN = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212253));
pub const VDS_E_DMADMIN_CORRUPT_NOTIFICATION = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212252));
pub const VDS_E_INCOMPATIBLE_FILE_SYSTEM = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212251));
pub const VDS_E_INCOMPATIBLE_MEDIA = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212250));
pub const VDS_E_ACCESS_DENIED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212249));
pub const VDS_E_MEDIA_WRITE_PROTECTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212248));
pub const VDS_E_BAD_LABEL = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212247));
pub const VDS_E_CANT_QUICK_FORMAT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212246));
pub const VDS_E_IO_ERROR = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212245));
pub const VDS_E_VOLUME_TOO_SMALL = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212244));
pub const VDS_E_VOLUME_TOO_BIG = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212243));
pub const VDS_E_CLUSTER_SIZE_TOO_SMALL = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212242));
pub const VDS_E_CLUSTER_SIZE_TOO_BIG = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212241));
pub const VDS_E_CLUSTER_COUNT_BEYOND_32BITS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212240));
pub const VDS_E_OBJECT_STATUS_FAILED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212239));
pub const VDS_E_VOLUME_INCOMPLETE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212238));
pub const VDS_E_EXTENT_SIZE_LESS_THAN_MIN = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212237));
pub const VDS_S_UPDATE_BOOTFILE_FAILED = @import("../zig.zig").typedConst(HRESULT, @as(i32, 271412));
pub const VDS_S_BOOT_PARTITION_NUMBER_CHANGE = @import("../zig.zig").typedConst(HRESULT, @as(i32, 271414));
pub const VDS_E_BOOT_PARTITION_NUMBER_CHANGE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212234));
pub const VDS_E_NO_FREE_SPACE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212233));
pub const VDS_E_ACTIVE_PARTITION = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212232));
pub const VDS_E_PARTITION_OF_UNKNOWN_TYPE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212231));
pub const VDS_E_LEGACY_VOLUME_FORMAT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212230));
pub const VDS_E_NON_CONTIGUOUS_DATA_PARTITIONS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212229));
pub const VDS_E_MIGRATE_OPEN_VOLUME = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212228));
pub const VDS_E_VOLUME_NOT_ONLINE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212227));
pub const VDS_E_VOLUME_NOT_HEALTHY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212226));
pub const VDS_E_VOLUME_SPANS_DISKS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212225));
pub const VDS_E_REQUIRES_CONTIGUOUS_DISK_SPACE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212224));
pub const VDS_E_BAD_PROVIDER_DATA = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212223));
pub const VDS_E_PROVIDER_FAILURE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212222));
pub const VDS_S_VOLUME_COMPRESS_FAILED = @import("../zig.zig").typedConst(HRESULT, @as(i32, 271427));
pub const VDS_E_PACK_OFFLINE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212220));
pub const VDS_E_VOLUME_NOT_A_MIRROR = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212219));
pub const VDS_E_NO_EXTENTS_FOR_VOLUME = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212218));
pub const VDS_E_DISK_NOT_LOADED_TO_CACHE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212217));
pub const VDS_E_INTERNAL_ERROR = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212216));
pub const VDS_S_ACCESS_PATH_NOT_DELETED = @import("../zig.zig").typedConst(HRESULT, @as(i32, 279108));
pub const VDS_E_PROVIDER_TYPE_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212214));
pub const VDS_E_DISK_NOT_ONLINE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212213));
pub const VDS_E_DISK_IN_USE_BY_VOLUME = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212212));
pub const VDS_S_IN_PROGRESS = @import("../zig.zig").typedConst(HRESULT, @as(i32, 271437));
pub const VDS_E_ASYNC_OBJECT_FAILURE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212210));
pub const VDS_E_VOLUME_NOT_MOUNTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212209));
pub const VDS_E_PACK_NOT_FOUND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212208));
pub const VDS_E_IMPORT_SET_INCOMPLETE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212207));
pub const VDS_E_DISK_NOT_IMPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212206));
pub const VDS_E_OBJECT_OUT_OF_SYNC = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212205));
pub const VDS_E_MISSING_DISK = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212204));
pub const VDS_E_DISK_PNP_REG_CORRUPT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212203));
pub const VDS_E_LBN_REMAP_ENABLED_FLAG = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212202));
pub const VDS_E_NO_DRIVELETTER_FLAG = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212201));
pub const VDS_E_REVERT_ON_CLOSE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212200));
pub const VDS_E_REVERT_ON_CLOSE_SET = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212199));
pub const VDS_E_IA64_BOOT_MIRRORED_TO_MBR = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212198));
pub const VDS_S_IA64_BOOT_MIRRORED_TO_MBR = @import("../zig.zig").typedConst(HRESULT, @as(i32, 271450));
pub const VDS_S_UNABLE_TO_GET_GPT_ATTRIBUTES = @import("../zig.zig").typedConst(HRESULT, @as(i32, 271451));
pub const VDS_E_VOLUME_TEMPORARILY_DISMOUNTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212196));
pub const VDS_E_VOLUME_PERMANENTLY_DISMOUNTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212195));
pub const VDS_E_VOLUME_HAS_PATH = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212194));
pub const VDS_E_TIMEOUT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212193));
pub const VDS_E_REPAIR_VOLUMESTATE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212192));
pub const VDS_E_LDM_TIMEOUT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212191));
pub const VDS_E_REVERT_ON_CLOSE_MISMATCH = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212190));
pub const VDS_E_RETRY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212189));
pub const VDS_E_ONLINE_PACK_EXISTS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212188));
pub const VDS_S_EXTEND_FILE_SYSTEM_FAILED = @import("../zig.zig").typedConst(HRESULT, @as(i32, 271461));
pub const VDS_E_EXTEND_FILE_SYSTEM_FAILED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212186));
pub const VDS_S_MBR_BOOT_MIRRORED_TO_GPT = @import("../zig.zig").typedConst(HRESULT, @as(i32, 271463));
pub const VDS_E_MAX_USABLE_MBR = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212184));
pub const VDS_S_GPT_BOOT_MIRRORED_TO_MBR = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212183));
pub const VDS_E_NO_SOFTWARE_PROVIDERS_LOADED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212032));
pub const VDS_E_DISK_NOT_MISSING = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212031));
pub const VDS_E_NO_VOLUME_LAYOUT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212030));
pub const VDS_E_CORRUPT_VOLUME_INFO = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212029));
pub const VDS_E_INVALID_ENUMERATOR = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212028));
pub const VDS_E_DRIVER_INTERNAL_ERROR = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212027));
pub const VDS_E_VOLUME_INVALID_NAME = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212025));
pub const VDS_S_DISK_IS_MISSING = @import("../zig.zig").typedConst(HRESULT, @as(i32, 271624));
pub const VDS_E_CORRUPT_PARTITION_INFO = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212023));
pub const VDS_S_NONCONFORMANT_PARTITION_INFO = @import("../zig.zig").typedConst(HRESULT, @as(i32, 271626));
pub const VDS_E_CORRUPT_EXTENT_INFO = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212021));
pub const VDS_E_DUP_EMPTY_PACK_GUID = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212020));
pub const VDS_E_DRIVER_NO_PACK_NAME = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212019));
pub const VDS_S_SYSTEM_PARTITION = @import("../zig.zig").typedConst(HRESULT, @as(i32, 271630));
pub const VDS_E_BAD_PNP_MESSAGE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212017));
pub const VDS_E_NO_PNP_DISK_ARRIVE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212016));
pub const VDS_E_NO_PNP_VOLUME_ARRIVE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212015));
pub const VDS_E_NO_PNP_DISK_REMOVE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212014));
pub const VDS_E_NO_PNP_VOLUME_REMOVE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212013));
pub const VDS_E_PROVIDER_EXITING = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212012));
pub const VDS_E_EXTENT_EXCEEDS_DISK_FREE_SPACE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212011));
pub const VDS_E_MEMBER_SIZE_INVALID = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212010));
pub const VDS_S_NO_NOTIFICATION = @import("../zig.zig").typedConst(HRESULT, @as(i32, 271639));
pub const VDS_S_DEFAULT_PLEX_MEMBER_IDS = @import("../zig.zig").typedConst(HRESULT, @as(i32, 271640));
pub const VDS_E_INVALID_DISK = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212007));
pub const VDS_E_INVALID_PACK = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212006));
pub const VDS_E_VOLUME_ON_DISK = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212005));
pub const VDS_E_DRIVER_INVALID_PARAM = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212004));
pub const VDS_E_TARGET_PACK_NOT_EMPTY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212003));
pub const VDS_E_CANNOT_SHRINK = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212002));
pub const VDS_E_MULTIPLE_PACKS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212001));
pub const VDS_E_PACK_ONLINE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147212000));
pub const VDS_E_INVALID_PLEX_COUNT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211999));
pub const VDS_E_INVALID_MEMBER_COUNT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211998));
pub const VDS_E_INVALID_PLEX_ORDER = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211997));
pub const VDS_E_INVALID_MEMBER_ORDER = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211996));
pub const VDS_E_INVALID_STRIPE_SIZE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211995));
pub const VDS_E_INVALID_DISK_COUNT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211994));
pub const VDS_E_INVALID_EXTENT_COUNT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211993));
pub const VDS_E_SOURCE_IS_TARGET_PACK = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211992));
pub const VDS_E_VOLUME_DISK_COUNT_MAX_EXCEEDED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211991));
pub const VDS_E_CORRUPT_NOTIFICATION_INFO = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211990));
pub const VDS_E_INVALID_PLEX_GUID = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211988));
pub const VDS_E_DISK_NOT_FOUND_IN_PACK = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211987));
pub const VDS_E_DUPLICATE_DISK = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211986));
pub const VDS_E_LAST_VALID_DISK = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211985));
pub const VDS_E_INVALID_SECTOR_SIZE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211984));
pub const VDS_E_ONE_EXTENT_PER_DISK = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211983));
pub const VDS_E_INVALID_BLOCK_SIZE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211982));
pub const VDS_E_PLEX_SIZE_INVALID = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211981));
pub const VDS_E_NO_EXTENTS_FOR_PLEX = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211980));
pub const VDS_E_INVALID_PLEX_TYPE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211979));
pub const VDS_E_INVALID_PLEX_BLOCK_SIZE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211978));
pub const VDS_E_NO_HEALTHY_DISKS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211977));
pub const VDS_E_CONFIG_LIMIT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211976));
pub const VDS_E_DISK_CONFIGURATION_CORRUPTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211975));
pub const VDS_E_DISK_CONFIGURATION_NOT_IN_SYNC = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211974));
pub const VDS_E_DISK_CONFIGURATION_UPDATE_FAILED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211973));
pub const VDS_E_DISK_DYNAMIC = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211972));
pub const VDS_E_DRIVER_OBJECT_NOT_FOUND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211971));
pub const VDS_E_PARTITION_NOT_CYLINDER_ALIGNED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211970));
pub const VDS_E_DISK_LAYOUT_PARTITIONS_TOO_SMALL = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211969));
pub const VDS_E_DISK_IO_FAILING = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211968));
pub const VDS_E_DYNAMIC_DISKS_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211967));
pub const VDS_E_FAULT_TOLERANT_DISKS_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211966));
pub const VDS_E_GPT_ATTRIBUTES_INVALID = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211965));
pub const VDS_E_MEMBER_IS_HEALTHY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211964));
pub const VDS_E_MEMBER_REGENERATING = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211963));
pub const VDS_E_PACK_NAME_INVALID = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211962));
pub const VDS_E_PLEX_IS_HEALTHY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211961));
pub const VDS_E_PLEX_LAST_ACTIVE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211960));
pub const VDS_E_PLEX_MISSING = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211959));
pub const VDS_E_MEMBER_MISSING = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211958));
pub const VDS_E_PLEX_REGENERATING = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211957));
pub const VDS_E_UNEXPECTED_DISK_LAYOUT_CHANGE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211955));
pub const VDS_E_INVALID_VOLUME_LENGTH = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211954));
pub const VDS_E_VOLUME_LENGTH_NOT_SECTOR_SIZE_MULTIPLE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211953));
pub const VDS_E_VOLUME_NOT_RETAINED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211952));
pub const VDS_E_VOLUME_RETAINED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211951));
pub const VDS_E_ALIGN_BEYOND_FIRST_CYLINDER = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211949));
pub const VDS_E_ALIGN_NOT_SECTOR_SIZE_MULTIPLE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211948));
pub const VDS_E_ALIGN_NOT_ZERO = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211947));
pub const VDS_E_CACHE_CORRUPT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211946));
pub const VDS_E_CANNOT_CLEAR_VOLUME_FLAG = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211945));
pub const VDS_E_DISK_BEING_CLEANED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211944));
pub const VDS_E_DISK_NOT_CONVERTIBLE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211943));
pub const VDS_E_DISK_REMOVEABLE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211942));
pub const VDS_E_DISK_REMOVEABLE_NOT_EMPTY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211941));
pub const VDS_E_DRIVE_LETTER_NOT_FREE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211940));
pub const VDS_E_EXTEND_MULTIPLE_DISKS_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211939));
pub const VDS_E_INVALID_DRIVE_LETTER = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211938));
pub const VDS_E_INVALID_DRIVE_LETTER_COUNT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211937));
pub const VDS_E_INVALID_FS_FLAG = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211936));
pub const VDS_E_INVALID_FS_TYPE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211935));
pub const VDS_E_INVALID_OBJECT_TYPE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211934));
pub const VDS_E_INVALID_PARTITION_LAYOUT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211933));
pub const VDS_E_INVALID_PARTITION_STYLE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211932));
pub const VDS_E_INVALID_PARTITION_TYPE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211931));
pub const VDS_E_INVALID_PROVIDER_CLSID = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211930));
pub const VDS_E_INVALID_PROVIDER_ID = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211929));
pub const VDS_E_INVALID_PROVIDER_NAME = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211928));
pub const VDS_E_INVALID_PROVIDER_TYPE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211927));
pub const VDS_E_INVALID_PROVIDER_VERSION_GUID = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211926));
pub const VDS_E_INVALID_PROVIDER_VERSION_STRING = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211925));
pub const VDS_E_INVALID_QUERY_PROVIDER_FLAG = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211924));
pub const VDS_E_INVALID_SERVICE_FLAG = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211923));
pub const VDS_E_INVALID_VOLUME_FLAG = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211922));
pub const VDS_E_PARTITION_NOT_OEM = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211921));
pub const VDS_E_PARTITION_PROTECTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211920));
pub const VDS_E_PARTITION_STYLE_MISMATCH = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211919));
pub const VDS_E_PROVIDER_INTERNAL_ERROR = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211918));
pub const VDS_E_SHRINK_SIZE_LESS_THAN_MIN = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211917));
pub const VDS_E_SHRINK_SIZE_TOO_BIG = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211916));
pub const VDS_E_UNRECOVERABLE_PROVIDER_ERROR = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211915));
pub const VDS_E_VOLUME_HIDDEN = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211914));
pub const VDS_S_DISMOUNT_FAILED = @import("../zig.zig").typedConst(HRESULT, @as(i32, 271735));
pub const VDS_S_REMOUNT_FAILED = @import("../zig.zig").typedConst(HRESULT, @as(i32, 271736));
pub const VDS_E_FLAG_ALREADY_SET = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211911));
pub const VDS_S_RESYNC_NOTIFICATION_TASK_FAILED = @import("../zig.zig").typedConst(HRESULT, @as(i32, 271738));
pub const VDS_E_DISTINCT_VOLUME = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211909));
pub const VDS_E_VOLUME_NOT_FOUND_IN_PACK = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211908));
pub const VDS_E_PARTITION_NON_DATA = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211907));
pub const VDS_E_CRITICAL_PLEX = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211906));
pub const VDS_E_VOLUME_SYNCHRONIZING = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211905));
pub const VDS_E_VOLUME_REGENERATING = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211904));
pub const VDS_S_VSS_FLUSH_AND_HOLD_WRITES = @import("../zig.zig").typedConst(HRESULT, @as(i32, 271745));
pub const VDS_S_VSS_RELEASE_WRITES = @import("../zig.zig").typedConst(HRESULT, @as(i32, 271746));
pub const VDS_S_FS_LOCK = @import("../zig.zig").typedConst(HRESULT, @as(i32, 271747));
pub const VDS_E_READONLY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211900));
pub const VDS_E_INVALID_VOLUME_TYPE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211899));
pub const VDS_E_BAD_BOOT_DISK = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211898));
pub const VDS_E_LOG_UPDATE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211897));
pub const VDS_E_VOLUME_MIRRORED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211896));
pub const VDS_E_VOLUME_SIMPLE_SPANNED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211895));
pub const VDS_E_NO_VALID_LOG_COPIES = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211894));
pub const VDS_S_PLEX_NOT_LOADED_TO_CACHE = @import("../zig.zig").typedConst(HRESULT, @as(i32, 271755));
pub const VDS_E_PLEX_NOT_LOADED_TO_CACHE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211893));
pub const VDS_E_PARTITION_MSR = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211892));
pub const VDS_E_PARTITION_LDM = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211891));
pub const VDS_S_WINPE_BOOTENTRY = @import("../zig.zig").typedConst(HRESULT, @as(i32, 271758));
pub const VDS_E_ALIGN_NOT_A_POWER_OF_TWO = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211889));
pub const VDS_E_ALIGN_IS_ZERO = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211888));
pub const VDS_E_SHRINK_IN_PROGRESS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211887));
pub const VDS_E_CANT_INVALIDATE_FVE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211886));
pub const VDS_E_FS_NOT_DETERMINED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211885));
pub const VDS_E_DISK_NOT_OFFLINE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211883));
pub const VDS_E_FAILED_TO_ONLINE_DISK = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211882));
pub const VDS_E_FAILED_TO_OFFLINE_DISK = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211881));
pub const VDS_E_BAD_REVISION_NUMBER = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211880));
pub const VDS_E_SHRINK_USER_CANCELLED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211879));
pub const VDS_E_SHRINK_DIRTY_VOLUME = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211878));
pub const VDS_S_NAME_TRUNCATED = @import("../zig.zig").typedConst(HRESULT, @as(i32, 272128));
pub const VDS_E_NAME_NOT_UNIQUE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211519));
pub const VDS_S_STATUSES_INCOMPLETELY_SET = @import("../zig.zig").typedConst(HRESULT, @as(i32, 272130));
pub const VDS_E_ADDRESSES_INCOMPLETELY_SET = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211517));
pub const VDS_E_SECURITY_INCOMPLETELY_SET = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211515));
pub const VDS_E_TARGET_SPECIFIC_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211514));
pub const VDS_E_INITIATOR_SPECIFIC_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211513));
pub const VDS_E_ISCSI_LOGIN_FAILED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211512));
pub const VDS_E_ISCSI_LOGOUT_FAILED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211511));
pub const VDS_E_ISCSI_SESSION_NOT_FOUND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211510));
pub const VDS_E_ASSOCIATED_LUNS_EXIST = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211509));
pub const VDS_E_ASSOCIATED_PORTALS_EXIST = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211508));
pub const VDS_E_NO_DISCOVERY_DOMAIN = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211507));
pub const VDS_E_MULTIPLE_DISCOVERY_DOMAINS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211506));
pub const VDS_E_NO_DISK_PATHNAME = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211505));
pub const VDS_E_ISCSI_LOGOUT_INCOMPLETE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211504));
pub const VDS_E_NO_VOLUME_PATHNAME = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211503));
pub const VDS_E_PROVIDER_CACHE_OUTOFSYNC = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211502));
pub const VDS_E_NO_IMPORT_TARGET = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211501));
pub const VDS_S_ALREADY_EXISTS = @import("../zig.zig").typedConst(HRESULT, @as(i32, 272148));
pub const VDS_S_PROPERTIES_INCOMPLETE = @import("../zig.zig").typedConst(HRESULT, @as(i32, 272149));
pub const VDS_S_ISCSI_SESSION_NOT_FOUND_PERSISTENT_LOGIN_REMOVED = @import("../zig.zig").typedConst(HRESULT, @as(i32, 272384));
pub const VDS_S_ISCSI_PERSISTENT_LOGIN_MAY_NOT_BE_REMOVED = @import("../zig.zig").typedConst(HRESULT, @as(i32, 272385));
pub const VDS_S_ISCSI_LOGIN_ALREAD_EXISTS = @import("../zig.zig").typedConst(HRESULT, @as(i32, 272386));
pub const VDS_E_UNABLE_TO_FIND_BOOT_DISK = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211261));
pub const VDS_E_INCORRECT_BOOT_VOLUME_EXTENT_INFO = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211260));
pub const VDS_E_GET_SAN_POLICY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211259));
pub const VDS_E_SET_SAN_POLICY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211258));
pub const VDS_E_BOOT_DISK = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211257));
pub const VDS_S_DISK_MOUNT_FAILED = @import("../zig.zig").typedConst(HRESULT, @as(i32, 272392));
pub const VDS_S_DISK_DISMOUNT_FAILED = @import("../zig.zig").typedConst(HRESULT, @as(i32, 272393));
pub const VDS_E_DISK_IS_OFFLINE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211254));
pub const VDS_E_DISK_IS_READ_ONLY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211253));
pub const VDS_E_PAGEFILE_DISK = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211252));
pub const VDS_E_HIBERNATION_FILE_DISK = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211251));
pub const VDS_E_CRASHDUMP_DISK = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211250));
pub const VDS_E_UNABLE_TO_FIND_SYSTEM_DISK = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211249));
pub const VDS_E_INCORRECT_SYSTEM_VOLUME_EXTENT_INFO = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211248));
pub const VDS_E_SYSTEM_DISK = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211247));
pub const VDS_E_VOLUME_SHRINK_FVE_LOCKED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211246));
pub const VDS_E_VOLUME_SHRINK_FVE_CORRUPT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211245));
pub const VDS_E_VOLUME_SHRINK_FVE_RECOVERY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211244));
pub const VDS_E_VOLUME_SHRINK_FVE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211243));
pub const VDS_E_SHRINK_OVER_DATA = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211242));
pub const VDS_E_INVALID_SHRINK_SIZE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211241));
pub const VDS_E_LUN_DISK_MISSING = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211240));
pub const VDS_E_LUN_DISK_FAILED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211239));
pub const VDS_E_LUN_DISK_NOT_READY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211238));
pub const VDS_E_LUN_DISK_NO_MEDIA = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211237));
pub const VDS_E_LUN_NOT_READY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211236));
pub const VDS_E_LUN_OFFLINE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211235));
pub const VDS_E_LUN_FAILED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211234));
pub const VDS_E_VOLUME_EXTEND_FVE_LOCKED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211233));
pub const VDS_E_VOLUME_EXTEND_FVE_CORRUPT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211232));
pub const VDS_E_VOLUME_EXTEND_FVE_RECOVERY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211231));
pub const VDS_E_VOLUME_EXTEND_FVE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211230));
pub const VDS_E_SECTOR_SIZE_ERROR = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211229));
pub const VDS_E_INITIATOR_ADAPTER_NOT_FOUND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211008));
pub const VDS_E_TARGET_PORTAL_NOT_FOUND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211007));
pub const VDS_E_INVALID_PORT_PATH = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211006));
pub const VDS_E_INVALID_ISCSI_TARGET_NAME = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211005));
pub const VDS_E_SET_TUNNEL_MODE_OUTER_ADDRESS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211004));
pub const VDS_E_ISCSI_GET_IKE_INFO = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211003));
pub const VDS_E_ISCSI_SET_IKE_INFO = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211002));
pub const VDS_E_SUBSYSTEM_ID_IS_NULL = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211001));
pub const VDS_E_ISCSI_INITIATOR_NODE_NAME = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147211000));
pub const VDS_E_ISCSI_GROUP_PRESHARE_KEY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210999));
pub const VDS_E_ISCSI_CHAP_SECRET = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210998));
pub const VDS_E_INVALID_IP_ADDRESS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210997));
pub const VDS_E_REBOOT_REQUIRED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210996));
pub const VDS_E_VOLUME_GUID_PATHNAME_NOT_ALLOWED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210995));
pub const VDS_E_BOOT_PAGEFILE_DRIVE_LETTER = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210994));
pub const VDS_E_DELETE_WITH_CRITICAL = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210993));
pub const VDS_E_CLEAN_WITH_DATA = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210992));
pub const VDS_E_CLEAN_WITH_OEM = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210991));
pub const VDS_E_CLEAN_WITH_CRITICAL = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210990));
pub const VDS_E_FORMAT_CRITICAL = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210989));
pub const VDS_E_NTFS_FORMAT_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210988));
pub const VDS_E_FAT32_FORMAT_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210987));
pub const VDS_E_FAT_FORMAT_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210986));
pub const VDS_E_FORMAT_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210985));
pub const VDS_E_COMPRESSION_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210984));
pub const VDS_E_VDISK_NOT_OPEN = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210983));
pub const VDS_E_VDISK_INVALID_OP_STATE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210982));
pub const VDS_E_INVALID_PATH = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210981));
pub const VDS_E_INVALID_ISCSI_PATH = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210980));
pub const VDS_E_SHRINK_LUN_NOT_UNMASKED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210979));
pub const VDS_E_LUN_DISK_READ_ONLY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210978));
pub const VDS_E_LUN_UPDATE_DISK = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210977));
pub const VDS_E_LUN_DYNAMIC = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210976));
pub const VDS_E_LUN_DYNAMIC_OFFLINE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210975));
pub const VDS_E_LUN_SHRINK_GPT_HEADER = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210974));
pub const VDS_E_MIRROR_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210973));
pub const VDS_E_RAID5_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210972));
pub const VDS_E_DISK_NOT_CONVERTIBLE_SIZE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210971));
pub const VDS_E_OFFLINE_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210970));
pub const VDS_E_VDISK_PATHNAME_INVALID = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210969));
pub const VDS_E_EXTEND_TOO_MANY_CLUSTERS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210968));
pub const VDS_E_EXTEND_UNKNOWN_FILESYSTEM = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210967));
pub const VDS_E_SHRINK_UNKNOWN_FILESYSTEM = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210966));
pub const VDS_E_VD_DISK_NOT_OPEN = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210965));
pub const VDS_E_VD_DISK_IS_EXPANDING = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210964));
pub const VDS_E_VD_DISK_IS_COMPACTING = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210963));
pub const VDS_E_VD_DISK_IS_MERGING = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210962));
pub const VDS_E_VD_IS_ATTACHED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210961));
pub const VDS_E_VD_DISK_ALREADY_OPEN = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210960));
pub const VDS_E_VD_DISK_ALREADY_EXPANDING = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210959));
pub const VDS_E_VD_ALREADY_COMPACTING = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210958));
pub const VDS_E_VD_ALREADY_MERGING = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210957));
pub const VDS_E_VD_ALREADY_ATTACHED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210956));
pub const VDS_E_VD_ALREADY_DETACHED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210955));
pub const VDS_E_VD_NOT_ATTACHED_READONLY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210954));
pub const VDS_E_VD_IS_BEING_ATTACHED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210953));
pub const VDS_E_VD_IS_BEING_DETACHED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210952));
pub const VDS_E_NO_POOL = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210752));
pub const VDS_E_NO_POOL_CREATED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210751));
pub const VDS_E_NO_MAINTENANCE_MODE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210750));
pub const VDS_E_BLOCK_CLUSTERED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210749));
pub const VDS_E_DISK_HAS_BANDS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210748));
pub const VDS_E_INVALID_STATE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210747));
pub const VDS_E_REFS_FORMAT_NOT_SUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210746));
pub const VDS_E_DELETE_WITH_BOOTBACKING = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210745));
pub const VDS_E_FORMAT_WITH_BOOTBACKING = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210744));
pub const VDS_E_CLEAN_WITH_BOOTBACKING = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210743));
pub const VDS_E_SHRINK_EXTEND_UNALIGNED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147210496));
//--------------------------------------------------------------------------------
// Section: Types (139)
//--------------------------------------------------------------------------------
pub const VDS_NF_PACK = enum(u32) {
ARRIVE = 1,
DEPART = 2,
MODIFY = 3,
};
pub const VDS_NF_PACK_ARRIVE = VDS_NF_PACK.ARRIVE;
pub const VDS_NF_PACK_DEPART = VDS_NF_PACK.DEPART;
pub const VDS_NF_PACK_MODIFY = VDS_NF_PACK.MODIFY;
pub const VDS_NF_FILE_SYSTEM = enum(u32) {
MODIFY = 203,
FORMAT_PROGRESS = 204,
};
pub const VDS_NF_FILE_SYSTEM_MODIFY = VDS_NF_FILE_SYSTEM.MODIFY;
pub const VDS_NF_FILE_SYSTEM_FORMAT_PROGRESS = VDS_NF_FILE_SYSTEM.FORMAT_PROGRESS;
pub const VDS_NF_CONTROLLER = enum(u32) {
ARRIVE = 103,
DEPART = 104,
MODIFY = 350,
REMOVED = 351,
};
pub const VDS_NF_CONTROLLER_ARRIVE = VDS_NF_CONTROLLER.ARRIVE;
pub const VDS_NF_CONTROLLER_DEPART = VDS_NF_CONTROLLER.DEPART;
pub const VDS_NF_CONTROLLER_MODIFY = VDS_NF_CONTROLLER.MODIFY;
pub const VDS_NF_CONTROLLER_REMOVED = VDS_NF_CONTROLLER.REMOVED;
pub const VDS_NF_DRIVE = enum(u32) {
ARRIVE = 105,
DEPART = 106,
MODIFY = 107,
REMOVED = 354,
};
pub const VDS_NF_DRIVE_ARRIVE = VDS_NF_DRIVE.ARRIVE;
pub const VDS_NF_DRIVE_DEPART = VDS_NF_DRIVE.DEPART;
pub const VDS_NF_DRIVE_MODIFY = VDS_NF_DRIVE.MODIFY;
pub const VDS_NF_DRIVE_REMOVED = VDS_NF_DRIVE.REMOVED;
pub const VDS_NF_PORT = enum(u32) {
ARRIVE = 121,
DEPART = 122,
MODIFY = 352,
REMOVED = 353,
};
pub const VDS_NF_PORT_ARRIVE = VDS_NF_PORT.ARRIVE;
pub const VDS_NF_PORT_DEPART = VDS_NF_PORT.DEPART;
pub const VDS_NF_PORT_MODIFY = VDS_NF_PORT.MODIFY;
pub const VDS_NF_PORT_REMOVED = VDS_NF_PORT.REMOVED;
pub const VDS_NF_LUN = enum(u32) {
ARRIVE = 108,
DEPART = 109,
MODIFY = 110,
};
pub const VDS_NF_LUN_ARRIVE = VDS_NF_LUN.ARRIVE;
pub const VDS_NF_LUN_DEPART = VDS_NF_LUN.DEPART;
pub const VDS_NF_LUN_MODIFY = VDS_NF_LUN.MODIFY;
pub const VDS_NF_DISK = enum(u32) {
ARRIVE = 8,
DEPART = 9,
MODIFY = 10,
};
pub const VDS_NF_DISK_ARRIVE = VDS_NF_DISK.ARRIVE;
pub const VDS_NF_DISK_DEPART = VDS_NF_DISK.DEPART;
pub const VDS_NF_DISK_MODIFY = VDS_NF_DISK.MODIFY;
pub const VDS_STORAGE_IDENTIFIER_CODE_SET = enum(i32) {
Reserved = 0,
Binary = 1,
Ascii = 2,
Utf8 = 3,
};
pub const VDSStorageIdCodeSetReserved = VDS_STORAGE_IDENTIFIER_CODE_SET.Reserved;
pub const VDSStorageIdCodeSetBinary = VDS_STORAGE_IDENTIFIER_CODE_SET.Binary;
pub const VDSStorageIdCodeSetAscii = VDS_STORAGE_IDENTIFIER_CODE_SET.Ascii;
pub const VDSStorageIdCodeSetUtf8 = VDS_STORAGE_IDENTIFIER_CODE_SET.Utf8;
pub const VDS_STORAGE_IDENTIFIER_TYPE = enum(i32) {
VendorSpecific = 0,
VendorId = 1,
EUI64 = 2,
FCPHName = 3,
PortRelative = 4,
TargetPortGroup = 5,
LogicalUnitGroup = 6,
MD5LogicalUnitIdentifier = 7,
ScsiNameString = 8,
};
pub const VDSStorageIdTypeVendorSpecific = VDS_STORAGE_IDENTIFIER_TYPE.VendorSpecific;
pub const VDSStorageIdTypeVendorId = VDS_STORAGE_IDENTIFIER_TYPE.VendorId;
pub const VDSStorageIdTypeEUI64 = VDS_STORAGE_IDENTIFIER_TYPE.EUI64;
pub const VDSStorageIdTypeFCPHName = VDS_STORAGE_IDENTIFIER_TYPE.FCPHName;
pub const VDSStorageIdTypePortRelative = VDS_STORAGE_IDENTIFIER_TYPE.PortRelative;
pub const VDSStorageIdTypeTargetPortGroup = VDS_STORAGE_IDENTIFIER_TYPE.TargetPortGroup;
pub const VDSStorageIdTypeLogicalUnitGroup = VDS_STORAGE_IDENTIFIER_TYPE.LogicalUnitGroup;
pub const VDSStorageIdTypeMD5LogicalUnitIdentifier = VDS_STORAGE_IDENTIFIER_TYPE.MD5LogicalUnitIdentifier;
pub const VDSStorageIdTypeScsiNameString = VDS_STORAGE_IDENTIFIER_TYPE.ScsiNameString;
pub const VDS_STORAGE_BUS_TYPE = enum(i32) {
Unknown = 0,
Scsi = 1,
Atapi = 2,
Ata = 3,
@"1394" = 4,
Ssa = 5,
Fibre = 6,
Usb = 7,
RAID = 8,
iScsi = 9,
Sas = 10,
Sata = 11,
Sd = 12,
Mmc = 13,
Max = 14,
// Virtual = 14, this enum value conflicts with Max
FileBackedVirtual = 15,
Spaces = 16,
NVMe = 17,
Scm = 18,
Ufs = 19,
MaxReserved = 127,
};
pub const VDSBusTypeUnknown = VDS_STORAGE_BUS_TYPE.Unknown;
pub const VDSBusTypeScsi = VDS_STORAGE_BUS_TYPE.Scsi;
pub const VDSBusTypeAtapi = VDS_STORAGE_BUS_TYPE.Atapi;
pub const VDSBusTypeAta = VDS_STORAGE_BUS_TYPE.Ata;
pub const VDSBusType1394 = VDS_STORAGE_BUS_TYPE.@"1394";
pub const VDSBusTypeSsa = VDS_STORAGE_BUS_TYPE.Ssa;
pub const VDSBusTypeFibre = VDS_STORAGE_BUS_TYPE.Fibre;
pub const VDSBusTypeUsb = VDS_STORAGE_BUS_TYPE.Usb;
pub const VDSBusTypeRAID = VDS_STORAGE_BUS_TYPE.RAID;
pub const VDSBusTypeiScsi = VDS_STORAGE_BUS_TYPE.iScsi;
pub const VDSBusTypeSas = VDS_STORAGE_BUS_TYPE.Sas;
pub const VDSBusTypeSata = VDS_STORAGE_BUS_TYPE.Sata;
pub const VDSBusTypeSd = VDS_STORAGE_BUS_TYPE.Sd;
pub const VDSBusTypeMmc = VDS_STORAGE_BUS_TYPE.Mmc;
pub const VDSBusTypeMax = VDS_STORAGE_BUS_TYPE.Max;
pub const VDSBusTypeVirtual = VDS_STORAGE_BUS_TYPE.Max;
pub const VDSBusTypeFileBackedVirtual = VDS_STORAGE_BUS_TYPE.FileBackedVirtual;
pub const VDSBusTypeSpaces = VDS_STORAGE_BUS_TYPE.Spaces;
pub const VDSBusTypeNVMe = VDS_STORAGE_BUS_TYPE.NVMe;
pub const VDSBusTypeScm = VDS_STORAGE_BUS_TYPE.Scm;
pub const VDSBusTypeUfs = VDS_STORAGE_BUS_TYPE.Ufs;
pub const VDSBusTypeMaxReserved = VDS_STORAGE_BUS_TYPE.MaxReserved;
pub const VDS_STORAGE_IDENTIFIER = extern struct {
m_CodeSet: VDS_STORAGE_IDENTIFIER_CODE_SET,
m_Type: VDS_STORAGE_IDENTIFIER_TYPE,
m_cbIdentifier: u32,
m_rgbIdentifier: ?*u8,
};
pub const VDS_STORAGE_DEVICE_ID_DESCRIPTOR = extern struct {
m_version: u32,
m_cIdentifiers: u32,
m_rgIdentifiers: ?*VDS_STORAGE_IDENTIFIER,
};
pub const VDS_INTERCONNECT_ADDRESS_TYPE = enum(i32) {
UNKNOWN = 0,
FCFS = 1,
FCPH = 2,
FCPH3 = 3,
MAC = 4,
SCSI = 5,
};
pub const VDS_IA_UNKNOWN = VDS_INTERCONNECT_ADDRESS_TYPE.UNKNOWN;
pub const VDS_IA_FCFS = VDS_INTERCONNECT_ADDRESS_TYPE.FCFS;
pub const VDS_IA_FCPH = VDS_INTERCONNECT_ADDRESS_TYPE.FCPH;
pub const VDS_IA_FCPH3 = VDS_INTERCONNECT_ADDRESS_TYPE.FCPH3;
pub const VDS_IA_MAC = VDS_INTERCONNECT_ADDRESS_TYPE.MAC;
pub const VDS_IA_SCSI = VDS_INTERCONNECT_ADDRESS_TYPE.SCSI;
pub const VDS_INTERCONNECT = extern struct {
m_addressType: VDS_INTERCONNECT_ADDRESS_TYPE,
m_cbPort: u32,
m_pbPort: ?*u8,
m_cbAddress: u32,
m_pbAddress: ?*u8,
};
pub const VDS_LUN_INFORMATION = extern struct {
m_version: u32,
m_DeviceType: u8,
m_DeviceTypeModifier: u8,
m_bCommandQueueing: BOOL,
m_BusType: VDS_STORAGE_BUS_TYPE,
m_szVendorId: ?*u8,
m_szProductId: ?*u8,
m_szProductRevision: ?*u8,
m_szSerialNumber: ?*u8,
m_diskSignature: Guid,
m_deviceIdDescriptor: VDS_STORAGE_DEVICE_ID_DESCRIPTOR,
m_cInterconnects: u32,
m_rgInterconnects: ?*VDS_INTERCONNECT,
};
pub const VDS_OBJECT_TYPE = enum(i32) {
UNKNOWN = 0,
PROVIDER = 1,
PACK = 10,
VOLUME = 11,
VOLUME_PLEX = 12,
DISK = 13,
SUB_SYSTEM = 30,
CONTROLLER = 31,
DRIVE = 32,
LUN = 33,
LUN_PLEX = 34,
PORT = 35,
PORTAL = 36,
TARGET = 37,
PORTAL_GROUP = 38,
STORAGE_POOL = 39,
HBAPORT = 90,
INIT_ADAPTER = 91,
INIT_PORTAL = 92,
ASYNC = 100,
ENUM = 101,
VDISK = 200,
OPEN_VDISK = 201,
};
pub const VDS_OT_UNKNOWN = VDS_OBJECT_TYPE.UNKNOWN;
pub const VDS_OT_PROVIDER = VDS_OBJECT_TYPE.PROVIDER;
pub const VDS_OT_PACK = VDS_OBJECT_TYPE.PACK;
pub const VDS_OT_VOLUME = VDS_OBJECT_TYPE.VOLUME;
pub const VDS_OT_VOLUME_PLEX = VDS_OBJECT_TYPE.VOLUME_PLEX;
pub const VDS_OT_DISK = VDS_OBJECT_TYPE.DISK;
pub const VDS_OT_SUB_SYSTEM = VDS_OBJECT_TYPE.SUB_SYSTEM;
pub const VDS_OT_CONTROLLER = VDS_OBJECT_TYPE.CONTROLLER;
pub const VDS_OT_DRIVE = VDS_OBJECT_TYPE.DRIVE;
pub const VDS_OT_LUN = VDS_OBJECT_TYPE.LUN;
pub const VDS_OT_LUN_PLEX = VDS_OBJECT_TYPE.LUN_PLEX;
pub const VDS_OT_PORT = VDS_OBJECT_TYPE.PORT;
pub const VDS_OT_PORTAL = VDS_OBJECT_TYPE.PORTAL;
pub const VDS_OT_TARGET = VDS_OBJECT_TYPE.TARGET;
pub const VDS_OT_PORTAL_GROUP = VDS_OBJECT_TYPE.PORTAL_GROUP;
pub const VDS_OT_STORAGE_POOL = VDS_OBJECT_TYPE.STORAGE_POOL;
pub const VDS_OT_HBAPORT = VDS_OBJECT_TYPE.HBAPORT;
pub const VDS_OT_INIT_ADAPTER = VDS_OBJECT_TYPE.INIT_ADAPTER;
pub const VDS_OT_INIT_PORTAL = VDS_OBJECT_TYPE.INIT_PORTAL;
pub const VDS_OT_ASYNC = VDS_OBJECT_TYPE.ASYNC;
pub const VDS_OT_ENUM = VDS_OBJECT_TYPE.ENUM;
pub const VDS_OT_VDISK = VDS_OBJECT_TYPE.VDISK;
pub const VDS_OT_OPEN_VDISK = VDS_OBJECT_TYPE.OPEN_VDISK;
pub const VDS_PROVIDER_TYPE = enum(i32) {
UNKNOWN = 0,
SOFTWARE = 1,
HARDWARE = 2,
VIRTUALDISK = 3,
MAX = 4,
};
pub const VDS_PT_UNKNOWN = VDS_PROVIDER_TYPE.UNKNOWN;
pub const VDS_PT_SOFTWARE = VDS_PROVIDER_TYPE.SOFTWARE;
pub const VDS_PT_HARDWARE = VDS_PROVIDER_TYPE.HARDWARE;
pub const VDS_PT_VIRTUALDISK = VDS_PROVIDER_TYPE.VIRTUALDISK;
pub const VDS_PT_MAX = VDS_PROVIDER_TYPE.MAX;
pub const VDS_PROVIDER_FLAG = enum(i32) {
DYNAMIC = 1,
INTERNAL_HARDWARE_PROVIDER = 2,
ONE_DISK_ONLY_PER_PACK = 4,
ONE_PACK_ONLINE_ONLY = 8,
VOLUME_SPACE_MUST_BE_CONTIGUOUS = 16,
SUPPORT_DYNAMIC = -2147483648,
SUPPORT_FAULT_TOLERANT = 1073741824,
SUPPORT_DYNAMIC_1394 = 536870912,
SUPPORT_MIRROR = 32,
SUPPORT_RAID5 = 64,
};
pub const VDS_PF_DYNAMIC = VDS_PROVIDER_FLAG.DYNAMIC;
pub const VDS_PF_INTERNAL_HARDWARE_PROVIDER = VDS_PROVIDER_FLAG.INTERNAL_HARDWARE_PROVIDER;
pub const VDS_PF_ONE_DISK_ONLY_PER_PACK = VDS_PROVIDER_FLAG.ONE_DISK_ONLY_PER_PACK;
pub const VDS_PF_ONE_PACK_ONLINE_ONLY = VDS_PROVIDER_FLAG.ONE_PACK_ONLINE_ONLY;
pub const VDS_PF_VOLUME_SPACE_MUST_BE_CONTIGUOUS = VDS_PROVIDER_FLAG.VOLUME_SPACE_MUST_BE_CONTIGUOUS;
pub const VDS_PF_SUPPORT_DYNAMIC = VDS_PROVIDER_FLAG.SUPPORT_DYNAMIC;
pub const VDS_PF_SUPPORT_FAULT_TOLERANT = VDS_PROVIDER_FLAG.SUPPORT_FAULT_TOLERANT;
pub const VDS_PF_SUPPORT_DYNAMIC_1394 = VDS_PROVIDER_FLAG.SUPPORT_DYNAMIC_1394;
pub const VDS_PF_SUPPORT_MIRROR = VDS_PROVIDER_FLAG.SUPPORT_MIRROR;
pub const VDS_PF_SUPPORT_RAID5 = VDS_PROVIDER_FLAG.SUPPORT_RAID5;
pub const VDS_RECOVER_ACTION = enum(i32) {
UNKNOWN = 0,
REFRESH = 1,
RESTART = 2,
};
pub const VDS_RA_UNKNOWN = VDS_RECOVER_ACTION.UNKNOWN;
pub const VDS_RA_REFRESH = VDS_RECOVER_ACTION.REFRESH;
pub const VDS_RA_RESTART = VDS_RECOVER_ACTION.RESTART;
pub const VDS_NOTIFICATION_TARGET_TYPE = enum(i32) {
UNKNOWN = 0,
PACK = 10,
VOLUME = 11,
DISK = 13,
PARTITION = 60,
DRIVE_LETTER = 61,
FILE_SYSTEM = 62,
MOUNT_POINT = 63,
SUB_SYSTEM = 30,
CONTROLLER = 31,
DRIVE = 32,
LUN = 33,
PORT = 35,
PORTAL = 36,
TARGET = 37,
PORTAL_GROUP = 38,
SERVICE = 200,
};
pub const VDS_NTT_UNKNOWN = VDS_NOTIFICATION_TARGET_TYPE.UNKNOWN;
pub const VDS_NTT_PACK = VDS_NOTIFICATION_TARGET_TYPE.PACK;
pub const VDS_NTT_VOLUME = VDS_NOTIFICATION_TARGET_TYPE.VOLUME;
pub const VDS_NTT_DISK = VDS_NOTIFICATION_TARGET_TYPE.DISK;
pub const VDS_NTT_PARTITION = VDS_NOTIFICATION_TARGET_TYPE.PARTITION;
pub const VDS_NTT_DRIVE_LETTER = VDS_NOTIFICATION_TARGET_TYPE.DRIVE_LETTER;
pub const VDS_NTT_FILE_SYSTEM = VDS_NOTIFICATION_TARGET_TYPE.FILE_SYSTEM;
pub const VDS_NTT_MOUNT_POINT = VDS_NOTIFICATION_TARGET_TYPE.MOUNT_POINT;
pub const VDS_NTT_SUB_SYSTEM = VDS_NOTIFICATION_TARGET_TYPE.SUB_SYSTEM;
pub const VDS_NTT_CONTROLLER = VDS_NOTIFICATION_TARGET_TYPE.CONTROLLER;
pub const VDS_NTT_DRIVE = VDS_NOTIFICATION_TARGET_TYPE.DRIVE;
pub const VDS_NTT_LUN = VDS_NOTIFICATION_TARGET_TYPE.LUN;
pub const VDS_NTT_PORT = VDS_NOTIFICATION_TARGET_TYPE.PORT;
pub const VDS_NTT_PORTAL = VDS_NOTIFICATION_TARGET_TYPE.PORTAL;
pub const VDS_NTT_TARGET = VDS_NOTIFICATION_TARGET_TYPE.TARGET;
pub const VDS_NTT_PORTAL_GROUP = VDS_NOTIFICATION_TARGET_TYPE.PORTAL_GROUP;
pub const VDS_NTT_SERVICE = VDS_NOTIFICATION_TARGET_TYPE.SERVICE;
pub const VDS_PACK_NOTIFICATION = extern struct {
ulEvent: VDS_NF_PACK,
packId: Guid,
};
pub const VDS_DISK_NOTIFICATION = extern struct {
ulEvent: VDS_NF_DISK,
diskId: Guid,
};
pub const VDS_VOLUME_NOTIFICATION = extern struct {
ulEvent: u32,
volumeId: Guid,
plexId: Guid,
ulPercentCompleted: u32,
};
pub const VDS_PARTITION_NOTIFICATION = extern struct {
ulEvent: u32,
diskId: Guid,
ullOffset: u64,
};
pub const VDS_SERVICE_NOTIFICATION = extern struct {
ulEvent: u32,
action: VDS_RECOVER_ACTION,
};
pub const VDS_DRIVE_LETTER_NOTIFICATION = extern struct {
ulEvent: u32,
wcLetter: u16,
volumeId: Guid,
};
pub const VDS_FILE_SYSTEM_NOTIFICATION = extern struct {
ulEvent: VDS_NF_FILE_SYSTEM,
volumeId: Guid,
dwPercentCompleted: u32,
};
pub const VDS_MOUNT_POINT_NOTIFICATION = extern struct {
ulEvent: u32,
volumeId: Guid,
};
pub const VDS_SUB_SYSTEM_NOTIFICATION = extern struct {
ulEvent: u32,
subSystemId: Guid,
};
pub const VDS_CONTROLLER_NOTIFICATION = extern struct {
ulEvent: VDS_NF_CONTROLLER,
controllerId: Guid,
};
pub const VDS_DRIVE_NOTIFICATION = extern struct {
ulEvent: VDS_NF_DRIVE,
driveId: Guid,
};
pub const VDS_LUN_NOTIFICATION = extern struct {
ulEvent: VDS_NF_LUN,
LunId: Guid,
};
pub const VDS_PORT_NOTIFICATION = extern struct {
ulEvent: VDS_NF_PORT,
portId: Guid,
};
pub const VDS_PORTAL_NOTIFICATION = extern struct {
ulEvent: u32,
portalId: Guid,
};
pub const VDS_TARGET_NOTIFICATION = extern struct {
ulEvent: u32,
targetId: Guid,
};
pub const VDS_PORTAL_GROUP_NOTIFICATION = extern struct {
ulEvent: u32,
portalGroupId: Guid,
};
pub const VDS_NOTIFICATION = extern struct {
objectType: VDS_NOTIFICATION_TARGET_TYPE,
Anonymous: extern union {
Pack: VDS_PACK_NOTIFICATION,
Disk: VDS_DISK_NOTIFICATION,
Volume: VDS_VOLUME_NOTIFICATION,
Partition: VDS_PARTITION_NOTIFICATION,
Letter: VDS_DRIVE_LETTER_NOTIFICATION,
FileSystem: VDS_FILE_SYSTEM_NOTIFICATION,
MountPoint: VDS_MOUNT_POINT_NOTIFICATION,
SubSystem: VDS_SUB_SYSTEM_NOTIFICATION,
Controller: VDS_CONTROLLER_NOTIFICATION,
Drive: VDS_DRIVE_NOTIFICATION,
Lun: VDS_LUN_NOTIFICATION,
Port: VDS_PORT_NOTIFICATION,
Portal: VDS_PORTAL_NOTIFICATION,
Target: VDS_TARGET_NOTIFICATION,
PortalGroup: VDS_PORTAL_GROUP_NOTIFICATION,
Service: VDS_SERVICE_NOTIFICATION,
},
};
pub const VDS_ASYNC_OUTPUT_TYPE = enum(i32) {
UNKNOWN = 0,
CREATEVOLUME = 1,
EXTENDVOLUME = 2,
SHRINKVOLUME = 3,
ADDVOLUMEPLEX = 4,
BREAKVOLUMEPLEX = 5,
REMOVEVOLUMEPLEX = 6,
REPAIRVOLUMEPLEX = 7,
RECOVERPACK = 8,
REPLACEDISK = 9,
CREATEPARTITION = 10,
CLEAN = 11,
CREATELUN = 50,
ADDLUNPLEX = 52,
REMOVELUNPLEX = 53,
EXTENDLUN = 54,
SHRINKLUN = 55,
RECOVERLUN = 56,
LOGINTOTARGET = 60,
LOGOUTFROMTARGET = 61,
CREATETARGET = 62,
CREATEPORTALGROUP = 63,
DELETETARGET = 64,
ADDPORTAL = 65,
REMOVEPORTAL = 66,
DELETEPORTALGROUP = 67,
FORMAT = 101,
CREATE_VDISK = 200,
ATTACH_VDISK = 201,
COMPACT_VDISK = 202,
MERGE_VDISK = 203,
EXPAND_VDISK = 204,
};
pub const VDS_ASYNCOUT_UNKNOWN = VDS_ASYNC_OUTPUT_TYPE.UNKNOWN;
pub const VDS_ASYNCOUT_CREATEVOLUME = VDS_ASYNC_OUTPUT_TYPE.CREATEVOLUME;
pub const VDS_ASYNCOUT_EXTENDVOLUME = VDS_ASYNC_OUTPUT_TYPE.EXTENDVOLUME;
pub const VDS_ASYNCOUT_SHRINKVOLUME = VDS_ASYNC_OUTPUT_TYPE.SHRINKVOLUME;
pub const VDS_ASYNCOUT_ADDVOLUMEPLEX = VDS_ASYNC_OUTPUT_TYPE.ADDVOLUMEPLEX;
pub const VDS_ASYNCOUT_BREAKVOLUMEPLEX = VDS_ASYNC_OUTPUT_TYPE.BREAKVOLUMEPLEX;
pub const VDS_ASYNCOUT_REMOVEVOLUMEPLEX = VDS_ASYNC_OUTPUT_TYPE.REMOVEVOLUMEPLEX;
pub const VDS_ASYNCOUT_REPAIRVOLUMEPLEX = VDS_ASYNC_OUTPUT_TYPE.REPAIRVOLUMEPLEX;
pub const VDS_ASYNCOUT_RECOVERPACK = VDS_ASYNC_OUTPUT_TYPE.RECOVERPACK;
pub const VDS_ASYNCOUT_REPLACEDISK = VDS_ASYNC_OUTPUT_TYPE.REPLACEDISK;
pub const VDS_ASYNCOUT_CREATEPARTITION = VDS_ASYNC_OUTPUT_TYPE.CREATEPARTITION;
pub const VDS_ASYNCOUT_CLEAN = VDS_ASYNC_OUTPUT_TYPE.CLEAN;
pub const VDS_ASYNCOUT_CREATELUN = VDS_ASYNC_OUTPUT_TYPE.CREATELUN;
pub const VDS_ASYNCOUT_ADDLUNPLEX = VDS_ASYNC_OUTPUT_TYPE.ADDLUNPLEX;
pub const VDS_ASYNCOUT_REMOVELUNPLEX = VDS_ASYNC_OUTPUT_TYPE.REMOVELUNPLEX;
pub const VDS_ASYNCOUT_EXTENDLUN = VDS_ASYNC_OUTPUT_TYPE.EXTENDLUN;
pub const VDS_ASYNCOUT_SHRINKLUN = VDS_ASYNC_OUTPUT_TYPE.SHRINKLUN;
pub const VDS_ASYNCOUT_RECOVERLUN = VDS_ASYNC_OUTPUT_TYPE.RECOVERLUN;
pub const VDS_ASYNCOUT_LOGINTOTARGET = VDS_ASYNC_OUTPUT_TYPE.LOGINTOTARGET;
pub const VDS_ASYNCOUT_LOGOUTFROMTARGET = VDS_ASYNC_OUTPUT_TYPE.LOGOUTFROMTARGET;
pub const VDS_ASYNCOUT_CREATETARGET = VDS_ASYNC_OUTPUT_TYPE.CREATETARGET;
pub const VDS_ASYNCOUT_CREATEPORTALGROUP = VDS_ASYNC_OUTPUT_TYPE.CREATEPORTALGROUP;
pub const VDS_ASYNCOUT_DELETETARGET = VDS_ASYNC_OUTPUT_TYPE.DELETETARGET;
pub const VDS_ASYNCOUT_ADDPORTAL = VDS_ASYNC_OUTPUT_TYPE.ADDPORTAL;
pub const VDS_ASYNCOUT_REMOVEPORTAL = VDS_ASYNC_OUTPUT_TYPE.REMOVEPORTAL;
pub const VDS_ASYNCOUT_DELETEPORTALGROUP = VDS_ASYNC_OUTPUT_TYPE.DELETEPORTALGROUP;
pub const VDS_ASYNCOUT_FORMAT = VDS_ASYNC_OUTPUT_TYPE.FORMAT;
pub const VDS_ASYNCOUT_CREATE_VDISK = VDS_ASYNC_OUTPUT_TYPE.CREATE_VDISK;
pub const VDS_ASYNCOUT_ATTACH_VDISK = VDS_ASYNC_OUTPUT_TYPE.ATTACH_VDISK;
pub const VDS_ASYNCOUT_COMPACT_VDISK = VDS_ASYNC_OUTPUT_TYPE.COMPACT_VDISK;
pub const VDS_ASYNCOUT_MERGE_VDISK = VDS_ASYNC_OUTPUT_TYPE.MERGE_VDISK;
pub const VDS_ASYNCOUT_EXPAND_VDISK = VDS_ASYNC_OUTPUT_TYPE.EXPAND_VDISK;
pub const VDS_ASYNC_OUTPUT = extern struct {
type: VDS_ASYNC_OUTPUT_TYPE,
Anonymous: extern union {
pub const _cpg = extern struct {
pPortalGroupUnk: ?*IUnknown,
};
pub const _cl = extern struct {
pLunUnk: ?*IUnknown,
};
pub const _bvp = extern struct {
pVolumeUnk: ?*IUnknown,
};
pub const _cp = extern struct {
ullOffset: u64,
volumeId: Guid,
};
pub const _cvd = extern struct {
pVDiskUnk: ?*IUnknown,
};
pub const _sv = extern struct {
ullReclaimedBytes: u64,
};
pub const _ct = extern struct {
pTargetUnk: ?*IUnknown,
};
pub const _cv = extern struct {
pVolumeUnk: ?*IUnknown,
};
cp: _cp,
cv: _cv,
bvp: _bvp,
sv: _sv,
cl: _cl,
ct: _ct,
cpg: _cpg,
cvd: _cvd,
},
};
pub const VDS_IPADDRESS_TYPE = enum(i32) {
TEXT = 0,
IPV4 = 1,
IPV6 = 2,
EMPTY = 3,
};
pub const VDS_IPT_TEXT = VDS_IPADDRESS_TYPE.TEXT;
pub const VDS_IPT_IPV4 = VDS_IPADDRESS_TYPE.IPV4;
pub const VDS_IPT_IPV6 = VDS_IPADDRESS_TYPE.IPV6;
pub const VDS_IPT_EMPTY = VDS_IPADDRESS_TYPE.EMPTY;
pub const VDS_HEALTH = enum(i32) {
UNKNOWN = 0,
HEALTHY = 1,
REBUILDING = 2,
STALE = 3,
FAILING = 4,
FAILING_REDUNDANCY = 5,
FAILED_REDUNDANCY = 6,
FAILED_REDUNDANCY_FAILING = 7,
FAILED = 8,
REPLACED = 9,
PENDING_FAILURE = 10,
DEGRADED = 11,
};
pub const VDS_H_UNKNOWN = VDS_HEALTH.UNKNOWN;
pub const VDS_H_HEALTHY = VDS_HEALTH.HEALTHY;
pub const VDS_H_REBUILDING = VDS_HEALTH.REBUILDING;
pub const VDS_H_STALE = VDS_HEALTH.STALE;
pub const VDS_H_FAILING = VDS_HEALTH.FAILING;
pub const VDS_H_FAILING_REDUNDANCY = VDS_HEALTH.FAILING_REDUNDANCY;
pub const VDS_H_FAILED_REDUNDANCY = VDS_HEALTH.FAILED_REDUNDANCY;
pub const VDS_H_FAILED_REDUNDANCY_FAILING = VDS_HEALTH.FAILED_REDUNDANCY_FAILING;
pub const VDS_H_FAILED = VDS_HEALTH.FAILED;
pub const VDS_H_REPLACED = VDS_HEALTH.REPLACED;
pub const VDS_H_PENDING_FAILURE = VDS_HEALTH.PENDING_FAILURE;
pub const VDS_H_DEGRADED = VDS_HEALTH.DEGRADED;
pub const VDS_TRANSITION_STATE = enum(i32) {
UNKNOWN = 0,
STABLE = 1,
EXTENDING = 2,
SHRINKING = 3,
RECONFIGING = 4,
RESTRIPING = 5,
};
pub const VDS_TS_UNKNOWN = VDS_TRANSITION_STATE.UNKNOWN;
pub const VDS_TS_STABLE = VDS_TRANSITION_STATE.STABLE;
pub const VDS_TS_EXTENDING = VDS_TRANSITION_STATE.EXTENDING;
pub const VDS_TS_SHRINKING = VDS_TRANSITION_STATE.SHRINKING;
pub const VDS_TS_RECONFIGING = VDS_TRANSITION_STATE.RECONFIGING;
pub const VDS_TS_RESTRIPING = VDS_TRANSITION_STATE.RESTRIPING;
pub const VDS_FILE_SYSTEM_TYPE = enum(i32) {
UNKNOWN = 0,
RAW = 1,
FAT = 2,
FAT32 = 3,
NTFS = 4,
CDFS = 5,
UDF = 6,
EXFAT = 7,
CSVFS = 8,
REFS = 9,
};
pub const VDS_FST_UNKNOWN = VDS_FILE_SYSTEM_TYPE.UNKNOWN;
pub const VDS_FST_RAW = VDS_FILE_SYSTEM_TYPE.RAW;
pub const VDS_FST_FAT = VDS_FILE_SYSTEM_TYPE.FAT;
pub const VDS_FST_FAT32 = VDS_FILE_SYSTEM_TYPE.FAT32;
pub const VDS_FST_NTFS = VDS_FILE_SYSTEM_TYPE.NTFS;
pub const VDS_FST_CDFS = VDS_FILE_SYSTEM_TYPE.CDFS;
pub const VDS_FST_UDF = VDS_FILE_SYSTEM_TYPE.UDF;
pub const VDS_FST_EXFAT = VDS_FILE_SYSTEM_TYPE.EXFAT;
pub const VDS_FST_CSVFS = VDS_FILE_SYSTEM_TYPE.CSVFS;
pub const VDS_FST_REFS = VDS_FILE_SYSTEM_TYPE.REFS;
pub const VDS_HBAPORT_TYPE = enum(i32) {
UNKNOWN = 1,
OTHER = 2,
NOTPRESENT = 3,
NPORT = 5,
NLPORT = 6,
FLPORT = 7,
FPORT = 8,
EPORT = 9,
GPORT = 10,
LPORT = 20,
PTP = 21,
};
pub const VDS_HPT_UNKNOWN = VDS_HBAPORT_TYPE.UNKNOWN;
pub const VDS_HPT_OTHER = VDS_HBAPORT_TYPE.OTHER;
pub const VDS_HPT_NOTPRESENT = VDS_HBAPORT_TYPE.NOTPRESENT;
pub const VDS_HPT_NPORT = VDS_HBAPORT_TYPE.NPORT;
pub const VDS_HPT_NLPORT = VDS_HBAPORT_TYPE.NLPORT;
pub const VDS_HPT_FLPORT = VDS_HBAPORT_TYPE.FLPORT;
pub const VDS_HPT_FPORT = VDS_HBAPORT_TYPE.FPORT;
pub const VDS_HPT_EPORT = VDS_HBAPORT_TYPE.EPORT;
pub const VDS_HPT_GPORT = VDS_HBAPORT_TYPE.GPORT;
pub const VDS_HPT_LPORT = VDS_HBAPORT_TYPE.LPORT;
pub const VDS_HPT_PTP = VDS_HBAPORT_TYPE.PTP;
pub const VDS_HBAPORT_STATUS = enum(i32) {
UNKNOWN = 1,
ONLINE = 2,
OFFLINE = 3,
BYPASSED = 4,
DIAGNOSTICS = 5,
LINKDOWN = 6,
ERROR = 7,
LOOPBACK = 8,
};
pub const VDS_HPS_UNKNOWN = VDS_HBAPORT_STATUS.UNKNOWN;
pub const VDS_HPS_ONLINE = VDS_HBAPORT_STATUS.ONLINE;
pub const VDS_HPS_OFFLINE = VDS_HBAPORT_STATUS.OFFLINE;
pub const VDS_HPS_BYPASSED = VDS_HBAPORT_STATUS.BYPASSED;
pub const VDS_HPS_DIAGNOSTICS = VDS_HBAPORT_STATUS.DIAGNOSTICS;
pub const VDS_HPS_LINKDOWN = VDS_HBAPORT_STATUS.LINKDOWN;
pub const VDS_HPS_ERROR = VDS_HBAPORT_STATUS.ERROR;
pub const VDS_HPS_LOOPBACK = VDS_HBAPORT_STATUS.LOOPBACK;
pub const VDS_HBAPORT_SPEED_FLAG = enum(i32) {
UNKNOWN = 0,
@"1GBIT" = 1,
@"2GBIT" = 2,
@"10GBIT" = 4,
@"4GBIT" = 8,
NOT_NEGOTIATED = 32768,
};
pub const VDS_HSF_UNKNOWN = VDS_HBAPORT_SPEED_FLAG.UNKNOWN;
pub const VDS_HSF_1GBIT = VDS_HBAPORT_SPEED_FLAG.@"1GBIT";
pub const VDS_HSF_2GBIT = VDS_HBAPORT_SPEED_FLAG.@"2GBIT";
pub const VDS_HSF_10GBIT = VDS_HBAPORT_SPEED_FLAG.@"10GBIT";
pub const VDS_HSF_4GBIT = VDS_HBAPORT_SPEED_FLAG.@"4GBIT";
pub const VDS_HSF_NOT_NEGOTIATED = VDS_HBAPORT_SPEED_FLAG.NOT_NEGOTIATED;
pub const VDS_PATH_STATUS = enum(i32) {
UNKNOWN = 0,
ONLINE = 1,
FAILED = 5,
STANDBY = 7,
};
pub const VDS_MPS_UNKNOWN = VDS_PATH_STATUS.UNKNOWN;
pub const VDS_MPS_ONLINE = VDS_PATH_STATUS.ONLINE;
pub const VDS_MPS_FAILED = VDS_PATH_STATUS.FAILED;
pub const VDS_MPS_STANDBY = VDS_PATH_STATUS.STANDBY;
pub const VDS_LOADBALANCE_POLICY_ENUM = enum(i32) {
UNKNOWN = 0,
FAILOVER = 1,
ROUND_ROBIN = 2,
ROUND_ROBIN_WITH_SUBSET = 3,
DYN_LEAST_QUEUE_DEPTH = 4,
WEIGHTED_PATHS = 5,
LEAST_BLOCKS = 6,
VENDOR_SPECIFIC = 7,
};
pub const VDS_LBP_UNKNOWN = VDS_LOADBALANCE_POLICY_ENUM.UNKNOWN;
pub const VDS_LBP_FAILOVER = VDS_LOADBALANCE_POLICY_ENUM.FAILOVER;
pub const VDS_LBP_ROUND_ROBIN = VDS_LOADBALANCE_POLICY_ENUM.ROUND_ROBIN;
pub const VDS_LBP_ROUND_ROBIN_WITH_SUBSET = VDS_LOADBALANCE_POLICY_ENUM.ROUND_ROBIN_WITH_SUBSET;
pub const VDS_LBP_DYN_LEAST_QUEUE_DEPTH = VDS_LOADBALANCE_POLICY_ENUM.DYN_LEAST_QUEUE_DEPTH;
pub const VDS_LBP_WEIGHTED_PATHS = VDS_LOADBALANCE_POLICY_ENUM.WEIGHTED_PATHS;
pub const VDS_LBP_LEAST_BLOCKS = VDS_LOADBALANCE_POLICY_ENUM.LEAST_BLOCKS;
pub const VDS_LBP_VENDOR_SPECIFIC = VDS_LOADBALANCE_POLICY_ENUM.VENDOR_SPECIFIC;
pub const VDS_PROVIDER_LBSUPPORT_FLAG = enum(i32) {
FAILOVER = 1,
ROUND_ROBIN = 2,
ROUND_ROBIN_WITH_SUBSET = 4,
DYN_LEAST_QUEUE_DEPTH = 8,
WEIGHTED_PATHS = 16,
LEAST_BLOCKS = 32,
VENDOR_SPECIFIC = 64,
};
pub const VDS_LBF_FAILOVER = VDS_PROVIDER_LBSUPPORT_FLAG.FAILOVER;
pub const VDS_LBF_ROUND_ROBIN = VDS_PROVIDER_LBSUPPORT_FLAG.ROUND_ROBIN;
pub const VDS_LBF_ROUND_ROBIN_WITH_SUBSET = VDS_PROVIDER_LBSUPPORT_FLAG.ROUND_ROBIN_WITH_SUBSET;
pub const VDS_LBF_DYN_LEAST_QUEUE_DEPTH = VDS_PROVIDER_LBSUPPORT_FLAG.DYN_LEAST_QUEUE_DEPTH;
pub const VDS_LBF_WEIGHTED_PATHS = VDS_PROVIDER_LBSUPPORT_FLAG.WEIGHTED_PATHS;
pub const VDS_LBF_LEAST_BLOCKS = VDS_PROVIDER_LBSUPPORT_FLAG.LEAST_BLOCKS;
pub const VDS_LBF_VENDOR_SPECIFIC = VDS_PROVIDER_LBSUPPORT_FLAG.VENDOR_SPECIFIC;
pub const VDS_VERSION_SUPPORT_FLAG = enum(i32) {
@"1_0" = 1,
@"1_1" = 2,
@"2_0" = 4,
@"2_1" = 8,
@"3_0" = 16,
};
pub const VDS_VSF_1_0 = VDS_VERSION_SUPPORT_FLAG.@"1_0";
pub const VDS_VSF_1_1 = VDS_VERSION_SUPPORT_FLAG.@"1_1";
pub const VDS_VSF_2_0 = VDS_VERSION_SUPPORT_FLAG.@"2_0";
pub const VDS_VSF_2_1 = VDS_VERSION_SUPPORT_FLAG.@"2_1";
pub const VDS_VSF_3_0 = VDS_VERSION_SUPPORT_FLAG.@"3_0";
pub const VDS_HWPROVIDER_TYPE = enum(i32) {
UNKNOWN = 0,
PCI_RAID = 1,
FIBRE_CHANNEL = 2,
ISCSI = 3,
SAS = 4,
HYBRID = 5,
};
pub const VDS_HWT_UNKNOWN = VDS_HWPROVIDER_TYPE.UNKNOWN;
pub const VDS_HWT_PCI_RAID = VDS_HWPROVIDER_TYPE.PCI_RAID;
pub const VDS_HWT_FIBRE_CHANNEL = VDS_HWPROVIDER_TYPE.FIBRE_CHANNEL;
pub const VDS_HWT_ISCSI = VDS_HWPROVIDER_TYPE.ISCSI;
pub const VDS_HWT_SAS = VDS_HWPROVIDER_TYPE.SAS;
pub const VDS_HWT_HYBRID = VDS_HWPROVIDER_TYPE.HYBRID;
pub const VDS_ISCSI_LOGIN_TYPE = enum(i32) {
MANUAL = 0,
PERSISTENT = 1,
BOOT = 2,
};
pub const VDS_ILT_MANUAL = VDS_ISCSI_LOGIN_TYPE.MANUAL;
pub const VDS_ILT_PERSISTENT = VDS_ISCSI_LOGIN_TYPE.PERSISTENT;
pub const VDS_ILT_BOOT = VDS_ISCSI_LOGIN_TYPE.BOOT;
pub const VDS_ISCSI_AUTH_TYPE = enum(i32) {
NONE = 0,
CHAP = 1,
MUTUAL_CHAP = 2,
};
pub const VDS_IAT_NONE = VDS_ISCSI_AUTH_TYPE.NONE;
pub const VDS_IAT_CHAP = VDS_ISCSI_AUTH_TYPE.CHAP;
pub const VDS_IAT_MUTUAL_CHAP = VDS_ISCSI_AUTH_TYPE.MUTUAL_CHAP;
pub const VDS_ISCSI_IPSEC_FLAG = enum(i32) {
VALID = 1,
IKE = 2,
MAIN_MODE = 4,
AGGRESSIVE_MODE = 8,
PFS_ENABLE = 16,
TRANSPORT_MODE_PREFERRED = 32,
TUNNEL_MODE_PREFERRED = 64,
};
pub const VDS_IIF_VALID = VDS_ISCSI_IPSEC_FLAG.VALID;
pub const VDS_IIF_IKE = VDS_ISCSI_IPSEC_FLAG.IKE;
pub const VDS_IIF_MAIN_MODE = VDS_ISCSI_IPSEC_FLAG.MAIN_MODE;
pub const VDS_IIF_AGGRESSIVE_MODE = VDS_ISCSI_IPSEC_FLAG.AGGRESSIVE_MODE;
pub const VDS_IIF_PFS_ENABLE = VDS_ISCSI_IPSEC_FLAG.PFS_ENABLE;
pub const VDS_IIF_TRANSPORT_MODE_PREFERRED = VDS_ISCSI_IPSEC_FLAG.TRANSPORT_MODE_PREFERRED;
pub const VDS_IIF_TUNNEL_MODE_PREFERRED = VDS_ISCSI_IPSEC_FLAG.TUNNEL_MODE_PREFERRED;
pub const VDS_ISCSI_LOGIN_FLAG = enum(i32) {
REQUIRE_IPSEC = 1,
MULTIPATH_ENABLED = 2,
};
pub const VDS_ILF_REQUIRE_IPSEC = VDS_ISCSI_LOGIN_FLAG.REQUIRE_IPSEC;
pub const VDS_ILF_MULTIPATH_ENABLED = VDS_ISCSI_LOGIN_FLAG.MULTIPATH_ENABLED;
pub const VDS_PATH_ID = extern struct {
ullSourceId: u64,
ullPathId: u64,
};
pub const VDS_WWN = extern struct {
rguchWwn: [8]u8,
};
pub const VDS_IPADDRESS = extern struct {
type: VDS_IPADDRESS_TYPE,
ipv4Address: u32,
ipv6Address: [16]u8,
ulIpv6FlowInfo: u32,
ulIpv6ScopeId: u32,
wszTextAddress: [257]u16,
ulPort: u32,
};
pub const VDS_ISCSI_IPSEC_KEY = extern struct {
pKey: ?*u8,
ulKeySize: u32,
};
pub const VDS_ISCSI_SHARED_SECRET = extern struct {
pSharedSecret: ?*u8,
ulSharedSecretSize: u32,
};
pub const VDS_HBAPORT_PROP = extern struct {
id: Guid,
wwnNode: VDS_WWN,
wwnPort: VDS_WWN,
type: VDS_HBAPORT_TYPE,
status: VDS_HBAPORT_STATUS,
ulPortSpeed: u32,
ulSupportedPortSpeed: u32,
};
pub const VDS_ISCSI_INITIATOR_ADAPTER_PROP = extern struct {
id: Guid,
pwszName: ?PWSTR,
};
pub const VDS_ISCSI_INITIATOR_PORTAL_PROP = extern struct {
id: Guid,
address: VDS_IPADDRESS,
ulPortIndex: u32,
};
pub const VDS_PROVIDER_PROP = extern struct {
id: Guid,
pwszName: ?PWSTR,
guidVersionId: Guid,
pwszVersion: ?PWSTR,
type: VDS_PROVIDER_TYPE,
ulFlags: u32,
ulStripeSizeFlags: u32,
sRebuildPriority: i16,
};
pub const VDS_PATH_INFO = extern struct {
pathId: VDS_PATH_ID,
type: VDS_HWPROVIDER_TYPE,
status: VDS_PATH_STATUS,
Anonymous1: extern union {
controllerPortId: Guid,
targetPortalId: Guid,
},
Anonymous2: extern union {
hbaPortId: Guid,
initiatorAdapterId: Guid,
},
Anonymous3: extern union {
pHbaPortProp: ?*VDS_HBAPORT_PROP,
pInitiatorPortalIpAddr: ?*VDS_IPADDRESS,
},
};
pub const VDS_PATH_POLICY = extern struct {
pathId: VDS_PATH_ID,
bPrimaryPath: BOOL,
ulWeight: u32,
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IEnumVdsObject_Value = Guid.initString("118610b7-8d94-4030-b5b8-500889788e4e");
pub const IID_IEnumVdsObject = &IID_IEnumVdsObject_Value;
pub const IEnumVdsObject = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Next: fn(
self: *const IEnumVdsObject,
celt: u32,
ppObjectArray: [*]?*IUnknown,
pcFetched: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Skip: fn(
self: *const IEnumVdsObject,
celt: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Reset: fn(
self: *const IEnumVdsObject,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Clone: fn(
self: *const IEnumVdsObject,
ppEnum: ?*?*IEnumVdsObject,
) 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 IEnumVdsObject_Next(self: *const T, celt: u32, ppObjectArray: [*]?*IUnknown, pcFetched: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumVdsObject.VTable, self.vtable).Next(@ptrCast(*const IEnumVdsObject, self), celt, ppObjectArray, pcFetched);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumVdsObject_Skip(self: *const T, celt: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumVdsObject.VTable, self.vtable).Skip(@ptrCast(*const IEnumVdsObject, self), celt);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumVdsObject_Reset(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumVdsObject.VTable, self.vtable).Reset(@ptrCast(*const IEnumVdsObject, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEnumVdsObject_Clone(self: *const T, ppEnum: ?*?*IEnumVdsObject) callconv(.Inline) HRESULT {
return @ptrCast(*const IEnumVdsObject.VTable, self.vtable).Clone(@ptrCast(*const IEnumVdsObject, self), ppEnum);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IVdsAsync_Value = Guid.initString("d5d23b6d-5a55-4492-9889-397a3c2d2dbc");
pub const IID_IVdsAsync = &IID_IVdsAsync_Value;
pub const IVdsAsync = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Cancel: fn(
self: *const IVdsAsync,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Wait: fn(
self: *const IVdsAsync,
pHrResult: ?*HRESULT,
pAsyncOut: ?*VDS_ASYNC_OUTPUT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
QueryStatus: fn(
self: *const IVdsAsync,
pHrResult: ?*HRESULT,
pulPercentCompleted: ?*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 IVdsAsync_Cancel(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsAsync.VTable, self.vtable).Cancel(@ptrCast(*const IVdsAsync, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsAsync_Wait(self: *const T, pHrResult: ?*HRESULT, pAsyncOut: ?*VDS_ASYNC_OUTPUT) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsAsync.VTable, self.vtable).Wait(@ptrCast(*const IVdsAsync, self), pHrResult, pAsyncOut);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsAsync_QueryStatus(self: *const T, pHrResult: ?*HRESULT, pulPercentCompleted: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsAsync.VTable, self.vtable).QueryStatus(@ptrCast(*const IVdsAsync, self), pHrResult, pulPercentCompleted);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IVdsAdviseSink_Value = Guid.initString("8326cd1d-cf59-4936-b786-5efc08798e25");
pub const IID_IVdsAdviseSink = &IID_IVdsAdviseSink_Value;
pub const IVdsAdviseSink = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
OnNotify: fn(
self: *const IVdsAdviseSink,
lNumberOfNotifications: i32,
pNotificationArray: [*]VDS_NOTIFICATION,
) 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 IVdsAdviseSink_OnNotify(self: *const T, lNumberOfNotifications: i32, pNotificationArray: [*]VDS_NOTIFICATION) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsAdviseSink.VTable, self.vtable).OnNotify(@ptrCast(*const IVdsAdviseSink, self), lNumberOfNotifications, pNotificationArray);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IVdsProvider_Value = Guid.initString("10c5e575-7984-4e81-a56b-431f5f92ae42");
pub const IID_IVdsProvider = &IID_IVdsProvider_Value;
pub const IVdsProvider = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetProperties: fn(
self: *const IVdsProvider,
pProviderProp: ?*VDS_PROVIDER_PROP,
) 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 IVdsProvider_GetProperties(self: *const T, pProviderProp: ?*VDS_PROVIDER_PROP) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsProvider.VTable, self.vtable).GetProperties(@ptrCast(*const IVdsProvider, self), pProviderProp);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IVdsProviderSupport_Value = Guid.initString("1732be13-e8f9-4a03-bfbc-5f616aa66ce1");
pub const IID_IVdsProviderSupport = &IID_IVdsProviderSupport_Value;
pub const IVdsProviderSupport = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetVersionSupport: fn(
self: *const IVdsProviderSupport,
ulVersionSupport: ?*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 IVdsProviderSupport_GetVersionSupport(self: *const T, ulVersionSupport: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsProviderSupport.VTable, self.vtable).GetVersionSupport(@ptrCast(*const IVdsProviderSupport, self), ulVersionSupport);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IVdsProviderPrivate_Value = Guid.initString("11f3cd41-b7e8-48ff-9472-9dff018aa292");
pub const IID_IVdsProviderPrivate = &IID_IVdsProviderPrivate_Value;
pub const IVdsProviderPrivate = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetObject: fn(
self: *const IVdsProviderPrivate,
ObjectId: Guid,
type: VDS_OBJECT_TYPE,
ppObjectUnk: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
OnLoad: fn(
self: *const IVdsProviderPrivate,
pwszMachineName: ?PWSTR,
pCallbackObject: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
OnUnload: fn(
self: *const IVdsProviderPrivate,
bForceUnload: 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 IVdsProviderPrivate_GetObject(self: *const T, ObjectId: Guid, type_: VDS_OBJECT_TYPE, ppObjectUnk: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsProviderPrivate.VTable, self.vtable).GetObject(@ptrCast(*const IVdsProviderPrivate, self), ObjectId, type_, ppObjectUnk);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsProviderPrivate_OnLoad(self: *const T, pwszMachineName: ?PWSTR, pCallbackObject: ?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsProviderPrivate.VTable, self.vtable).OnLoad(@ptrCast(*const IVdsProviderPrivate, self), pwszMachineName, pCallbackObject);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsProviderPrivate_OnUnload(self: *const T, bForceUnload: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsProviderPrivate.VTable, self.vtable).OnUnload(@ptrCast(*const IVdsProviderPrivate, self), bForceUnload);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const VDS_SUB_SYSTEM_STATUS = enum(i32) {
UNKNOWN = 0,
ONLINE = 1,
NOT_READY = 2,
OFFLINE = 4,
FAILED = 5,
PARTIALLY_MANAGED = 9,
};
pub const VDS_SSS_UNKNOWN = VDS_SUB_SYSTEM_STATUS.UNKNOWN;
pub const VDS_SSS_ONLINE = VDS_SUB_SYSTEM_STATUS.ONLINE;
pub const VDS_SSS_NOT_READY = VDS_SUB_SYSTEM_STATUS.NOT_READY;
pub const VDS_SSS_OFFLINE = VDS_SUB_SYSTEM_STATUS.OFFLINE;
pub const VDS_SSS_FAILED = VDS_SUB_SYSTEM_STATUS.FAILED;
pub const VDS_SSS_PARTIALLY_MANAGED = VDS_SUB_SYSTEM_STATUS.PARTIALLY_MANAGED;
pub const VDS_SUB_SYSTEM_FLAG = enum(i32) {
LUN_MASKING_CAPABLE = 1,
LUN_PLEXING_CAPABLE = 2,
LUN_REMAPPING_CAPABLE = 4,
DRIVE_EXTENT_CAPABLE = 8,
HARDWARE_CHECKSUM_CAPABLE = 16,
RADIUS_CAPABLE = 32,
READ_BACK_VERIFY_CAPABLE = 64,
WRITE_THROUGH_CACHING_CAPABLE = 128,
SUPPORTS_FAULT_TOLERANT_LUNS = 512,
SUPPORTS_NON_FAULT_TOLERANT_LUNS = 1024,
SUPPORTS_SIMPLE_LUNS = 2048,
SUPPORTS_SPAN_LUNS = 4096,
SUPPORTS_STRIPE_LUNS = 8192,
SUPPORTS_MIRROR_LUNS = 16384,
SUPPORTS_PARITY_LUNS = 32768,
SUPPORTS_AUTH_CHAP = 65536,
SUPPORTS_AUTH_MUTUAL_CHAP = 131072,
SUPPORTS_SIMPLE_TARGET_CONFIG = 262144,
SUPPORTS_LUN_NUMBER = 524288,
SUPPORTS_MIRRORED_CACHE = 1048576,
READ_CACHING_CAPABLE = 2097152,
WRITE_CACHING_CAPABLE = 4194304,
MEDIA_SCAN_CAPABLE = 8388608,
CONSISTENCY_CHECK_CAPABLE = 16777216,
};
pub const VDS_SF_LUN_MASKING_CAPABLE = VDS_SUB_SYSTEM_FLAG.LUN_MASKING_CAPABLE;
pub const VDS_SF_LUN_PLEXING_CAPABLE = VDS_SUB_SYSTEM_FLAG.LUN_PLEXING_CAPABLE;
pub const VDS_SF_LUN_REMAPPING_CAPABLE = VDS_SUB_SYSTEM_FLAG.LUN_REMAPPING_CAPABLE;
pub const VDS_SF_DRIVE_EXTENT_CAPABLE = VDS_SUB_SYSTEM_FLAG.DRIVE_EXTENT_CAPABLE;
pub const VDS_SF_HARDWARE_CHECKSUM_CAPABLE = VDS_SUB_SYSTEM_FLAG.HARDWARE_CHECKSUM_CAPABLE;
pub const VDS_SF_RADIUS_CAPABLE = VDS_SUB_SYSTEM_FLAG.RADIUS_CAPABLE;
pub const VDS_SF_READ_BACK_VERIFY_CAPABLE = VDS_SUB_SYSTEM_FLAG.READ_BACK_VERIFY_CAPABLE;
pub const VDS_SF_WRITE_THROUGH_CACHING_CAPABLE = VDS_SUB_SYSTEM_FLAG.WRITE_THROUGH_CACHING_CAPABLE;
pub const VDS_SF_SUPPORTS_FAULT_TOLERANT_LUNS = VDS_SUB_SYSTEM_FLAG.SUPPORTS_FAULT_TOLERANT_LUNS;
pub const VDS_SF_SUPPORTS_NON_FAULT_TOLERANT_LUNS = VDS_SUB_SYSTEM_FLAG.SUPPORTS_NON_FAULT_TOLERANT_LUNS;
pub const VDS_SF_SUPPORTS_SIMPLE_LUNS = VDS_SUB_SYSTEM_FLAG.SUPPORTS_SIMPLE_LUNS;
pub const VDS_SF_SUPPORTS_SPAN_LUNS = VDS_SUB_SYSTEM_FLAG.SUPPORTS_SPAN_LUNS;
pub const VDS_SF_SUPPORTS_STRIPE_LUNS = VDS_SUB_SYSTEM_FLAG.SUPPORTS_STRIPE_LUNS;
pub const VDS_SF_SUPPORTS_MIRROR_LUNS = VDS_SUB_SYSTEM_FLAG.SUPPORTS_MIRROR_LUNS;
pub const VDS_SF_SUPPORTS_PARITY_LUNS = VDS_SUB_SYSTEM_FLAG.SUPPORTS_PARITY_LUNS;
pub const VDS_SF_SUPPORTS_AUTH_CHAP = VDS_SUB_SYSTEM_FLAG.SUPPORTS_AUTH_CHAP;
pub const VDS_SF_SUPPORTS_AUTH_MUTUAL_CHAP = VDS_SUB_SYSTEM_FLAG.SUPPORTS_AUTH_MUTUAL_CHAP;
pub const VDS_SF_SUPPORTS_SIMPLE_TARGET_CONFIG = VDS_SUB_SYSTEM_FLAG.SUPPORTS_SIMPLE_TARGET_CONFIG;
pub const VDS_SF_SUPPORTS_LUN_NUMBER = VDS_SUB_SYSTEM_FLAG.SUPPORTS_LUN_NUMBER;
pub const VDS_SF_SUPPORTS_MIRRORED_CACHE = VDS_SUB_SYSTEM_FLAG.SUPPORTS_MIRRORED_CACHE;
pub const VDS_SF_READ_CACHING_CAPABLE = VDS_SUB_SYSTEM_FLAG.READ_CACHING_CAPABLE;
pub const VDS_SF_WRITE_CACHING_CAPABLE = VDS_SUB_SYSTEM_FLAG.WRITE_CACHING_CAPABLE;
pub const VDS_SF_MEDIA_SCAN_CAPABLE = VDS_SUB_SYSTEM_FLAG.MEDIA_SCAN_CAPABLE;
pub const VDS_SF_CONSISTENCY_CHECK_CAPABLE = VDS_SUB_SYSTEM_FLAG.CONSISTENCY_CHECK_CAPABLE;
pub const VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG = enum(i32) {
@"2_LUNS" = 1,
@"3_LUNS" = 2,
@"4_LUNS" = 4,
@"5_LUNS" = 8,
@"6_LUNS" = 16,
@"01_LUNS" = 32,
@"03_LUNS" = 64,
@"05_LUNS" = 128,
@"10_LUNS" = 256,
@"15_LUNS" = 512,
@"30_LUNS" = 1024,
@"50_LUNS" = 2048,
@"51_LUNS" = 4096,
@"53_LUNS" = 8192,
@"60_LUNS" = 16384,
@"61_LUNS" = 32768,
};
pub const VDS_SF_SUPPORTS_RAID2_LUNS = VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG.@"2_LUNS";
pub const VDS_SF_SUPPORTS_RAID3_LUNS = VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG.@"3_LUNS";
pub const VDS_SF_SUPPORTS_RAID4_LUNS = VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG.@"4_LUNS";
pub const VDS_SF_SUPPORTS_RAID5_LUNS = VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG.@"5_LUNS";
pub const VDS_SF_SUPPORTS_RAID6_LUNS = VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG.@"6_LUNS";
pub const VDS_SF_SUPPORTS_RAID01_LUNS = VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG.@"01_LUNS";
pub const VDS_SF_SUPPORTS_RAID03_LUNS = VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG.@"03_LUNS";
pub const VDS_SF_SUPPORTS_RAID05_LUNS = VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG.@"05_LUNS";
pub const VDS_SF_SUPPORTS_RAID10_LUNS = VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG.@"10_LUNS";
pub const VDS_SF_SUPPORTS_RAID15_LUNS = VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG.@"15_LUNS";
pub const VDS_SF_SUPPORTS_RAID30_LUNS = VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG.@"30_LUNS";
pub const VDS_SF_SUPPORTS_RAID50_LUNS = VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG.@"50_LUNS";
pub const VDS_SF_SUPPORTS_RAID51_LUNS = VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG.@"51_LUNS";
pub const VDS_SF_SUPPORTS_RAID53_LUNS = VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG.@"53_LUNS";
pub const VDS_SF_SUPPORTS_RAID60_LUNS = VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG.@"60_LUNS";
pub const VDS_SF_SUPPORTS_RAID61_LUNS = VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG.@"61_LUNS";
pub const VDS_INTERCONNECT_FLAG = enum(i32) {
PCI_RAID = 1,
FIBRE_CHANNEL = 2,
ISCSI = 4,
SAS = 8,
};
pub const VDS_ITF_PCI_RAID = VDS_INTERCONNECT_FLAG.PCI_RAID;
pub const VDS_ITF_FIBRE_CHANNEL = VDS_INTERCONNECT_FLAG.FIBRE_CHANNEL;
pub const VDS_ITF_ISCSI = VDS_INTERCONNECT_FLAG.ISCSI;
pub const VDS_ITF_SAS = VDS_INTERCONNECT_FLAG.SAS;
pub const VDS_CONTROLLER_STATUS = enum(i32) {
UNKNOWN = 0,
ONLINE = 1,
NOT_READY = 2,
OFFLINE = 4,
FAILED = 5,
REMOVED = 8,
};
pub const VDS_CS_UNKNOWN = VDS_CONTROLLER_STATUS.UNKNOWN;
pub const VDS_CS_ONLINE = VDS_CONTROLLER_STATUS.ONLINE;
pub const VDS_CS_NOT_READY = VDS_CONTROLLER_STATUS.NOT_READY;
pub const VDS_CS_OFFLINE = VDS_CONTROLLER_STATUS.OFFLINE;
pub const VDS_CS_FAILED = VDS_CONTROLLER_STATUS.FAILED;
pub const VDS_CS_REMOVED = VDS_CONTROLLER_STATUS.REMOVED;
pub const VDS_PORT_STATUS = enum(i32) {
UNKNOWN = 0,
ONLINE = 1,
NOT_READY = 2,
OFFLINE = 4,
FAILED = 5,
REMOVED = 8,
};
pub const VDS_PRS_UNKNOWN = VDS_PORT_STATUS.UNKNOWN;
pub const VDS_PRS_ONLINE = VDS_PORT_STATUS.ONLINE;
pub const VDS_PRS_NOT_READY = VDS_PORT_STATUS.NOT_READY;
pub const VDS_PRS_OFFLINE = VDS_PORT_STATUS.OFFLINE;
pub const VDS_PRS_FAILED = VDS_PORT_STATUS.FAILED;
pub const VDS_PRS_REMOVED = VDS_PORT_STATUS.REMOVED;
pub const VDS_DRIVE_STATUS = enum(i32) {
UNKNOWN = 0,
ONLINE = 1,
NOT_READY = 2,
OFFLINE = 4,
FAILED = 5,
REMOVED = 8,
};
pub const VDS_DRS_UNKNOWN = VDS_DRIVE_STATUS.UNKNOWN;
pub const VDS_DRS_ONLINE = VDS_DRIVE_STATUS.ONLINE;
pub const VDS_DRS_NOT_READY = VDS_DRIVE_STATUS.NOT_READY;
pub const VDS_DRS_OFFLINE = VDS_DRIVE_STATUS.OFFLINE;
pub const VDS_DRS_FAILED = VDS_DRIVE_STATUS.FAILED;
pub const VDS_DRS_REMOVED = VDS_DRIVE_STATUS.REMOVED;
pub const VDS_DRIVE_FLAG = enum(i32) {
HOTSPARE = 1,
ASSIGNED = 2,
UNASSIGNED = 4,
HOTSPARE_IN_USE = 8,
HOTSPARE_STANDBY = 16,
};
pub const VDS_DRF_HOTSPARE = VDS_DRIVE_FLAG.HOTSPARE;
pub const VDS_DRF_ASSIGNED = VDS_DRIVE_FLAG.ASSIGNED;
pub const VDS_DRF_UNASSIGNED = VDS_DRIVE_FLAG.UNASSIGNED;
pub const VDS_DRF_HOTSPARE_IN_USE = VDS_DRIVE_FLAG.HOTSPARE_IN_USE;
pub const VDS_DRF_HOTSPARE_STANDBY = VDS_DRIVE_FLAG.HOTSPARE_STANDBY;
pub const VDS_LUN_TYPE = enum(i32) {
UNKNOWN = 0,
DEFAULT = 1,
FAULT_TOLERANT = 2,
NON_FAULT_TOLERANT = 3,
SIMPLE = 10,
SPAN = 11,
STRIPE = 12,
MIRROR = 13,
PARITY = 14,
RAID2 = 15,
RAID3 = 16,
RAID4 = 17,
RAID5 = 18,
RAID6 = 19,
RAID01 = 20,
RAID03 = 21,
RAID05 = 22,
RAID10 = 23,
RAID15 = 24,
RAID30 = 25,
RAID50 = 26,
RAID51 = 27,
RAID53 = 28,
RAID60 = 29,
RAID61 = 30,
};
pub const VDS_LT_UNKNOWN = VDS_LUN_TYPE.UNKNOWN;
pub const VDS_LT_DEFAULT = VDS_LUN_TYPE.DEFAULT;
pub const VDS_LT_FAULT_TOLERANT = VDS_LUN_TYPE.FAULT_TOLERANT;
pub const VDS_LT_NON_FAULT_TOLERANT = VDS_LUN_TYPE.NON_FAULT_TOLERANT;
pub const VDS_LT_SIMPLE = VDS_LUN_TYPE.SIMPLE;
pub const VDS_LT_SPAN = VDS_LUN_TYPE.SPAN;
pub const VDS_LT_STRIPE = VDS_LUN_TYPE.STRIPE;
pub const VDS_LT_MIRROR = VDS_LUN_TYPE.MIRROR;
pub const VDS_LT_PARITY = VDS_LUN_TYPE.PARITY;
pub const VDS_LT_RAID2 = VDS_LUN_TYPE.RAID2;
pub const VDS_LT_RAID3 = VDS_LUN_TYPE.RAID3;
pub const VDS_LT_RAID4 = VDS_LUN_TYPE.RAID4;
pub const VDS_LT_RAID5 = VDS_LUN_TYPE.RAID5;
pub const VDS_LT_RAID6 = VDS_LUN_TYPE.RAID6;
pub const VDS_LT_RAID01 = VDS_LUN_TYPE.RAID01;
pub const VDS_LT_RAID03 = VDS_LUN_TYPE.RAID03;
pub const VDS_LT_RAID05 = VDS_LUN_TYPE.RAID05;
pub const VDS_LT_RAID10 = VDS_LUN_TYPE.RAID10;
pub const VDS_LT_RAID15 = VDS_LUN_TYPE.RAID15;
pub const VDS_LT_RAID30 = VDS_LUN_TYPE.RAID30;
pub const VDS_LT_RAID50 = VDS_LUN_TYPE.RAID50;
pub const VDS_LT_RAID51 = VDS_LUN_TYPE.RAID51;
pub const VDS_LT_RAID53 = VDS_LUN_TYPE.RAID53;
pub const VDS_LT_RAID60 = VDS_LUN_TYPE.RAID60;
pub const VDS_LT_RAID61 = VDS_LUN_TYPE.RAID61;
pub const VDS_LUN_STATUS = enum(i32) {
UNKNOWN = 0,
ONLINE = 1,
NOT_READY = 2,
OFFLINE = 4,
FAILED = 5,
};
pub const VDS_LS_UNKNOWN = VDS_LUN_STATUS.UNKNOWN;
pub const VDS_LS_ONLINE = VDS_LUN_STATUS.ONLINE;
pub const VDS_LS_NOT_READY = VDS_LUN_STATUS.NOT_READY;
pub const VDS_LS_OFFLINE = VDS_LUN_STATUS.OFFLINE;
pub const VDS_LS_FAILED = VDS_LUN_STATUS.FAILED;
pub const VDS_LUN_FLAG = enum(i32) {
LBN_REMAP_ENABLED = 1,
READ_BACK_VERIFY_ENABLED = 2,
WRITE_THROUGH_CACHING_ENABLED = 4,
HARDWARE_CHECKSUM_ENABLED = 8,
READ_CACHE_ENABLED = 16,
WRITE_CACHE_ENABLED = 32,
MEDIA_SCAN_ENABLED = 64,
CONSISTENCY_CHECK_ENABLED = 128,
SNAPSHOT = 256,
};
pub const VDS_LF_LBN_REMAP_ENABLED = VDS_LUN_FLAG.LBN_REMAP_ENABLED;
pub const VDS_LF_READ_BACK_VERIFY_ENABLED = VDS_LUN_FLAG.READ_BACK_VERIFY_ENABLED;
pub const VDS_LF_WRITE_THROUGH_CACHING_ENABLED = VDS_LUN_FLAG.WRITE_THROUGH_CACHING_ENABLED;
pub const VDS_LF_HARDWARE_CHECKSUM_ENABLED = VDS_LUN_FLAG.HARDWARE_CHECKSUM_ENABLED;
pub const VDS_LF_READ_CACHE_ENABLED = VDS_LUN_FLAG.READ_CACHE_ENABLED;
pub const VDS_LF_WRITE_CACHE_ENABLED = VDS_LUN_FLAG.WRITE_CACHE_ENABLED;
pub const VDS_LF_MEDIA_SCAN_ENABLED = VDS_LUN_FLAG.MEDIA_SCAN_ENABLED;
pub const VDS_LF_CONSISTENCY_CHECK_ENABLED = VDS_LUN_FLAG.CONSISTENCY_CHECK_ENABLED;
pub const VDS_LF_SNAPSHOT = VDS_LUN_FLAG.SNAPSHOT;
pub const VDS_LUN_PLEX_TYPE = enum(i32) {
UNKNOWN = 0,
SIMPLE = 10,
SPAN = 11,
STRIPE = 12,
PARITY = 14,
RAID2 = 15,
RAID3 = 16,
RAID4 = 17,
RAID5 = 18,
RAID6 = 19,
RAID03 = 21,
RAID05 = 22,
RAID10 = 23,
RAID15 = 24,
RAID30 = 25,
RAID50 = 26,
RAID53 = 28,
RAID60 = 29,
};
pub const VDS_LPT_UNKNOWN = VDS_LUN_PLEX_TYPE.UNKNOWN;
pub const VDS_LPT_SIMPLE = VDS_LUN_PLEX_TYPE.SIMPLE;
pub const VDS_LPT_SPAN = VDS_LUN_PLEX_TYPE.SPAN;
pub const VDS_LPT_STRIPE = VDS_LUN_PLEX_TYPE.STRIPE;
pub const VDS_LPT_PARITY = VDS_LUN_PLEX_TYPE.PARITY;
pub const VDS_LPT_RAID2 = VDS_LUN_PLEX_TYPE.RAID2;
pub const VDS_LPT_RAID3 = VDS_LUN_PLEX_TYPE.RAID3;
pub const VDS_LPT_RAID4 = VDS_LUN_PLEX_TYPE.RAID4;
pub const VDS_LPT_RAID5 = VDS_LUN_PLEX_TYPE.RAID5;
pub const VDS_LPT_RAID6 = VDS_LUN_PLEX_TYPE.RAID6;
pub const VDS_LPT_RAID03 = VDS_LUN_PLEX_TYPE.RAID03;
pub const VDS_LPT_RAID05 = VDS_LUN_PLEX_TYPE.RAID05;
pub const VDS_LPT_RAID10 = VDS_LUN_PLEX_TYPE.RAID10;
pub const VDS_LPT_RAID15 = VDS_LUN_PLEX_TYPE.RAID15;
pub const VDS_LPT_RAID30 = VDS_LUN_PLEX_TYPE.RAID30;
pub const VDS_LPT_RAID50 = VDS_LUN_PLEX_TYPE.RAID50;
pub const VDS_LPT_RAID53 = VDS_LUN_PLEX_TYPE.RAID53;
pub const VDS_LPT_RAID60 = VDS_LUN_PLEX_TYPE.RAID60;
pub const VDS_LUN_PLEX_STATUS = enum(i32) {
UNKNOWN = 0,
ONLINE = 1,
NOT_READY = 2,
OFFLINE = 4,
FAILED = 5,
};
pub const VDS_LPS_UNKNOWN = VDS_LUN_PLEX_STATUS.UNKNOWN;
pub const VDS_LPS_ONLINE = VDS_LUN_PLEX_STATUS.ONLINE;
pub const VDS_LPS_NOT_READY = VDS_LUN_PLEX_STATUS.NOT_READY;
pub const VDS_LPS_OFFLINE = VDS_LUN_PLEX_STATUS.OFFLINE;
pub const VDS_LPS_FAILED = VDS_LUN_PLEX_STATUS.FAILED;
pub const VDS_LUN_PLEX_FLAG = enum(i32) {
D = 1,
};
pub const VDS_LPF_LBN_REMAP_ENABLED = VDS_LUN_PLEX_FLAG.D;
pub const VDS_ISCSI_PORTAL_STATUS = enum(i32) {
UNKNOWN = 0,
ONLINE = 1,
NOT_READY = 2,
OFFLINE = 4,
FAILED = 5,
};
pub const VDS_IPS_UNKNOWN = VDS_ISCSI_PORTAL_STATUS.UNKNOWN;
pub const VDS_IPS_ONLINE = VDS_ISCSI_PORTAL_STATUS.ONLINE;
pub const VDS_IPS_NOT_READY = VDS_ISCSI_PORTAL_STATUS.NOT_READY;
pub const VDS_IPS_OFFLINE = VDS_ISCSI_PORTAL_STATUS.OFFLINE;
pub const VDS_IPS_FAILED = VDS_ISCSI_PORTAL_STATUS.FAILED;
pub const VDS_STORAGE_POOL_STATUS = enum(i32) {
UNKNOWN = 0,
ONLINE = 1,
NOT_READY = 2,
OFFLINE = 4,
};
pub const VDS_SPS_UNKNOWN = VDS_STORAGE_POOL_STATUS.UNKNOWN;
pub const VDS_SPS_ONLINE = VDS_STORAGE_POOL_STATUS.ONLINE;
pub const VDS_SPS_NOT_READY = VDS_STORAGE_POOL_STATUS.NOT_READY;
pub const VDS_SPS_OFFLINE = VDS_STORAGE_POOL_STATUS.OFFLINE;
pub const VDS_STORAGE_POOL_TYPE = enum(i32) {
UNKNOWN = 0,
PRIMORDIAL = 1,
CONCRETE = 2,
};
pub const VDS_SPT_UNKNOWN = VDS_STORAGE_POOL_TYPE.UNKNOWN;
pub const VDS_SPT_PRIMORDIAL = VDS_STORAGE_POOL_TYPE.PRIMORDIAL;
pub const VDS_SPT_CONCRETE = VDS_STORAGE_POOL_TYPE.CONCRETE;
pub const VDS_MAINTENANCE_OPERATION = enum(i32) {
BlinkLight = 1,
BeepAlarm = 2,
SpinDown = 3,
SpinUp = 4,
Ping = 5,
};
pub const BlinkLight = VDS_MAINTENANCE_OPERATION.BlinkLight;
pub const BeepAlarm = VDS_MAINTENANCE_OPERATION.BeepAlarm;
pub const SpinDown = VDS_MAINTENANCE_OPERATION.SpinDown;
pub const SpinUp = VDS_MAINTENANCE_OPERATION.SpinUp;
pub const Ping = VDS_MAINTENANCE_OPERATION.Ping;
pub const VDS_HINTS = extern struct {
ullHintMask: u64,
ullExpectedMaximumSize: u64,
ulOptimalReadSize: u32,
ulOptimalReadAlignment: u32,
ulOptimalWriteSize: u32,
ulOptimalWriteAlignment: u32,
ulMaximumDriveCount: u32,
ulStripeSize: u32,
bFastCrashRecoveryRequired: BOOL,
bMostlyReads: BOOL,
bOptimizeForSequentialReads: BOOL,
bOptimizeForSequentialWrites: BOOL,
bRemapEnabled: BOOL,
bReadBackVerifyEnabled: BOOL,
bWriteThroughCachingEnabled: BOOL,
bHardwareChecksumEnabled: BOOL,
bIsYankable: BOOL,
sRebuildPriority: i16,
};
pub const VDS_HINTS2 = extern struct {
ullHintMask: u64,
ullExpectedMaximumSize: u64,
ulOptimalReadSize: u32,
ulOptimalReadAlignment: u32,
ulOptimalWriteSize: u32,
ulOptimalWriteAlignment: u32,
ulMaximumDriveCount: u32,
ulStripeSize: u32,
ulReserved1: u32,
ulReserved2: u32,
ulReserved3: u32,
bFastCrashRecoveryRequired: BOOL,
bMostlyReads: BOOL,
bOptimizeForSequentialReads: BOOL,
bOptimizeForSequentialWrites: BOOL,
bRemapEnabled: BOOL,
bReadBackVerifyEnabled: BOOL,
bWriteThroughCachingEnabled: BOOL,
bHardwareChecksumEnabled: BOOL,
bIsYankable: BOOL,
bAllocateHotSpare: BOOL,
bUseMirroredCache: BOOL,
bReadCachingEnabled: BOOL,
bWriteCachingEnabled: BOOL,
bMediaScanEnabled: BOOL,
bConsistencyCheckEnabled: BOOL,
BusType: VDS_STORAGE_BUS_TYPE,
bReserved1: BOOL,
bReserved2: BOOL,
bReserved3: BOOL,
sRebuildPriority: i16,
};
pub const VDS_SUB_SYSTEM_PROP = extern struct {
id: Guid,
pwszFriendlyName: ?PWSTR,
pwszIdentification: ?PWSTR,
ulFlags: u32,
ulStripeSizeFlags: u32,
status: VDS_SUB_SYSTEM_STATUS,
health: VDS_HEALTH,
sNumberOfInternalBuses: i16,
sMaxNumberOfSlotsEachBus: i16,
sMaxNumberOfControllers: i16,
sRebuildPriority: i16,
};
pub const VDS_SUB_SYSTEM_PROP2 = extern struct {
id: Guid,
pwszFriendlyName: ?PWSTR,
pwszIdentification: ?PWSTR,
ulFlags: u32,
ulStripeSizeFlags: u32,
ulSupportedRaidTypeFlags: u32,
status: VDS_SUB_SYSTEM_STATUS,
health: VDS_HEALTH,
sNumberOfInternalBuses: i16,
sMaxNumberOfSlotsEachBus: i16,
sMaxNumberOfControllers: i16,
sRebuildPriority: i16,
ulNumberOfEnclosures: u32,
};
pub const VDS_CONTROLLER_PROP = extern struct {
id: Guid,
pwszFriendlyName: ?PWSTR,
pwszIdentification: ?PWSTR,
status: VDS_CONTROLLER_STATUS,
health: VDS_HEALTH,
sNumberOfPorts: i16,
};
pub const VDS_DRIVE_PROP = extern struct {
id: Guid,
ullSize: u64,
pwszFriendlyName: ?PWSTR,
pwszIdentification: ?PWSTR,
ulFlags: u32,
status: VDS_DRIVE_STATUS,
health: VDS_HEALTH,
sInternalBusNumber: i16,
sSlotNumber: i16,
};
pub const VDS_DRIVE_PROP2 = extern struct {
id: Guid,
ullSize: u64,
pwszFriendlyName: ?PWSTR,
pwszIdentification: ?PWSTR,
ulFlags: u32,
status: VDS_DRIVE_STATUS,
health: VDS_HEALTH,
sInternalBusNumber: i16,
sSlotNumber: i16,
ulEnclosureNumber: u32,
busType: VDS_STORAGE_BUS_TYPE,
ulSpindleSpeed: u32,
};
pub const VDS_DRIVE_EXTENT = extern struct {
id: Guid,
LunId: Guid,
ullSize: u64,
bUsed: BOOL,
};
pub const VDS_LUN_PROP = extern struct {
id: Guid,
ullSize: u64,
pwszFriendlyName: ?PWSTR,
pwszIdentification: ?PWSTR,
pwszUnmaskingList: ?PWSTR,
ulFlags: u32,
type: VDS_LUN_TYPE,
status: VDS_LUN_STATUS,
health: VDS_HEALTH,
TransitionState: VDS_TRANSITION_STATE,
sRebuildPriority: i16,
};
pub const VDS_LUN_PLEX_PROP = extern struct {
id: Guid,
ullSize: u64,
type: VDS_LUN_PLEX_TYPE,
status: VDS_LUN_PLEX_STATUS,
health: VDS_HEALTH,
TransitionState: VDS_TRANSITION_STATE,
ulFlags: u32,
ulStripeSize: u32,
sRebuildPriority: i16,
};
pub const VDS_PORT_PROP = extern struct {
id: Guid,
pwszFriendlyName: ?PWSTR,
pwszIdentification: ?PWSTR,
status: VDS_PORT_STATUS,
};
pub const VDS_ISCSI_PORTAL_PROP = extern struct {
id: Guid,
address: VDS_IPADDRESS,
status: VDS_ISCSI_PORTAL_STATUS,
};
pub const VDS_ISCSI_TARGET_PROP = extern struct {
id: Guid,
pwszIscsiName: ?PWSTR,
pwszFriendlyName: ?PWSTR,
bChapEnabled: BOOL,
};
pub const VDS_ISCSI_PORTALGROUP_PROP = extern struct {
id: Guid,
tag: u16,
};
pub const VDS_RAID_TYPE = enum(i32) {
UNKNOWN = 0,
RAID0 = 10,
RAID1 = 11,
RAID2 = 12,
RAID3 = 13,
RAID4 = 14,
RAID5 = 15,
RAID6 = 16,
RAID01 = 17,
RAID03 = 18,
RAID05 = 19,
RAID10 = 20,
RAID15 = 21,
RAID30 = 22,
RAID50 = 23,
RAID51 = 24,
RAID53 = 25,
RAID60 = 26,
RAID61 = 27,
};
pub const VDS_RT_UNKNOWN = VDS_RAID_TYPE.UNKNOWN;
pub const VDS_RT_RAID0 = VDS_RAID_TYPE.RAID0;
pub const VDS_RT_RAID1 = VDS_RAID_TYPE.RAID1;
pub const VDS_RT_RAID2 = VDS_RAID_TYPE.RAID2;
pub const VDS_RT_RAID3 = VDS_RAID_TYPE.RAID3;
pub const VDS_RT_RAID4 = VDS_RAID_TYPE.RAID4;
pub const VDS_RT_RAID5 = VDS_RAID_TYPE.RAID5;
pub const VDS_RT_RAID6 = VDS_RAID_TYPE.RAID6;
pub const VDS_RT_RAID01 = VDS_RAID_TYPE.RAID01;
pub const VDS_RT_RAID03 = VDS_RAID_TYPE.RAID03;
pub const VDS_RT_RAID05 = VDS_RAID_TYPE.RAID05;
pub const VDS_RT_RAID10 = VDS_RAID_TYPE.RAID10;
pub const VDS_RT_RAID15 = VDS_RAID_TYPE.RAID15;
pub const VDS_RT_RAID30 = VDS_RAID_TYPE.RAID30;
pub const VDS_RT_RAID50 = VDS_RAID_TYPE.RAID50;
pub const VDS_RT_RAID51 = VDS_RAID_TYPE.RAID51;
pub const VDS_RT_RAID53 = VDS_RAID_TYPE.RAID53;
pub const VDS_RT_RAID60 = VDS_RAID_TYPE.RAID60;
pub const VDS_RT_RAID61 = VDS_RAID_TYPE.RAID61;
pub const VDS_POOL_CUSTOM_ATTRIBUTES = extern struct {
pwszName: ?PWSTR,
pwszValue: ?PWSTR,
};
pub const VDS_POOL_ATTRIBUTES = extern struct {
ullAttributeMask: u64,
raidType: VDS_RAID_TYPE,
busType: VDS_STORAGE_BUS_TYPE,
pwszIntendedUsage: ?PWSTR,
bSpinDown: BOOL,
bIsThinProvisioned: BOOL,
ullProvisionedSpace: u64,
bNoSinglePointOfFailure: BOOL,
ulDataRedundancyMax: u32,
ulDataRedundancyMin: u32,
ulDataRedundancyDefault: u32,
ulPackageRedundancyMax: u32,
ulPackageRedundancyMin: u32,
ulPackageRedundancyDefault: u32,
ulStripeSize: u32,
ulStripeSizeMax: u32,
ulStripeSizeMin: u32,
ulDefaultStripeSize: u32,
ulNumberOfColumns: u32,
ulNumberOfColumnsMax: u32,
ulNumberOfColumnsMin: u32,
ulDefaultNumberofColumns: u32,
ulDataAvailabilityHint: u32,
ulAccessRandomnessHint: u32,
ulAccessDirectionHint: u32,
ulAccessSizeHint: u32,
ulAccessLatencyHint: u32,
ulAccessBandwidthWeightHint: u32,
ulStorageCostHint: u32,
ulStorageEfficiencyHint: u32,
ulNumOfCustomAttributes: u32,
pPoolCustomAttributes: ?*VDS_POOL_CUSTOM_ATTRIBUTES,
bReserved1: BOOL,
bReserved2: BOOL,
ulReserved1: u32,
ulReserved2: u32,
ullReserved1: u64,
ullReserved2: u64,
};
pub const VDS_STORAGE_POOL_PROP = extern struct {
id: Guid,
status: VDS_STORAGE_POOL_STATUS,
health: VDS_HEALTH,
type: VDS_STORAGE_POOL_TYPE,
pwszName: ?PWSTR,
pwszDescription: ?PWSTR,
ullTotalConsumedSpace: u64,
ullTotalManagedSpace: u64,
ullRemainingFreeSpace: u64,
};
pub const VDS_STORAGE_POOL_DRIVE_EXTENT = extern struct {
id: Guid,
ullSize: u64,
bUsed: BOOL,
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IVdsHwProvider_Value = Guid.initString("d99bdaae-b13a-4178-9fdb-e27f16b4603e");
pub const IID_IVdsHwProvider = &IID_IVdsHwProvider_Value;
pub const IVdsHwProvider = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
QuerySubSystems: fn(
self: *const IVdsHwProvider,
ppEnum: ?*?*IEnumVdsObject,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Reenumerate: fn(
self: *const IVdsHwProvider,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Refresh: fn(
self: *const IVdsHwProvider,
) 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 IVdsHwProvider_QuerySubSystems(self: *const T, ppEnum: ?*?*IEnumVdsObject) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsHwProvider.VTable, self.vtable).QuerySubSystems(@ptrCast(*const IVdsHwProvider, self), ppEnum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsHwProvider_Reenumerate(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsHwProvider.VTable, self.vtable).Reenumerate(@ptrCast(*const IVdsHwProvider, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsHwProvider_Refresh(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsHwProvider.VTable, self.vtable).Refresh(@ptrCast(*const IVdsHwProvider, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IVdsHwProviderType_Value = Guid.initString("3e0f5166-542d-4fc6-947a-012174240b7e");
pub const IID_IVdsHwProviderType = &IID_IVdsHwProviderType_Value;
pub const IVdsHwProviderType = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetProviderType: fn(
self: *const IVdsHwProviderType,
pType: ?*VDS_HWPROVIDER_TYPE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsHwProviderType_GetProviderType(self: *const T, pType: ?*VDS_HWPROVIDER_TYPE) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsHwProviderType.VTable, self.vtable).GetProviderType(@ptrCast(*const IVdsHwProviderType, self), pType);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IVdsHwProviderType2_Value = Guid.initString("8190236f-c4d0-4e81-8011-d69512fcc984");
pub const IID_IVdsHwProviderType2 = &IID_IVdsHwProviderType2_Value;
pub const IVdsHwProviderType2 = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetProviderType2: fn(
self: *const IVdsHwProviderType2,
pType: ?*VDS_HWPROVIDER_TYPE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsHwProviderType2_GetProviderType2(self: *const T, pType: ?*VDS_HWPROVIDER_TYPE) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsHwProviderType2.VTable, self.vtable).GetProviderType2(@ptrCast(*const IVdsHwProviderType2, self), pType);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IVdsHwProviderStoragePools_Value = Guid.initString("d5b5937a-f188-4c79-b86c-11c920ad11b8");
pub const IID_IVdsHwProviderStoragePools = &IID_IVdsHwProviderStoragePools_Value;
pub const IVdsHwProviderStoragePools = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
QueryStoragePools: fn(
self: *const IVdsHwProviderStoragePools,
ulFlags: u32,
ullRemainingFreeSpace: u64,
pPoolAttributes: ?*VDS_POOL_ATTRIBUTES,
ppEnum: ?*?*IEnumVdsObject,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateLunInStoragePool: fn(
self: *const IVdsHwProviderStoragePools,
type: VDS_LUN_TYPE,
ullSizeInBytes: u64,
StoragePoolId: Guid,
pwszUnmaskingList: ?PWSTR,
pHints2: ?*VDS_HINTS2,
ppAsync: ?*?*IVdsAsync,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
QueryMaxLunCreateSizeInStoragePool: fn(
self: *const IVdsHwProviderStoragePools,
type: VDS_LUN_TYPE,
StoragePoolId: Guid,
pHints2: ?*VDS_HINTS2,
pullMaxLunSize: ?*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 IVdsHwProviderStoragePools_QueryStoragePools(self: *const T, ulFlags: u32, ullRemainingFreeSpace: u64, pPoolAttributes: ?*VDS_POOL_ATTRIBUTES, ppEnum: ?*?*IEnumVdsObject) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsHwProviderStoragePools.VTable, self.vtable).QueryStoragePools(@ptrCast(*const IVdsHwProviderStoragePools, self), ulFlags, ullRemainingFreeSpace, pPoolAttributes, ppEnum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsHwProviderStoragePools_CreateLunInStoragePool(self: *const T, type_: VDS_LUN_TYPE, ullSizeInBytes: u64, StoragePoolId: Guid, pwszUnmaskingList: ?PWSTR, pHints2: ?*VDS_HINTS2, ppAsync: ?*?*IVdsAsync) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsHwProviderStoragePools.VTable, self.vtable).CreateLunInStoragePool(@ptrCast(*const IVdsHwProviderStoragePools, self), type_, ullSizeInBytes, StoragePoolId, pwszUnmaskingList, pHints2, ppAsync);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsHwProviderStoragePools_QueryMaxLunCreateSizeInStoragePool(self: *const T, type_: VDS_LUN_TYPE, StoragePoolId: Guid, pHints2: ?*VDS_HINTS2, pullMaxLunSize: ?*u64) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsHwProviderStoragePools.VTable, self.vtable).QueryMaxLunCreateSizeInStoragePool(@ptrCast(*const IVdsHwProviderStoragePools, self), type_, StoragePoolId, pHints2, pullMaxLunSize);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IVdsSubSystem_Value = Guid.initString("6fcee2d3-6d90-4f91-80e2-a5c7caaca9d8");
pub const IID_IVdsSubSystem = &IID_IVdsSubSystem_Value;
pub const IVdsSubSystem = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetProperties: fn(
self: *const IVdsSubSystem,
pSubSystemProp: ?*VDS_SUB_SYSTEM_PROP,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetProvider: fn(
self: *const IVdsSubSystem,
ppProvider: ?*?*IVdsProvider,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
QueryControllers: fn(
self: *const IVdsSubSystem,
ppEnum: ?*?*IEnumVdsObject,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
QueryLuns: fn(
self: *const IVdsSubSystem,
ppEnum: ?*?*IEnumVdsObject,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
QueryDrives: fn(
self: *const IVdsSubSystem,
ppEnum: ?*?*IEnumVdsObject,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDrive: fn(
self: *const IVdsSubSystem,
sBusNumber: i16,
sSlotNumber: i16,
ppDrive: ?*?*IVdsDrive,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Reenumerate: fn(
self: *const IVdsSubSystem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetControllerStatus: fn(
self: *const IVdsSubSystem,
pOnlineControllerIdArray: [*]Guid,
lNumberOfOnlineControllers: i32,
pOfflineControllerIdArray: [*]Guid,
lNumberOfOfflineControllers: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateLun: fn(
self: *const IVdsSubSystem,
type: VDS_LUN_TYPE,
ullSizeInBytes: u64,
pDriveIdArray: ?[*]Guid,
lNumberOfDrives: i32,
pwszUnmaskingList: ?PWSTR,
pHints: ?*VDS_HINTS,
ppAsync: ?*?*IVdsAsync,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ReplaceDrive: fn(
self: *const IVdsSubSystem,
DriveToBeReplaced: Guid,
ReplacementDrive: Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetStatus: fn(
self: *const IVdsSubSystem,
status: VDS_SUB_SYSTEM_STATUS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
QueryMaxLunCreateSize: fn(
self: *const IVdsSubSystem,
type: VDS_LUN_TYPE,
pDriveIdArray: ?[*]Guid,
lNumberOfDrives: i32,
pHints: ?*VDS_HINTS,
pullMaxLunSize: ?*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 IVdsSubSystem_GetProperties(self: *const T, pSubSystemProp: ?*VDS_SUB_SYSTEM_PROP) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsSubSystem.VTable, self.vtable).GetProperties(@ptrCast(*const IVdsSubSystem, self), pSubSystemProp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsSubSystem_GetProvider(self: *const T, ppProvider: ?*?*IVdsProvider) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsSubSystem.VTable, self.vtable).GetProvider(@ptrCast(*const IVdsSubSystem, self), ppProvider);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsSubSystem_QueryControllers(self: *const T, ppEnum: ?*?*IEnumVdsObject) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsSubSystem.VTable, self.vtable).QueryControllers(@ptrCast(*const IVdsSubSystem, self), ppEnum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsSubSystem_QueryLuns(self: *const T, ppEnum: ?*?*IEnumVdsObject) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsSubSystem.VTable, self.vtable).QueryLuns(@ptrCast(*const IVdsSubSystem, self), ppEnum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsSubSystem_QueryDrives(self: *const T, ppEnum: ?*?*IEnumVdsObject) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsSubSystem.VTable, self.vtable).QueryDrives(@ptrCast(*const IVdsSubSystem, self), ppEnum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsSubSystem_GetDrive(self: *const T, sBusNumber: i16, sSlotNumber: i16, ppDrive: ?*?*IVdsDrive) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsSubSystem.VTable, self.vtable).GetDrive(@ptrCast(*const IVdsSubSystem, self), sBusNumber, sSlotNumber, ppDrive);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsSubSystem_Reenumerate(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsSubSystem.VTable, self.vtable).Reenumerate(@ptrCast(*const IVdsSubSystem, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsSubSystem_SetControllerStatus(self: *const T, pOnlineControllerIdArray: [*]Guid, lNumberOfOnlineControllers: i32, pOfflineControllerIdArray: [*]Guid, lNumberOfOfflineControllers: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsSubSystem.VTable, self.vtable).SetControllerStatus(@ptrCast(*const IVdsSubSystem, self), pOnlineControllerIdArray, lNumberOfOnlineControllers, pOfflineControllerIdArray, lNumberOfOfflineControllers);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsSubSystem_CreateLun(self: *const T, type_: VDS_LUN_TYPE, ullSizeInBytes: u64, pDriveIdArray: ?[*]Guid, lNumberOfDrives: i32, pwszUnmaskingList: ?PWSTR, pHints: ?*VDS_HINTS, ppAsync: ?*?*IVdsAsync) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsSubSystem.VTable, self.vtable).CreateLun(@ptrCast(*const IVdsSubSystem, self), type_, ullSizeInBytes, pDriveIdArray, lNumberOfDrives, pwszUnmaskingList, pHints, ppAsync);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsSubSystem_ReplaceDrive(self: *const T, DriveToBeReplaced: Guid, ReplacementDrive: Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsSubSystem.VTable, self.vtable).ReplaceDrive(@ptrCast(*const IVdsSubSystem, self), DriveToBeReplaced, ReplacementDrive);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsSubSystem_SetStatus(self: *const T, status: VDS_SUB_SYSTEM_STATUS) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsSubSystem.VTable, self.vtable).SetStatus(@ptrCast(*const IVdsSubSystem, self), status);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsSubSystem_QueryMaxLunCreateSize(self: *const T, type_: VDS_LUN_TYPE, pDriveIdArray: ?[*]Guid, lNumberOfDrives: i32, pHints: ?*VDS_HINTS, pullMaxLunSize: ?*u64) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsSubSystem.VTable, self.vtable).QueryMaxLunCreateSize(@ptrCast(*const IVdsSubSystem, self), type_, pDriveIdArray, lNumberOfDrives, pHints, pullMaxLunSize);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IVdsSubSystem2_Value = Guid.initString("be666735-7800-4a77-9d9c-40f85b87e292");
pub const IID_IVdsSubSystem2 = &IID_IVdsSubSystem2_Value;
pub const IVdsSubSystem2 = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetProperties2: fn(
self: *const IVdsSubSystem2,
pSubSystemProp2: ?*VDS_SUB_SYSTEM_PROP2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDrive2: fn(
self: *const IVdsSubSystem2,
sBusNumber: i16,
sSlotNumber: i16,
ulEnclosureNumber: u32,
ppDrive: ?*?*IVdsDrive,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateLun2: fn(
self: *const IVdsSubSystem2,
type: VDS_LUN_TYPE,
ullSizeInBytes: u64,
pDriveIdArray: ?[*]Guid,
lNumberOfDrives: i32,
pwszUnmaskingList: ?PWSTR,
pHints2: ?*VDS_HINTS2,
ppAsync: ?*?*IVdsAsync,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
QueryMaxLunCreateSize2: fn(
self: *const IVdsSubSystem2,
type: VDS_LUN_TYPE,
pDriveIdArray: ?[*]Guid,
lNumberOfDrives: i32,
pHints2: ?*VDS_HINTS2,
pullMaxLunSize: ?*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 IVdsSubSystem2_GetProperties2(self: *const T, pSubSystemProp2: ?*VDS_SUB_SYSTEM_PROP2) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsSubSystem2.VTable, self.vtable).GetProperties2(@ptrCast(*const IVdsSubSystem2, self), pSubSystemProp2);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsSubSystem2_GetDrive2(self: *const T, sBusNumber: i16, sSlotNumber: i16, ulEnclosureNumber: u32, ppDrive: ?*?*IVdsDrive) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsSubSystem2.VTable, self.vtable).GetDrive2(@ptrCast(*const IVdsSubSystem2, self), sBusNumber, sSlotNumber, ulEnclosureNumber, ppDrive);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsSubSystem2_CreateLun2(self: *const T, type_: VDS_LUN_TYPE, ullSizeInBytes: u64, pDriveIdArray: ?[*]Guid, lNumberOfDrives: i32, pwszUnmaskingList: ?PWSTR, pHints2: ?*VDS_HINTS2, ppAsync: ?*?*IVdsAsync) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsSubSystem2.VTable, self.vtable).CreateLun2(@ptrCast(*const IVdsSubSystem2, self), type_, ullSizeInBytes, pDriveIdArray, lNumberOfDrives, pwszUnmaskingList, pHints2, ppAsync);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsSubSystem2_QueryMaxLunCreateSize2(self: *const T, type_: VDS_LUN_TYPE, pDriveIdArray: ?[*]Guid, lNumberOfDrives: i32, pHints2: ?*VDS_HINTS2, pullMaxLunSize: ?*u64) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsSubSystem2.VTable, self.vtable).QueryMaxLunCreateSize2(@ptrCast(*const IVdsSubSystem2, self), type_, pDriveIdArray, lNumberOfDrives, pHints2, pullMaxLunSize);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IVdsSubSystemNaming_Value = Guid.initString("0d70faa3-9cd4-4900-aa20-6981b6aafc75");
pub const IID_IVdsSubSystemNaming = &IID_IVdsSubSystemNaming_Value;
pub const IVdsSubSystemNaming = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetFriendlyName: fn(
self: *const IVdsSubSystemNaming,
pwszFriendlyName: ?PWSTR,
) 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 IVdsSubSystemNaming_SetFriendlyName(self: *const T, pwszFriendlyName: ?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsSubSystemNaming.VTable, self.vtable).SetFriendlyName(@ptrCast(*const IVdsSubSystemNaming, self), pwszFriendlyName);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IVdsSubSystemIscsi_Value = Guid.initString("0027346f-40d0-4b45-8cec-5906dc0380c8");
pub const IID_IVdsSubSystemIscsi = &IID_IVdsSubSystemIscsi_Value;
pub const IVdsSubSystemIscsi = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
QueryTargets: fn(
self: *const IVdsSubSystemIscsi,
ppEnum: ?*?*IEnumVdsObject,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
QueryPortals: fn(
self: *const IVdsSubSystemIscsi,
ppEnum: ?*?*IEnumVdsObject,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateTarget: fn(
self: *const IVdsSubSystemIscsi,
pwszIscsiName: ?PWSTR,
pwszFriendlyName: ?PWSTR,
ppAsync: ?*?*IVdsAsync,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetIpsecGroupPresharedKey: fn(
self: *const IVdsSubSystemIscsi,
pIpsecKey: ?*VDS_ISCSI_IPSEC_KEY,
) 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 IVdsSubSystemIscsi_QueryTargets(self: *const T, ppEnum: ?*?*IEnumVdsObject) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsSubSystemIscsi.VTable, self.vtable).QueryTargets(@ptrCast(*const IVdsSubSystemIscsi, self), ppEnum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsSubSystemIscsi_QueryPortals(self: *const T, ppEnum: ?*?*IEnumVdsObject) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsSubSystemIscsi.VTable, self.vtable).QueryPortals(@ptrCast(*const IVdsSubSystemIscsi, self), ppEnum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsSubSystemIscsi_CreateTarget(self: *const T, pwszIscsiName: ?PWSTR, pwszFriendlyName: ?PWSTR, ppAsync: ?*?*IVdsAsync) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsSubSystemIscsi.VTable, self.vtable).CreateTarget(@ptrCast(*const IVdsSubSystemIscsi, self), pwszIscsiName, pwszFriendlyName, ppAsync);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsSubSystemIscsi_SetIpsecGroupPresharedKey(self: *const T, pIpsecKey: ?*VDS_ISCSI_IPSEC_KEY) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsSubSystemIscsi.VTable, self.vtable).SetIpsecGroupPresharedKey(@ptrCast(*const IVdsSubSystemIscsi, self), pIpsecKey);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IVdsSubSystemInterconnect_Value = Guid.initString("9e6fa560-c141-477b-83ba-0b6c38f7febf");
pub const IID_IVdsSubSystemInterconnect = &IID_IVdsSubSystemInterconnect_Value;
pub const IVdsSubSystemInterconnect = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetSupportedInterconnects: fn(
self: *const IVdsSubSystemInterconnect,
pulSupportedInterconnectsFlag: ?*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 IVdsSubSystemInterconnect_GetSupportedInterconnects(self: *const T, pulSupportedInterconnectsFlag: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsSubSystemInterconnect.VTable, self.vtable).GetSupportedInterconnects(@ptrCast(*const IVdsSubSystemInterconnect, self), pulSupportedInterconnectsFlag);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IVdsControllerPort_Value = Guid.initString("18691d0d-4e7f-43e8-92e4-cf44beeed11c");
pub const IID_IVdsControllerPort = &IID_IVdsControllerPort_Value;
pub const IVdsControllerPort = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetProperties: fn(
self: *const IVdsControllerPort,
pPortProp: ?*VDS_PORT_PROP,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetController: fn(
self: *const IVdsControllerPort,
ppController: ?*?*IVdsController,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
QueryAssociatedLuns: fn(
self: *const IVdsControllerPort,
ppEnum: ?*?*IEnumVdsObject,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Reset: fn(
self: *const IVdsControllerPort,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetStatus: fn(
self: *const IVdsControllerPort,
status: VDS_PORT_STATUS,
) 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 IVdsControllerPort_GetProperties(self: *const T, pPortProp: ?*VDS_PORT_PROP) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsControllerPort.VTable, self.vtable).GetProperties(@ptrCast(*const IVdsControllerPort, self), pPortProp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsControllerPort_GetController(self: *const T, ppController: ?*?*IVdsController) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsControllerPort.VTable, self.vtable).GetController(@ptrCast(*const IVdsControllerPort, self), ppController);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsControllerPort_QueryAssociatedLuns(self: *const T, ppEnum: ?*?*IEnumVdsObject) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsControllerPort.VTable, self.vtable).QueryAssociatedLuns(@ptrCast(*const IVdsControllerPort, self), ppEnum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsControllerPort_Reset(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsControllerPort.VTable, self.vtable).Reset(@ptrCast(*const IVdsControllerPort, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsControllerPort_SetStatus(self: *const T, status: VDS_PORT_STATUS) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsControllerPort.VTable, self.vtable).SetStatus(@ptrCast(*const IVdsControllerPort, self), status);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IVdsController_Value = Guid.initString("cb53d96e-dffb-474a-a078-790d1e2bc082");
pub const IID_IVdsController = &IID_IVdsController_Value;
pub const IVdsController = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetProperties: fn(
self: *const IVdsController,
pControllerProp: ?*VDS_CONTROLLER_PROP,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSubSystem: fn(
self: *const IVdsController,
ppSubSystem: ?*?*IVdsSubSystem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPortProperties: fn(
self: *const IVdsController,
sPortNumber: i16,
pPortProp: ?*VDS_PORT_PROP,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FlushCache: fn(
self: *const IVdsController,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
InvalidateCache: fn(
self: *const IVdsController,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Reset: fn(
self: *const IVdsController,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
QueryAssociatedLuns: fn(
self: *const IVdsController,
ppEnum: ?*?*IEnumVdsObject,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetStatus: fn(
self: *const IVdsController,
status: VDS_CONTROLLER_STATUS,
) 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 IVdsController_GetProperties(self: *const T, pControllerProp: ?*VDS_CONTROLLER_PROP) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsController.VTable, self.vtable).GetProperties(@ptrCast(*const IVdsController, self), pControllerProp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsController_GetSubSystem(self: *const T, ppSubSystem: ?*?*IVdsSubSystem) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsController.VTable, self.vtable).GetSubSystem(@ptrCast(*const IVdsController, self), ppSubSystem);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsController_GetPortProperties(self: *const T, sPortNumber: i16, pPortProp: ?*VDS_PORT_PROP) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsController.VTable, self.vtable).GetPortProperties(@ptrCast(*const IVdsController, self), sPortNumber, pPortProp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsController_FlushCache(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsController.VTable, self.vtable).FlushCache(@ptrCast(*const IVdsController, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsController_InvalidateCache(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsController.VTable, self.vtable).InvalidateCache(@ptrCast(*const IVdsController, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsController_Reset(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsController.VTable, self.vtable).Reset(@ptrCast(*const IVdsController, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsController_QueryAssociatedLuns(self: *const T, ppEnum: ?*?*IEnumVdsObject) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsController.VTable, self.vtable).QueryAssociatedLuns(@ptrCast(*const IVdsController, self), ppEnum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsController_SetStatus(self: *const T, status: VDS_CONTROLLER_STATUS) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsController.VTable, self.vtable).SetStatus(@ptrCast(*const IVdsController, self), status);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IVdsControllerControllerPort_Value = Guid.initString("ca5d735f-6bae-42c0-b30e-f2666045ce71");
pub const IID_IVdsControllerControllerPort = &IID_IVdsControllerControllerPort_Value;
pub const IVdsControllerControllerPort = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
QueryControllerPorts: fn(
self: *const IVdsControllerControllerPort,
ppEnum: ?*?*IEnumVdsObject,
) 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 IVdsControllerControllerPort_QueryControllerPorts(self: *const T, ppEnum: ?*?*IEnumVdsObject) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsControllerControllerPort.VTable, self.vtable).QueryControllerPorts(@ptrCast(*const IVdsControllerControllerPort, self), ppEnum);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IVdsDrive_Value = Guid.initString("ff24efa4-aade-4b6b-898b-eaa6a20887c7");
pub const IID_IVdsDrive = &IID_IVdsDrive_Value;
pub const IVdsDrive = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetProperties: fn(
self: *const IVdsDrive,
pDriveProp: ?*VDS_DRIVE_PROP,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSubSystem: fn(
self: *const IVdsDrive,
ppSubSystem: ?*?*IVdsSubSystem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
QueryExtents: fn(
self: *const IVdsDrive,
ppExtentArray: ?[*]?*VDS_DRIVE_EXTENT,
plNumberOfExtents: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetFlags: fn(
self: *const IVdsDrive,
ulFlags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ClearFlags: fn(
self: *const IVdsDrive,
ulFlags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetStatus: fn(
self: *const IVdsDrive,
status: VDS_DRIVE_STATUS,
) 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 IVdsDrive_GetProperties(self: *const T, pDriveProp: ?*VDS_DRIVE_PROP) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsDrive.VTable, self.vtable).GetProperties(@ptrCast(*const IVdsDrive, self), pDriveProp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsDrive_GetSubSystem(self: *const T, ppSubSystem: ?*?*IVdsSubSystem) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsDrive.VTable, self.vtable).GetSubSystem(@ptrCast(*const IVdsDrive, self), ppSubSystem);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsDrive_QueryExtents(self: *const T, ppExtentArray: ?[*]?*VDS_DRIVE_EXTENT, plNumberOfExtents: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsDrive.VTable, self.vtable).QueryExtents(@ptrCast(*const IVdsDrive, self), ppExtentArray, plNumberOfExtents);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsDrive_SetFlags(self: *const T, ulFlags: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsDrive.VTable, self.vtable).SetFlags(@ptrCast(*const IVdsDrive, self), ulFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsDrive_ClearFlags(self: *const T, ulFlags: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsDrive.VTable, self.vtable).ClearFlags(@ptrCast(*const IVdsDrive, self), ulFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsDrive_SetStatus(self: *const T, status: VDS_DRIVE_STATUS) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsDrive.VTable, self.vtable).SetStatus(@ptrCast(*const IVdsDrive, self), status);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IVdsDrive2_Value = Guid.initString("60b5a730-addf-4436-8ca7-5769e2d1ffa4");
pub const IID_IVdsDrive2 = &IID_IVdsDrive2_Value;
pub const IVdsDrive2 = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetProperties2: fn(
self: *const IVdsDrive2,
pDriveProp2: ?*VDS_DRIVE_PROP2,
) 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 IVdsDrive2_GetProperties2(self: *const T, pDriveProp2: ?*VDS_DRIVE_PROP2) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsDrive2.VTable, self.vtable).GetProperties2(@ptrCast(*const IVdsDrive2, self), pDriveProp2);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IVdsLun_Value = Guid.initString("3540a9c7-e60f-4111-a840-8bba6c2c83d8");
pub const IID_IVdsLun = &IID_IVdsLun_Value;
pub const IVdsLun = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetProperties: fn(
self: *const IVdsLun,
pLunProp: ?*VDS_LUN_PROP,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSubSystem: fn(
self: *const IVdsLun,
ppSubSystem: ?*?*IVdsSubSystem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetIdentificationData: fn(
self: *const IVdsLun,
pLunInfo: ?*VDS_LUN_INFORMATION,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
QueryActiveControllers: fn(
self: *const IVdsLun,
ppEnum: ?*?*IEnumVdsObject,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Extend: fn(
self: *const IVdsLun,
ullNumberOfBytesToAdd: u64,
pDriveIdArray: ?[*]Guid,
lNumberOfDrives: i32,
ppAsync: ?*?*IVdsAsync,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Shrink: fn(
self: *const IVdsLun,
ullNumberOfBytesToRemove: u64,
ppAsync: ?*?*IVdsAsync,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
QueryPlexes: fn(
self: *const IVdsLun,
ppEnum: ?*?*IEnumVdsObject,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddPlex: fn(
self: *const IVdsLun,
lunId: Guid,
ppAsync: ?*?*IVdsAsync,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemovePlex: fn(
self: *const IVdsLun,
plexId: Guid,
ppAsync: ?*?*IVdsAsync,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Recover: fn(
self: *const IVdsLun,
ppAsync: ?*?*IVdsAsync,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetMask: fn(
self: *const IVdsLun,
pwszUnmaskingList: ?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Delete: fn(
self: *const IVdsLun,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AssociateControllers: fn(
self: *const IVdsLun,
pActiveControllerIdArray: ?[*]Guid,
lNumberOfActiveControllers: i32,
pInactiveControllerIdArray: ?[*]Guid,
lNumberOfInactiveControllers: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
QueryHints: fn(
self: *const IVdsLun,
pHints: ?*VDS_HINTS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ApplyHints: fn(
self: *const IVdsLun,
pHints: ?*VDS_HINTS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetStatus: fn(
self: *const IVdsLun,
status: VDS_LUN_STATUS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
QueryMaxLunExtendSize: fn(
self: *const IVdsLun,
pDriveIdArray: ?[*]Guid,
lNumberOfDrives: i32,
pullMaxBytesToBeAdded: ?*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 IVdsLun_GetProperties(self: *const T, pLunProp: ?*VDS_LUN_PROP) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsLun.VTable, self.vtable).GetProperties(@ptrCast(*const IVdsLun, self), pLunProp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsLun_GetSubSystem(self: *const T, ppSubSystem: ?*?*IVdsSubSystem) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsLun.VTable, self.vtable).GetSubSystem(@ptrCast(*const IVdsLun, self), ppSubSystem);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsLun_GetIdentificationData(self: *const T, pLunInfo: ?*VDS_LUN_INFORMATION) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsLun.VTable, self.vtable).GetIdentificationData(@ptrCast(*const IVdsLun, self), pLunInfo);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsLun_QueryActiveControllers(self: *const T, ppEnum: ?*?*IEnumVdsObject) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsLun.VTable, self.vtable).QueryActiveControllers(@ptrCast(*const IVdsLun, self), ppEnum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsLun_Extend(self: *const T, ullNumberOfBytesToAdd: u64, pDriveIdArray: ?[*]Guid, lNumberOfDrives: i32, ppAsync: ?*?*IVdsAsync) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsLun.VTable, self.vtable).Extend(@ptrCast(*const IVdsLun, self), ullNumberOfBytesToAdd, pDriveIdArray, lNumberOfDrives, ppAsync);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsLun_Shrink(self: *const T, ullNumberOfBytesToRemove: u64, ppAsync: ?*?*IVdsAsync) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsLun.VTable, self.vtable).Shrink(@ptrCast(*const IVdsLun, self), ullNumberOfBytesToRemove, ppAsync);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsLun_QueryPlexes(self: *const T, ppEnum: ?*?*IEnumVdsObject) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsLun.VTable, self.vtable).QueryPlexes(@ptrCast(*const IVdsLun, self), ppEnum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsLun_AddPlex(self: *const T, lunId: Guid, ppAsync: ?*?*IVdsAsync) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsLun.VTable, self.vtable).AddPlex(@ptrCast(*const IVdsLun, self), lunId, ppAsync);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsLun_RemovePlex(self: *const T, plexId: Guid, ppAsync: ?*?*IVdsAsync) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsLun.VTable, self.vtable).RemovePlex(@ptrCast(*const IVdsLun, self), plexId, ppAsync);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsLun_Recover(self: *const T, ppAsync: ?*?*IVdsAsync) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsLun.VTable, self.vtable).Recover(@ptrCast(*const IVdsLun, self), ppAsync);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsLun_SetMask(self: *const T, pwszUnmaskingList: ?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsLun.VTable, self.vtable).SetMask(@ptrCast(*const IVdsLun, self), pwszUnmaskingList);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsLun_Delete(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsLun.VTable, self.vtable).Delete(@ptrCast(*const IVdsLun, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsLun_AssociateControllers(self: *const T, pActiveControllerIdArray: ?[*]Guid, lNumberOfActiveControllers: i32, pInactiveControllerIdArray: ?[*]Guid, lNumberOfInactiveControllers: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsLun.VTable, self.vtable).AssociateControllers(@ptrCast(*const IVdsLun, self), pActiveControllerIdArray, lNumberOfActiveControllers, pInactiveControllerIdArray, lNumberOfInactiveControllers);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsLun_QueryHints(self: *const T, pHints: ?*VDS_HINTS) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsLun.VTable, self.vtable).QueryHints(@ptrCast(*const IVdsLun, self), pHints);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsLun_ApplyHints(self: *const T, pHints: ?*VDS_HINTS) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsLun.VTable, self.vtable).ApplyHints(@ptrCast(*const IVdsLun, self), pHints);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsLun_SetStatus(self: *const T, status: VDS_LUN_STATUS) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsLun.VTable, self.vtable).SetStatus(@ptrCast(*const IVdsLun, self), status);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsLun_QueryMaxLunExtendSize(self: *const T, pDriveIdArray: ?[*]Guid, lNumberOfDrives: i32, pullMaxBytesToBeAdded: ?*u64) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsLun.VTable, self.vtable).QueryMaxLunExtendSize(@ptrCast(*const IVdsLun, self), pDriveIdArray, lNumberOfDrives, pullMaxBytesToBeAdded);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IVdsLun2_Value = Guid.initString("e5b3a735-9efb-499a-8071-4394d9ee6fcb");
pub const IID_IVdsLun2 = &IID_IVdsLun2_Value;
pub const IVdsLun2 = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
QueryHints2: fn(
self: *const IVdsLun2,
pHints2: ?*VDS_HINTS2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ApplyHints2: fn(
self: *const IVdsLun2,
pHints2: ?*VDS_HINTS2,
) 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 IVdsLun2_QueryHints2(self: *const T, pHints2: ?*VDS_HINTS2) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsLun2.VTable, self.vtable).QueryHints2(@ptrCast(*const IVdsLun2, self), pHints2);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsLun2_ApplyHints2(self: *const T, pHints2: ?*VDS_HINTS2) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsLun2.VTable, self.vtable).ApplyHints2(@ptrCast(*const IVdsLun2, self), pHints2);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IVdsLunNaming_Value = Guid.initString("907504cb-6b4e-4d88-a34d-17ba661fbb06");
pub const IID_IVdsLunNaming = &IID_IVdsLunNaming_Value;
pub const IVdsLunNaming = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetFriendlyName: fn(
self: *const IVdsLunNaming,
pwszFriendlyName: ?PWSTR,
) 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 IVdsLunNaming_SetFriendlyName(self: *const T, pwszFriendlyName: ?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsLunNaming.VTable, self.vtable).SetFriendlyName(@ptrCast(*const IVdsLunNaming, self), pwszFriendlyName);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IVdsLunNumber_Value = Guid.initString("d3f95e46-54b3-41f9-b678-0f1871443a08");
pub const IID_IVdsLunNumber = &IID_IVdsLunNumber_Value;
pub const IVdsLunNumber = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetLunNumber: fn(
self: *const IVdsLunNumber,
pulLunNumber: ?*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 IVdsLunNumber_GetLunNumber(self: *const T, pulLunNumber: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsLunNumber.VTable, self.vtable).GetLunNumber(@ptrCast(*const IVdsLunNumber, self), pulLunNumber);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IVdsLunControllerPorts_Value = Guid.initString("451fe266-da6d-406a-bb60-82e534f85aeb");
pub const IID_IVdsLunControllerPorts = &IID_IVdsLunControllerPorts_Value;
pub const IVdsLunControllerPorts = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
AssociateControllerPorts: fn(
self: *const IVdsLunControllerPorts,
pActiveControllerPortIdArray: ?[*]Guid,
lNumberOfActiveControllerPorts: i32,
pInactiveControllerPortIdArray: ?[*]Guid,
lNumberOfInactiveControllerPorts: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
QueryActiveControllerPorts: fn(
self: *const IVdsLunControllerPorts,
ppEnum: ?*?*IEnumVdsObject,
) 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 IVdsLunControllerPorts_AssociateControllerPorts(self: *const T, pActiveControllerPortIdArray: ?[*]Guid, lNumberOfActiveControllerPorts: i32, pInactiveControllerPortIdArray: ?[*]Guid, lNumberOfInactiveControllerPorts: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsLunControllerPorts.VTable, self.vtable).AssociateControllerPorts(@ptrCast(*const IVdsLunControllerPorts, self), pActiveControllerPortIdArray, lNumberOfActiveControllerPorts, pInactiveControllerPortIdArray, lNumberOfInactiveControllerPorts);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsLunControllerPorts_QueryActiveControllerPorts(self: *const T, ppEnum: ?*?*IEnumVdsObject) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsLunControllerPorts.VTable, self.vtable).QueryActiveControllerPorts(@ptrCast(*const IVdsLunControllerPorts, self), ppEnum);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IVdsLunMpio_Value = Guid.initString("7c5fbae3-333a-48a1-a982-33c15788cde3");
pub const IID_IVdsLunMpio = &IID_IVdsLunMpio_Value;
pub const IVdsLunMpio = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetPathInfo: fn(
self: *const IVdsLunMpio,
ppPaths: ?[*]?*VDS_PATH_INFO,
plNumberOfPaths: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLoadBalancePolicy: fn(
self: *const IVdsLunMpio,
pPolicy: ?*VDS_LOADBALANCE_POLICY_ENUM,
ppPaths: ?[*]?*VDS_PATH_POLICY,
plNumberOfPaths: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetLoadBalancePolicy: fn(
self: *const IVdsLunMpio,
policy: VDS_LOADBALANCE_POLICY_ENUM,
pPaths: ?[*]VDS_PATH_POLICY,
lNumberOfPaths: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSupportedLbPolicies: fn(
self: *const IVdsLunMpio,
pulLbFlags: ?*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 IVdsLunMpio_GetPathInfo(self: *const T, ppPaths: ?[*]?*VDS_PATH_INFO, plNumberOfPaths: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsLunMpio.VTable, self.vtable).GetPathInfo(@ptrCast(*const IVdsLunMpio, self), ppPaths, plNumberOfPaths);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsLunMpio_GetLoadBalancePolicy(self: *const T, pPolicy: ?*VDS_LOADBALANCE_POLICY_ENUM, ppPaths: ?[*]?*VDS_PATH_POLICY, plNumberOfPaths: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsLunMpio.VTable, self.vtable).GetLoadBalancePolicy(@ptrCast(*const IVdsLunMpio, self), pPolicy, ppPaths, plNumberOfPaths);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsLunMpio_SetLoadBalancePolicy(self: *const T, policy: VDS_LOADBALANCE_POLICY_ENUM, pPaths: ?[*]VDS_PATH_POLICY, lNumberOfPaths: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsLunMpio.VTable, self.vtable).SetLoadBalancePolicy(@ptrCast(*const IVdsLunMpio, self), policy, pPaths, lNumberOfPaths);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsLunMpio_GetSupportedLbPolicies(self: *const T, pulLbFlags: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsLunMpio.VTable, self.vtable).GetSupportedLbPolicies(@ptrCast(*const IVdsLunMpio, self), pulLbFlags);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IVdsLunIscsi_Value = Guid.initString("0d7c1e64-b59b-45ae-b86a-2c2cc6a42067");
pub const IID_IVdsLunIscsi = &IID_IVdsLunIscsi_Value;
pub const IVdsLunIscsi = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
AssociateTargets: fn(
self: *const IVdsLunIscsi,
pTargetIdArray: ?[*]Guid,
lNumberOfTargets: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
QueryAssociatedTargets: fn(
self: *const IVdsLunIscsi,
ppEnum: ?*?*IEnumVdsObject,
) 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 IVdsLunIscsi_AssociateTargets(self: *const T, pTargetIdArray: ?[*]Guid, lNumberOfTargets: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsLunIscsi.VTable, self.vtable).AssociateTargets(@ptrCast(*const IVdsLunIscsi, self), pTargetIdArray, lNumberOfTargets);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsLunIscsi_QueryAssociatedTargets(self: *const T, ppEnum: ?*?*IEnumVdsObject) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsLunIscsi.VTable, self.vtable).QueryAssociatedTargets(@ptrCast(*const IVdsLunIscsi, self), ppEnum);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IVdsLunPlex_Value = Guid.initString("0ee1a790-5d2e-4abb-8c99-c481e8be2138");
pub const IID_IVdsLunPlex = &IID_IVdsLunPlex_Value;
pub const IVdsLunPlex = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetProperties: fn(
self: *const IVdsLunPlex,
pPlexProp: ?*VDS_LUN_PLEX_PROP,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLun: fn(
self: *const IVdsLunPlex,
ppLun: ?*?*IVdsLun,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
QueryExtents: fn(
self: *const IVdsLunPlex,
ppExtentArray: ?[*]?*VDS_DRIVE_EXTENT,
plNumberOfExtents: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
QueryHints: fn(
self: *const IVdsLunPlex,
pHints: ?*VDS_HINTS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ApplyHints: fn(
self: *const IVdsLunPlex,
pHints: ?*VDS_HINTS,
) 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 IVdsLunPlex_GetProperties(self: *const T, pPlexProp: ?*VDS_LUN_PLEX_PROP) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsLunPlex.VTable, self.vtable).GetProperties(@ptrCast(*const IVdsLunPlex, self), pPlexProp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsLunPlex_GetLun(self: *const T, ppLun: ?*?*IVdsLun) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsLunPlex.VTable, self.vtable).GetLun(@ptrCast(*const IVdsLunPlex, self), ppLun);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsLunPlex_QueryExtents(self: *const T, ppExtentArray: ?[*]?*VDS_DRIVE_EXTENT, plNumberOfExtents: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsLunPlex.VTable, self.vtable).QueryExtents(@ptrCast(*const IVdsLunPlex, self), ppExtentArray, plNumberOfExtents);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsLunPlex_QueryHints(self: *const T, pHints: ?*VDS_HINTS) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsLunPlex.VTable, self.vtable).QueryHints(@ptrCast(*const IVdsLunPlex, self), pHints);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsLunPlex_ApplyHints(self: *const T, pHints: ?*VDS_HINTS) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsLunPlex.VTable, self.vtable).ApplyHints(@ptrCast(*const IVdsLunPlex, self), pHints);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IVdsIscsiPortal_Value = Guid.initString("7fa1499d-ec85-4a8a-a47b-ff69201fcd34");
pub const IID_IVdsIscsiPortal = &IID_IVdsIscsiPortal_Value;
pub const IVdsIscsiPortal = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetProperties: fn(
self: *const IVdsIscsiPortal,
pPortalProp: ?*VDS_ISCSI_PORTAL_PROP,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSubSystem: fn(
self: *const IVdsIscsiPortal,
ppSubSystem: ?*?*IVdsSubSystem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
QueryAssociatedPortalGroups: fn(
self: *const IVdsIscsiPortal,
ppEnum: ?*?*IEnumVdsObject,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetStatus: fn(
self: *const IVdsIscsiPortal,
status: VDS_ISCSI_PORTAL_STATUS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetIpsecTunnelAddress: fn(
self: *const IVdsIscsiPortal,
pTunnelAddress: ?*VDS_IPADDRESS,
pDestinationAddress: ?*VDS_IPADDRESS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetIpsecSecurity: fn(
self: *const IVdsIscsiPortal,
pInitiatorPortalAddress: ?*VDS_IPADDRESS,
pullSecurityFlags: ?*u64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetIpsecSecurity: fn(
self: *const IVdsIscsiPortal,
pInitiatorPortalAddress: ?*VDS_IPADDRESS,
ullSecurityFlags: u64,
pIpsecKey: ?*VDS_ISCSI_IPSEC_KEY,
) 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 IVdsIscsiPortal_GetProperties(self: *const T, pPortalProp: ?*VDS_ISCSI_PORTAL_PROP) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsIscsiPortal.VTable, self.vtable).GetProperties(@ptrCast(*const IVdsIscsiPortal, self), pPortalProp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsIscsiPortal_GetSubSystem(self: *const T, ppSubSystem: ?*?*IVdsSubSystem) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsIscsiPortal.VTable, self.vtable).GetSubSystem(@ptrCast(*const IVdsIscsiPortal, self), ppSubSystem);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsIscsiPortal_QueryAssociatedPortalGroups(self: *const T, ppEnum: ?*?*IEnumVdsObject) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsIscsiPortal.VTable, self.vtable).QueryAssociatedPortalGroups(@ptrCast(*const IVdsIscsiPortal, self), ppEnum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsIscsiPortal_SetStatus(self: *const T, status: VDS_ISCSI_PORTAL_STATUS) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsIscsiPortal.VTable, self.vtable).SetStatus(@ptrCast(*const IVdsIscsiPortal, self), status);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsIscsiPortal_SetIpsecTunnelAddress(self: *const T, pTunnelAddress: ?*VDS_IPADDRESS, pDestinationAddress: ?*VDS_IPADDRESS) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsIscsiPortal.VTable, self.vtable).SetIpsecTunnelAddress(@ptrCast(*const IVdsIscsiPortal, self), pTunnelAddress, pDestinationAddress);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsIscsiPortal_GetIpsecSecurity(self: *const T, pInitiatorPortalAddress: ?*VDS_IPADDRESS, pullSecurityFlags: ?*u64) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsIscsiPortal.VTable, self.vtable).GetIpsecSecurity(@ptrCast(*const IVdsIscsiPortal, self), pInitiatorPortalAddress, pullSecurityFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsIscsiPortal_SetIpsecSecurity(self: *const T, pInitiatorPortalAddress: ?*VDS_IPADDRESS, ullSecurityFlags: u64, pIpsecKey: ?*VDS_ISCSI_IPSEC_KEY) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsIscsiPortal.VTable, self.vtable).SetIpsecSecurity(@ptrCast(*const IVdsIscsiPortal, self), pInitiatorPortalAddress, ullSecurityFlags, pIpsecKey);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IVdsIscsiTarget_Value = Guid.initString("aa8f5055-83e5-4bcc-aa73-19851a36a849");
pub const IID_IVdsIscsiTarget = &IID_IVdsIscsiTarget_Value;
pub const IVdsIscsiTarget = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetProperties: fn(
self: *const IVdsIscsiTarget,
pTargetProp: ?*VDS_ISCSI_TARGET_PROP,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSubSystem: fn(
self: *const IVdsIscsiTarget,
ppSubSystem: ?*?*IVdsSubSystem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
QueryPortalGroups: fn(
self: *const IVdsIscsiTarget,
ppEnum: ?*?*IEnumVdsObject,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
QueryAssociatedLuns: fn(
self: *const IVdsIscsiTarget,
ppEnum: ?*?*IEnumVdsObject,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreatePortalGroup: fn(
self: *const IVdsIscsiTarget,
ppAsync: ?*?*IVdsAsync,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Delete: fn(
self: *const IVdsIscsiTarget,
ppAsync: ?*?*IVdsAsync,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetFriendlyName: fn(
self: *const IVdsIscsiTarget,
pwszFriendlyName: ?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetSharedSecret: fn(
self: *const IVdsIscsiTarget,
pTargetSharedSecret: ?*VDS_ISCSI_SHARED_SECRET,
pwszInitiatorName: ?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RememberInitiatorSharedSecret: fn(
self: *const IVdsIscsiTarget,
pwszInitiatorName: ?PWSTR,
pInitiatorSharedSecret: ?*VDS_ISCSI_SHARED_SECRET,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetConnectedInitiators: fn(
self: *const IVdsIscsiTarget,
pppwszInitiatorList: ?[*]?*?PWSTR,
plNumberOfInitiators: ?*i32,
) 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 IVdsIscsiTarget_GetProperties(self: *const T, pTargetProp: ?*VDS_ISCSI_TARGET_PROP) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsIscsiTarget.VTable, self.vtable).GetProperties(@ptrCast(*const IVdsIscsiTarget, self), pTargetProp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsIscsiTarget_GetSubSystem(self: *const T, ppSubSystem: ?*?*IVdsSubSystem) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsIscsiTarget.VTable, self.vtable).GetSubSystem(@ptrCast(*const IVdsIscsiTarget, self), ppSubSystem);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsIscsiTarget_QueryPortalGroups(self: *const T, ppEnum: ?*?*IEnumVdsObject) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsIscsiTarget.VTable, self.vtable).QueryPortalGroups(@ptrCast(*const IVdsIscsiTarget, self), ppEnum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsIscsiTarget_QueryAssociatedLuns(self: *const T, ppEnum: ?*?*IEnumVdsObject) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsIscsiTarget.VTable, self.vtable).QueryAssociatedLuns(@ptrCast(*const IVdsIscsiTarget, self), ppEnum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsIscsiTarget_CreatePortalGroup(self: *const T, ppAsync: ?*?*IVdsAsync) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsIscsiTarget.VTable, self.vtable).CreatePortalGroup(@ptrCast(*const IVdsIscsiTarget, self), ppAsync);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsIscsiTarget_Delete(self: *const T, ppAsync: ?*?*IVdsAsync) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsIscsiTarget.VTable, self.vtable).Delete(@ptrCast(*const IVdsIscsiTarget, self), ppAsync);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsIscsiTarget_SetFriendlyName(self: *const T, pwszFriendlyName: ?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsIscsiTarget.VTable, self.vtable).SetFriendlyName(@ptrCast(*const IVdsIscsiTarget, self), pwszFriendlyName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsIscsiTarget_SetSharedSecret(self: *const T, pTargetSharedSecret: ?*VDS_ISCSI_SHARED_SECRET, pwszInitiatorName: ?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsIscsiTarget.VTable, self.vtable).SetSharedSecret(@ptrCast(*const IVdsIscsiTarget, self), pTargetSharedSecret, pwszInitiatorName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsIscsiTarget_RememberInitiatorSharedSecret(self: *const T, pwszInitiatorName: ?PWSTR, pInitiatorSharedSecret: ?*VDS_ISCSI_SHARED_SECRET) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsIscsiTarget.VTable, self.vtable).RememberInitiatorSharedSecret(@ptrCast(*const IVdsIscsiTarget, self), pwszInitiatorName, pInitiatorSharedSecret);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsIscsiTarget_GetConnectedInitiators(self: *const T, pppwszInitiatorList: ?[*]?*?PWSTR, plNumberOfInitiators: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsIscsiTarget.VTable, self.vtable).GetConnectedInitiators(@ptrCast(*const IVdsIscsiTarget, self), pppwszInitiatorList, plNumberOfInitiators);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IVdsIscsiPortalGroup_Value = Guid.initString("fef5f89d-a3dd-4b36-bf28-e7dde045c593");
pub const IID_IVdsIscsiPortalGroup = &IID_IVdsIscsiPortalGroup_Value;
pub const IVdsIscsiPortalGroup = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetProperties: fn(
self: *const IVdsIscsiPortalGroup,
pPortalGroupProp: ?*VDS_ISCSI_PORTALGROUP_PROP,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetTarget: fn(
self: *const IVdsIscsiPortalGroup,
ppTarget: ?*?*IVdsIscsiTarget,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
QueryAssociatedPortals: fn(
self: *const IVdsIscsiPortalGroup,
ppEnum: ?*?*IEnumVdsObject,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddPortal: fn(
self: *const IVdsIscsiPortalGroup,
portalId: Guid,
ppAsync: ?*?*IVdsAsync,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemovePortal: fn(
self: *const IVdsIscsiPortalGroup,
portalId: Guid,
ppAsync: ?*?*IVdsAsync,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Delete: fn(
self: *const IVdsIscsiPortalGroup,
ppAsync: ?*?*IVdsAsync,
) 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 IVdsIscsiPortalGroup_GetProperties(self: *const T, pPortalGroupProp: ?*VDS_ISCSI_PORTALGROUP_PROP) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsIscsiPortalGroup.VTable, self.vtable).GetProperties(@ptrCast(*const IVdsIscsiPortalGroup, self), pPortalGroupProp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsIscsiPortalGroup_GetTarget(self: *const T, ppTarget: ?*?*IVdsIscsiTarget) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsIscsiPortalGroup.VTable, self.vtable).GetTarget(@ptrCast(*const IVdsIscsiPortalGroup, self), ppTarget);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsIscsiPortalGroup_QueryAssociatedPortals(self: *const T, ppEnum: ?*?*IEnumVdsObject) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsIscsiPortalGroup.VTable, self.vtable).QueryAssociatedPortals(@ptrCast(*const IVdsIscsiPortalGroup, self), ppEnum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsIscsiPortalGroup_AddPortal(self: *const T, portalId: Guid, ppAsync: ?*?*IVdsAsync) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsIscsiPortalGroup.VTable, self.vtable).AddPortal(@ptrCast(*const IVdsIscsiPortalGroup, self), portalId, ppAsync);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsIscsiPortalGroup_RemovePortal(self: *const T, portalId: Guid, ppAsync: ?*?*IVdsAsync) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsIscsiPortalGroup.VTable, self.vtable).RemovePortal(@ptrCast(*const IVdsIscsiPortalGroup, self), portalId, ppAsync);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsIscsiPortalGroup_Delete(self: *const T, ppAsync: ?*?*IVdsAsync) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsIscsiPortalGroup.VTable, self.vtable).Delete(@ptrCast(*const IVdsIscsiPortalGroup, self), ppAsync);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IVdsStoragePool_Value = Guid.initString("932ca8cf-0eb3-4ba8-9620-22665d7f8450");
pub const IID_IVdsStoragePool = &IID_IVdsStoragePool_Value;
pub const IVdsStoragePool = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetProvider: fn(
self: *const IVdsStoragePool,
ppProvider: ?*?*IVdsProvider,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetProperties: fn(
self: *const IVdsStoragePool,
pStoragePoolProp: ?*VDS_STORAGE_POOL_PROP,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetAttributes: fn(
self: *const IVdsStoragePool,
pStoragePoolAttributes: ?*VDS_POOL_ATTRIBUTES,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
QueryDriveExtents: fn(
self: *const IVdsStoragePool,
ppExtentArray: ?[*]?*VDS_STORAGE_POOL_DRIVE_EXTENT,
plNumberOfExtents: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
QueryAllocatedLuns: fn(
self: *const IVdsStoragePool,
ppEnum: ?*?*IEnumVdsObject,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
QueryAllocatedStoragePools: fn(
self: *const IVdsStoragePool,
ppEnum: ?*?*IEnumVdsObject,
) 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 IVdsStoragePool_GetProvider(self: *const T, ppProvider: ?*?*IVdsProvider) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsStoragePool.VTable, self.vtable).GetProvider(@ptrCast(*const IVdsStoragePool, self), ppProvider);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsStoragePool_GetProperties(self: *const T, pStoragePoolProp: ?*VDS_STORAGE_POOL_PROP) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsStoragePool.VTable, self.vtable).GetProperties(@ptrCast(*const IVdsStoragePool, self), pStoragePoolProp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsStoragePool_GetAttributes(self: *const T, pStoragePoolAttributes: ?*VDS_POOL_ATTRIBUTES) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsStoragePool.VTable, self.vtable).GetAttributes(@ptrCast(*const IVdsStoragePool, self), pStoragePoolAttributes);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsStoragePool_QueryDriveExtents(self: *const T, ppExtentArray: ?[*]?*VDS_STORAGE_POOL_DRIVE_EXTENT, plNumberOfExtents: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsStoragePool.VTable, self.vtable).QueryDriveExtents(@ptrCast(*const IVdsStoragePool, self), ppExtentArray, plNumberOfExtents);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsStoragePool_QueryAllocatedLuns(self: *const T, ppEnum: ?*?*IEnumVdsObject) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsStoragePool.VTable, self.vtable).QueryAllocatedLuns(@ptrCast(*const IVdsStoragePool, self), ppEnum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsStoragePool_QueryAllocatedStoragePools(self: *const T, ppEnum: ?*?*IEnumVdsObject) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsStoragePool.VTable, self.vtable).QueryAllocatedStoragePools(@ptrCast(*const IVdsStoragePool, self), ppEnum);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IVdsMaintenance_Value = Guid.initString("daebeef3-8523-47ed-a2b9-05cecce2a1ae");
pub const IID_IVdsMaintenance = &IID_IVdsMaintenance_Value;
pub const IVdsMaintenance = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
StartMaintenance: fn(
self: *const IVdsMaintenance,
operation: VDS_MAINTENANCE_OPERATION,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
StopMaintenance: fn(
self: *const IVdsMaintenance,
operation: VDS_MAINTENANCE_OPERATION,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
PulseMaintenance: fn(
self: *const IVdsMaintenance,
operation: VDS_MAINTENANCE_OPERATION,
ulCount: 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 IVdsMaintenance_StartMaintenance(self: *const T, operation: VDS_MAINTENANCE_OPERATION) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsMaintenance.VTable, self.vtable).StartMaintenance(@ptrCast(*const IVdsMaintenance, self), operation);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsMaintenance_StopMaintenance(self: *const T, operation: VDS_MAINTENANCE_OPERATION) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsMaintenance.VTable, self.vtable).StopMaintenance(@ptrCast(*const IVdsMaintenance, self), operation);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsMaintenance_PulseMaintenance(self: *const T, operation: VDS_MAINTENANCE_OPERATION, ulCount: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsMaintenance.VTable, self.vtable).PulseMaintenance(@ptrCast(*const IVdsMaintenance, self), operation, ulCount);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IVdsHwProviderPrivate_Value = Guid.initString("98f17bf3-9f33-4f12-8714-8b4075092c2e");
pub const IID_IVdsHwProviderPrivate = &IID_IVdsHwProviderPrivate_Value;
pub const IVdsHwProviderPrivate = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
QueryIfCreatedLun: fn(
self: *const IVdsHwProviderPrivate,
pwszDevicePath: ?PWSTR,
pVdsLunInformation: ?*VDS_LUN_INFORMATION,
pLunId: ?*Guid,
) 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 IVdsHwProviderPrivate_QueryIfCreatedLun(self: *const T, pwszDevicePath: ?PWSTR, pVdsLunInformation: ?*VDS_LUN_INFORMATION, pLunId: ?*Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsHwProviderPrivate.VTable, self.vtable).QueryIfCreatedLun(@ptrCast(*const IVdsHwProviderPrivate, self), pwszDevicePath, pVdsLunInformation, pLunId);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IVdsHwProviderPrivateMpio_Value = Guid.initString("310a7715-ac2b-4c6f-9827-3d742f351676");
pub const IID_IVdsHwProviderPrivateMpio = &IID_IVdsHwProviderPrivateMpio_Value;
pub const IVdsHwProviderPrivateMpio = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetAllPathStatusesFromHbaPort: fn(
self: *const IVdsHwProviderPrivateMpio,
hbaPortProp: VDS_HBAPORT_PROP,
status: VDS_PATH_STATUS,
) 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 IVdsHwProviderPrivateMpio_SetAllPathStatusesFromHbaPort(self: *const T, hbaPortProp: VDS_HBAPORT_PROP, status: VDS_PATH_STATUS) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsHwProviderPrivateMpio.VTable, self.vtable).SetAllPathStatusesFromHbaPort(@ptrCast(*const IVdsHwProviderPrivateMpio, self), hbaPortProp, status);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IVdsAdmin_Value = Guid.initString("d188e97d-85aa-4d33-abc6-26299a10ffc1");
pub const IID_IVdsAdmin = &IID_IVdsAdmin_Value;
pub const IVdsAdmin = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
RegisterProvider: fn(
self: *const IVdsAdmin,
providerId: Guid,
providerClsid: Guid,
pwszName: ?PWSTR,
type: VDS_PROVIDER_TYPE,
pwszMachineName: ?PWSTR,
pwszVersion: ?PWSTR,
guidVersionId: Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
UnregisterProvider: fn(
self: *const IVdsAdmin,
providerId: Guid,
) 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 IVdsAdmin_RegisterProvider(self: *const T, providerId: Guid, providerClsid: Guid, pwszName: ?PWSTR, type_: VDS_PROVIDER_TYPE, pwszMachineName: ?PWSTR, pwszVersion: ?PWSTR, guidVersionId: Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsAdmin.VTable, self.vtable).RegisterProvider(@ptrCast(*const IVdsAdmin, self), providerId, providerClsid, pwszName, type_, pwszMachineName, pwszVersion, guidVersionId);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVdsAdmin_UnregisterProvider(self: *const T, providerId: Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const IVdsAdmin.VTable, self.vtable).UnregisterProvider(@ptrCast(*const IVdsAdmin, self), providerId);
}
};}
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 (5)
//--------------------------------------------------------------------------------
const Guid = @import("../zig.zig").Guid;
const BOOL = @import("../foundation.zig").BOOL;
const HRESULT = @import("../foundation.zig").HRESULT;
const IUnknown = @import("../system/com.zig").IUnknown;
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/storage/virtual_disk_service.zig |
const std = @import("std");
pub fn Combinator(comptime Left: type, comptime Right: type) type {
return struct {
const Self = @This();
/// Take two enum types and yield a new enum that contains the cross product of them.
/// Enum values are ignored to guarantee there are no collisions.
/// Names are directly concatenated, left ++ right.
pub const Cross = blk: {
const lefts = std.meta.fields(Left);
const rights = std.meta.fields(Right);
var enumFields: [lefts.len * rights.len]std.builtin.TypeInfo.EnumField = undefined;
var decls = [_]std.builtin.TypeInfo.Declaration{};
var i: usize = 0;
inline for (lefts) |left, li| {
if (left.value != li) {
@compileLog(Left, left.name, left.value);
@compileError("Enums must not override ordinal values");
}
inline for (rights) |right, ri| {
if (right.value != ri) {
@compileLog(Right, right.name, right.value);
@compileError("Enums must not override ordinal values");
}
enumFields[i] = .{
.name = left.name ++ right.name,
.value = i,
};
i += 1;
}
}
break :blk @Type(.{
.Enum = .{
.layout = .Auto,
.tag_type = std.math.IntFittingRange(0, i - 1),
.fields = &enumFields,
.decls = &decls,
.is_exhaustive = true,
},
});
};
/// Yield the cross-product value of two comptime-known enum values
pub fn cross(left: Left, right: Right) Self.Cross {
return @intToEnum(Self.Cross, @enumToInt(left) * std.meta.fields(Right).len + @enumToInt(right));
}
};
}
test "Cross" {
const E1 = enum(u3) { x, y };
const E2 = enum { a, b };
const E1E2 = Combinator(E1, E2);
const names = std.meta.fieldNames(E1E2.Cross);
try std.testing.expectEqualStrings("xa", names[0]);
try std.testing.expectEqualStrings("xb", names[1]);
try std.testing.expectEqualStrings("ya", names[2]);
try std.testing.expectEqualStrings("yb", names[3]);
try std.testing.expectEqual(@enumToInt(E1E2.cross(.x, .b)), @enumToInt(E1E2.Cross.xb));
} | src/util/enums.zig |
const std = @import("std");
const expect = std.testing.expect;
pub const CyclicBarrier = struct {
pub const Node = struct {
status: i32=1,
prev: ?*Node=null,
resetEvent: std.ResetEvent,
};
rounds: u32 = 0,
parties: u32,
count: u32,
broken: bool=false,
link: ?*Node = null,
mutex: std.Mutex=std.Mutex{},
const Self = @This();
pub fn init(parties: u32) Self {
return Self {.parties = parties, .count=parties};
}
pub fn getParties(self: *const Self) u32 {
return self.parties;
}
pub fn isBroken(self: *Self) bool {
var lock = self.mutex.acquire();
defer lock.release();
return self.broken;
}
pub fn wait(self: *Self) !void {
var lock = self.mutex.acquire();
if(self.broken == true){
lock.release();
return error.BARRIER_BROEKN;
}
if(self.parties == 0){
lock.release();
return;
}
if(self.count <= 1){
if(self.parties == 1){
self.rounds +%= 1;
lock.release();
return;
}
self.reset_barrier();
lock.release();
return;
}
var node = Node{.status = 1, .resetEvent = std.ResetEvent.init()};
defer node.resetEvent.deinit();
self.add_waiter(&node);
self.count -= 1;
lock.release();
node.resetEvent.wait();
var val = @atomicLoad(i32, &node.status, .Acquire);
if(val == 0){
return;
}
if(val == 1){
std.debug.print("unexpected wakeup\n", .{});
unreachable;
}
if(val == 2){
return error.BARRIER_BROEKN;
}
}
pub fn timedWait(self: *Self, timeout: u64) !void {
var lock = self.mutex.acquire();
if(self.broken == true){
lock.release();
return error.BARRIER_BROEKN;
}
if(self.parties == 0){
lock.release();
return;
}
if(self.count <= 1){
expect(self.count == 1);
if(self.parties == 1){
self.rounds +%= 1;
lock.release();
return;
}
self.reset_barrier();
lock.release();
return;
}
var node = Node{.status = 1, .resetEvent = std.ResetEvent.init()};
defer node.resetEvent.deinit();
self.add_waiter(&node);
self.count -= 1;
lock.release();
var ret = node.resetEvent.timedWait(timeout);
if(ret) |_| {
if(node.status == 0){
return;
}
if(node.status == 2){
return error.BARRIER_BROEKN;
}
expect(node.status == 1);
} else |err| {
lock = self.mutex.acquire();
defer lock.release();
if(node.status == 0){
return;
}
if(node.status == 2){
return error.BARRIER_BROEKN;
}
expect(node.status == 1);
self.break_barrier();
return error.TimedOut;
}
}
fn set_status_all(self: *Self, status: i32) void{
expect(self.link != null);
var node: ?*Node = self.link;
while(node != null) {
const cur = node.?;
node = cur.prev;
cur.prev = null;
cur.status = status;
cur.resetEvent.set();
}
}
pub fn break_all(self: *Self) void {
self.set_status_all(2);
}
pub fn wakeup_all(self: *Self) void {
self.set_status_all(0);
}
fn add_waiter(self: *Self, node: *Node) void {
if(self.link == null){
self.link = node;
} else {
node.prev = self.link;
self.link = node;
}
}
fn reset_barrier(self: *Self) void {
self.count = self.parties;
self.rounds +%= 1;
self.broken = false;
self.wakeup_all();
self.link = null;
}
fn break_barrier(self: *Self) void {
self.count = self.parties;
self.broken = true;
self.break_all();
self.link = null;
}
}; | CyclicBarrier.zig |
const std = @import("std");
const builtin = @import("builtin");
pub const PlayerCount = 4;
const StartingCoins = 3;
const LoRollEstablishmentPileCount = 5;
const HiRollEstablishmentPileCount = 5;
const MajorEstablishmentPileCount = 2;
//const verboseMode = (builtin.mode == builtin.Mode.Debug);
const verboseMode = false;
pub const BotCode = struct {
shouldRollTwoDiceFunc: fn (*GameState) bool,
getCardToPurchaseFunc: fn (*GameState) ?PurchasableCard,
shouldActivateHarborFunc: fn (*GameState) bool,
shouldReroll: fn (*GameState) bool,
getPlayerToStealCoinsFrom: fn (*GameState, u32) usize,
};
const ActivationTurn = enum {
Any,
You,
Els,
};
pub const CardIcon = enum {
Wheat,
Cow,
Cog,
Box,
Cup,
Factory,
Tower,
Boat,
Briefcase,
};
pub const CardType = enum {
Landmark,
Establishment,
};
const MultiplyType = enum {
CardIcon,
EstablishmentType,
};
const CoinMultiplier = struct {
type: MultiplyType,
index: usize,
fn initIcon(icon: CardIcon) CoinMultiplier {
return CoinMultiplier{
.type = MultiplyType.CardIcon,
.index = @enumToInt(icon),
};
}
fn initEst(estType: EstablishmentType) CoinMultiplier {
return CoinMultiplier{
.type = MultiplyType.EstablishmentType,
.index = @enumToInt(estType),
};
}
};
pub const PurchasableCard = struct {
type: CardType,
index: usize,
};
// City Hall?
pub const Landmark = enum {
Harbor,
TrainStation,
ShoppingMall,
AmusementPark,
RadioTower,
Airport,
};
const EstablishmentDeck = enum {
LowCost,
HighCost,
Major,
};
pub const EstablishmentType = enum {
// Primary Industry (Blue)
WheatField,
Ranch,
FlowerOrchard,
Forest,
Vineyard,
MackerelBoat,
Mine,
AppleOrchard,
TunaBoat,
// Secondary Industry (Green)
Bakery,
ConvenienceStore,
FlowerShop,
CheeseFactory,
FurnitureFactory,
FarmersMarket,
FoodWarehouse,
// Restaurant (Red)
SushiBar,
Cafe,
PizzaJoint,
HamburgerStand,
FamilyRestaurant,
// Major Establishment (Purple)
Stadium,
TVStation,
BusinessCentre,
Publisher,
TaxOffice,
};
const Establishment = struct {
type: EstablishmentType,
cost: i32,
activationMin: u32,
activationMax: u32,
activationTurn: ActivationTurn,
coinsGiven: i32,
icon: CardIcon,
multiplier: ?CoinMultiplier,
pub fn init(cost: i32, actMin: u32, actMax: u32, turn: ActivationTurn, coinsGiven: i32, icon: CardIcon, estType: EstablishmentType, multiplier: ?CoinMultiplier) Establishment {
return Establishment{
.type = estType,
.cost = cost,
.activationMin = actMin,
.activationMax = actMax,
.activationTurn = turn,
.coinsGiven = coinsGiven,
.icon = icon,
.multiplier = multiplier,
};
}
fn deck(self: *const Establishment) EstablishmentDeck {
if (self.icon == CardIcon.Tower) return EstablishmentDeck.Major;
if (self.activationMin <= 6) return EstablishmentDeck.LowCost;
return EstablishmentDeck.HighCost;
}
};
pub const allEstablishments: [@memberCount(EstablishmentType)]Establishment = [_]Establishment{
Establishment.init(1, 1, 1, ActivationTurn.Any, 1, CardIcon.Wheat, EstablishmentType.WheatField, null),
Establishment.init(1, 2, 2, ActivationTurn.Any, 1, CardIcon.Cow, EstablishmentType.Ranch, null),
Establishment.init(2, 4, 4, ActivationTurn.Any, 1, CardIcon.Wheat, EstablishmentType.FlowerOrchard, null),
Establishment.init(3, 5, 5, ActivationTurn.Any, 1, CardIcon.Cog, EstablishmentType.Forest, null),
Establishment.init(3, 7, 7, ActivationTurn.Any, 3, CardIcon.Wheat, EstablishmentType.Vineyard, null),
Establishment.init(2, 8, 8, ActivationTurn.Any, 3, CardIcon.Boat, EstablishmentType.MackerelBoat, null),
Establishment.init(6, 9, 9, ActivationTurn.Any, 5, CardIcon.Cog, EstablishmentType.Mine, null),
Establishment.init(3, 10, 10, ActivationTurn.Any, 3, CardIcon.Wheat, EstablishmentType.AppleOrchard, null),
Establishment.init(5, 12, 14, ActivationTurn.Any, 0, CardIcon.Boat, EstablishmentType.TunaBoat, null),
Establishment.init(1, 2, 3, ActivationTurn.You, 1, CardIcon.Box, EstablishmentType.Bakery, null),
Establishment.init(2, 4, 4, ActivationTurn.You, 3, CardIcon.Box, EstablishmentType.ConvenienceStore, null),
Establishment.init(1, 6, 6, ActivationTurn.You, 1, CardIcon.Box, EstablishmentType.FlowerShop, CoinMultiplier.initEst(EstablishmentType.FlowerOrchard)),
Establishment.init(5, 7, 7, ActivationTurn.You, 3, CardIcon.Factory, EstablishmentType.CheeseFactory, CoinMultiplier.initIcon(CardIcon.Cow)),
Establishment.init(3, 8, 8, ActivationTurn.You, 3, CardIcon.Factory, EstablishmentType.FurnitureFactory, CoinMultiplier.initIcon(CardIcon.Cog)),
Establishment.init(2, 11, 12, ActivationTurn.You, 2, CardIcon.Factory, EstablishmentType.FarmersMarket, CoinMultiplier.initIcon(CardIcon.Wheat)),
Establishment.init(2, 12, 13, ActivationTurn.You, 2, CardIcon.Factory, EstablishmentType.FoodWarehouse, CoinMultiplier.initIcon(CardIcon.Cup)),
Establishment.init(4, 1, 1, ActivationTurn.Els, 3, CardIcon.Cup, EstablishmentType.SushiBar, null),
Establishment.init(2, 3, 3, ActivationTurn.Els, 1, CardIcon.Cup, EstablishmentType.Cafe, null),
Establishment.init(1, 7, 7, ActivationTurn.Els, 1, CardIcon.Cup, EstablishmentType.PizzaJoint, null),
Establishment.init(1, 8, 8, ActivationTurn.Els, 1, CardIcon.Cup, EstablishmentType.HamburgerStand, null),
Establishment.init(3, 9, 10, ActivationTurn.Els, 2, CardIcon.Cup, EstablishmentType.FamilyRestaurant, null),
Establishment.init(6, 6, 6, ActivationTurn.You, 0, CardIcon.Tower, EstablishmentType.Stadium, null),
Establishment.init(7, 6, 6, ActivationTurn.You, 0, CardIcon.Tower, EstablishmentType.TVStation, null),
Establishment.init(8, 6, 6, ActivationTurn.You, 0, CardIcon.Tower, EstablishmentType.BusinessCentre, null),
Establishment.init(5, 7, 7, ActivationTurn.You, 0, CardIcon.Tower, EstablishmentType.Publisher, null),
Establishment.init(4, 8, 9, ActivationTurn.You, 0, CardIcon.Tower, EstablishmentType.TaxOffice, null),
// TODO: Extras
//Establishment.init(0, 2, 2, ActivationTurn.You, 2, CardIcon.Box, EstablishmentType.GeneralStore, null), // TODO: Requires 0 or 1 built landmarks
//Establishment.init(3, 5, 5, ActivationTurn.Els, 5, CardIcon.Cup, EstablishmentType.FrenchRestaurant, null), // TODO: Requires the opponent as at least 2 landmarks built
//Establishment.init(-5, 5, 6, ActivationTurn.You, -2, CardIcon.Briefcase, EstablishmentType.LoanOffice, null), // TODO: Only lose coins if you can (IE never get negative coins)
//Establishment.init(2, 3, 4, ActivationTurn.Any, 1, CardIcon.Wheat, EstablishmentType.CornField, null), // TODO: Requires 0 or 1 landmarks
//Establishment.init(2, 4, 4, ActivationTurn.You, 0, CardIcon.Briefcase, EstablishmentType.DemolitionCompany, null), // TODO: You may demolish a built landmark to get 8 coins
//Establishment.init(2, 9, 10, ActivationTurn.You, 0, CardIcon.Briefcase, EstablishmentType.MovingCompany, null), // TODO: Get 4 coins if you give a non-tower establishment to an opponent
//Establishment.init(5, 11, 11, ActivationTurn.You, 1, CardIcon.Factory, EstablishmentType.SodaBottlingPlant, CardIcon.Cup), // TODO: Also multiply by the number of cups owned by all other players (IE all players in total)
//Establishment.init(3, 9, 9, AcitvationTurn.You, 6, CardIcon.Factory, EstablishmentType.Winery, null), // TODO: Multiply by the number of vineyards you own, then close for renovation
//Establishment.init(4, 12, 14, ActivationTurn.Els, 0, CardIcon.Cup, EstablishmentType.PrivateClub, null), // TODO: Require that the other player has at least 3 built landmarks, take all their money
//Establishment.init(4, 8, 8, ActivationTurn.You, 0, CardIcon.Tower, EstablishmentType.RenovationCompany, null), // TODO: Close all copies of any 1 establishment in play for renovation. Take 1 coin from each opponent for each establishment they own that was closed this way
//Establishment.init(3, 11, 13, ActivationTurn.You, 0, CardIcon.Tower, EstablishmentType.Park, null), // TODO: Redistribute all players coins as evenly as possible, making up any difference with coins from the bank
//Establishment.init(7, 10, 10, ActivationTurn.You, 0, CardIcon.Tower, EstablishmentType.ExhibitHall, null), // TODO: May activate 1 of your non-tower establishments instead of this one. If you do, return this establishment to the supply
//Establishment.init(1, 10, 10, ActivationTurn.You, 0, CardIcon.Tower, EstablishmentType.TechStartup, null), // TODO: At the end of each of your turns, you may add 1 coin to this card. When activated, take coins from each opponent equal to the amount on this card
};
fn enumToEstablishment(estType: EstablishmentType) *const Establishment {
return &allEstablishments[@enumToInt(estType)];
}
const GamePlayerState = struct {
coins: i32,
landmarks: [@memberCount(Landmark)]bool,
establishmentsAnyTurn: std.ArrayList(*const Establishment),
establishmentsYourTurn: std.ArrayList(*const Establishment),
establishmentsOtherTurns: std.ArrayList(*const Establishment),
totalCoinsEarned: [@memberCount(EstablishmentType)]i64,
pub fn addEstablishment(self: *@This(), est: *const Establishment) !void {
self.coins -= est.cost;
try switch (est.activationTurn) {
ActivationTurn.Any => self.establishmentsAnyTurn.append(est),
ActivationTurn.You => self.establishmentsYourTurn.append(est),
ActivationTurn.Els => self.establishmentsOtherTurns.append(est),
};
}
};
const EstablishmentPurchasingPile = struct {
establishment: *const Establishment,
count: u32,
};
pub const GameState = struct {
currentTurn: u32,
currentPlayerIndex: u32,
rng: *std.rand.Xoroshiro128,
players: [PlayerCount]GamePlayerState,
alloc: *std.mem.Allocator,
establishmentPurchasePiles: [@memberCount(EstablishmentType)]u8,
loEstablishmentDeck: std.ArrayList(*const Establishment),
hiEstablishmentDeck: std.ArrayList(*const Establishment),
majorEstablishmentDeck: std.ArrayList(*const Establishment),
bot: BotCode,
pub fn init(alloc: *std.mem.Allocator, rng: *std.rand.Xoroshiro128, bot: BotCode) !GameState {
for (allEstablishments) |est, estIndex| {
if (estIndex != @enumToInt(est.type)) {
std.debug.panic("Establishment {} expected at index {}, found at index {}!", est.type, @enumToInt(est.type), estIndex);
}
}
var result = GameState{
.currentTurn = 0,
.currentPlayerIndex = 0,
.rng = rng,
.players = [_]GamePlayerState{undefined} ** PlayerCount,
.alloc = alloc,
.establishmentPurchasePiles = [_]u8{0} ** @memberCount(EstablishmentType),
.loEstablishmentDeck = std.ArrayList(*const Establishment).init(alloc),
.hiEstablishmentDeck = std.ArrayList(*const Establishment).init(alloc),
.majorEstablishmentDeck = std.ArrayList(*const Establishment).init(alloc),
.bot = bot,
};
try addEstablishmentToDeck(&result.loEstablishmentDeck, 6, EstablishmentType.WheatField);
try addEstablishmentToDeck(&result.loEstablishmentDeck, 6, EstablishmentType.Ranch);
try addEstablishmentToDeck(&result.loEstablishmentDeck, 6, EstablishmentType.FlowerOrchard);
try addEstablishmentToDeck(&result.loEstablishmentDeck, 6, EstablishmentType.Forest);
try addEstablishmentToDeck(&result.loEstablishmentDeck, 6, EstablishmentType.Bakery);
try addEstablishmentToDeck(&result.loEstablishmentDeck, 6, EstablishmentType.ConvenienceStore);
try addEstablishmentToDeck(&result.loEstablishmentDeck, 6, EstablishmentType.FlowerShop);
try addEstablishmentToDeck(&result.loEstablishmentDeck, 6, EstablishmentType.SushiBar);
try addEstablishmentToDeck(&result.loEstablishmentDeck, 6, EstablishmentType.Cafe);
result.rng.random.shuffle(*const Establishment, result.loEstablishmentDeck.toSlice());
try addEstablishmentToDeck(&result.hiEstablishmentDeck, 6, EstablishmentType.Vineyard);
try addEstablishmentToDeck(&result.hiEstablishmentDeck, 6, EstablishmentType.MackerelBoat);
try addEstablishmentToDeck(&result.hiEstablishmentDeck, 6, EstablishmentType.Mine);
try addEstablishmentToDeck(&result.hiEstablishmentDeck, 6, EstablishmentType.AppleOrchard);
try addEstablishmentToDeck(&result.hiEstablishmentDeck, 6, EstablishmentType.TunaBoat);
try addEstablishmentToDeck(&result.hiEstablishmentDeck, 6, EstablishmentType.CheeseFactory);
try addEstablishmentToDeck(&result.hiEstablishmentDeck, 6, EstablishmentType.FurnitureFactory);
try addEstablishmentToDeck(&result.hiEstablishmentDeck, 6, EstablishmentType.FarmersMarket);
try addEstablishmentToDeck(&result.hiEstablishmentDeck, 6, EstablishmentType.FoodWarehouse);
try addEstablishmentToDeck(&result.hiEstablishmentDeck, 6, EstablishmentType.PizzaJoint);
try addEstablishmentToDeck(&result.hiEstablishmentDeck, 6, EstablishmentType.HamburgerStand);
try addEstablishmentToDeck(&result.hiEstablishmentDeck, 6, EstablishmentType.FamilyRestaurant);
result.rng.random.shuffle(*const Establishment, result.hiEstablishmentDeck.toSlice());
try addEstablishmentToDeck(&result.majorEstablishmentDeck, 4, EstablishmentType.Stadium);
try addEstablishmentToDeck(&result.majorEstablishmentDeck, 4, EstablishmentType.TVStation);
try addEstablishmentToDeck(&result.majorEstablishmentDeck, 4, EstablishmentType.Publisher);
try addEstablishmentToDeck(&result.majorEstablishmentDeck, 4, EstablishmentType.TaxOffice);
result.rng.random.shuffle(*const Establishment, result.majorEstablishmentDeck.toSlice());
var pid: usize = 0;
while (pid < PlayerCount) {
defer pid += 1;
result.players[pid].coins = StartingCoins;
result.players[pid].landmarks = [_]bool{false} ** @memberCount(Landmark);
result.players[pid].establishmentsAnyTurn = std.ArrayList(*const Establishment).init(alloc);
result.players[pid].establishmentsYourTurn = std.ArrayList(*const Establishment).init(alloc);
result.players[pid].establishmentsOtherTurns = std.ArrayList(*const Establishment).init(alloc);
result.players[pid].totalCoinsEarned = [_]i64{0} ** @memberCount(EstablishmentType);
try result.players[pid].establishmentsAnyTurn.append(enumToEstablishment(EstablishmentType.WheatField));
try result.players[pid].establishmentsYourTurn.append(enumToEstablishment(EstablishmentType.Bakery));
}
var i: usize = 0;
while (i < LoRollEstablishmentPileCount) {
result.createEstablishmentPile(&result.loEstablishmentDeck);
i += 1;
}
i = 0;
while (i < HiRollEstablishmentPileCount) {
result.createEstablishmentPile(&result.hiEstablishmentDeck);
i += 1;
}
i = 0;
while (i < MajorEstablishmentPileCount) {
result.createEstablishmentPile(&result.majorEstablishmentDeck);
i += 1;
}
return result;
}
fn addEstablishmentToDeck(deck: *std.ArrayList(*const Establishment), count: usize, estType: EstablishmentType) !void {
const est = &allEstablishments[@enumToInt(estType)];
var i: usize = 0;
while (i < count) {
try deck.append(est);
i += 1;
}
}
fn createEstablishmentPile(self: *GameState, deck: *std.ArrayList(*const Establishment)) void {
while (deck.len > 0) {
const est = deck.pop();
const pileSize = &self.establishmentPurchasePiles[@enumToInt(est.type)];
if (pileSize.* > 0) {
pileSize.* += 1;
continue;
}
pileSize.* = 1;
break;
}
}
fn print(self: *GameState) void {
std.debug.warn("Current Turn: {}\n", self.currentTurn);
std.debug.warn("Current Player: {}\n", self.currentPlayerIndex);
std.debug.warn("Low-cost establishment deck has {} cards remaining\n", self.loEstablishmentDeck.count());
std.debug.warn("High-cost establishment deck has {} cards remaining\n", self.hiEstablishmentDeck.count());
std.debug.warn("Major establishment deck has {} cards remaining\n", self.majorEstablishmentDeck.count());
std.debug.warn("Establishment purchasing piles: ");
for (self.establishmentPurchasePiles) |pileHeight, establishmentTypeIndex| {
if (pileHeight == 0) continue;
const est = allEstablishments[establishmentTypeIndex];
std.debug.warn("{}x{}, ", pileHeight, @tagName(est.type));
}
std.debug.warn("\n");
for (self.players) |player, playerIndex| {
std.debug.warn("Player {}: Coins={}, Landmarks=", playerIndex, player.coins);
for (player.landmarks) |landmarkPurchased| {
std.debug.warn("{}/", landmarkPurchased);
}
std.debug.warn("\n");
var playerEstablishmentCounts = [_]u8{0} ** @memberCount(EstablishmentType);
for (player.establishmentsAnyTurn.toSliceConst()) |est| {
playerEstablishmentCounts[@enumToInt(est.type)] += 1;
}
for (player.establishmentsYourTurn.toSliceConst()) |est| {
playerEstablishmentCounts[@enumToInt(est.type)] += 1;
}
for (player.establishmentsOtherTurns.toSliceConst()) |est| {
playerEstablishmentCounts[@enumToInt(est.type)] += 1;
}
for (playerEstablishmentCounts) |estCount, estType| {
if (estCount == 0) continue;
std.debug.warn("{}x {}, ", estCount, @tagName(@intToEnum(EstablishmentType, @intCast(@TagType(EstablishmentType), estType))));
}
std.debug.warn("\n");
}
}
fn rollDie(rng: *std.rand.Random) u32 {
return 1 + rng.uintAtMost(u32, 5);
}
pub fn playTurn(state: *GameState) !bool {
state.currentTurn += 1;
const currentPlayer = &state.players[state.currentPlayerIndex];
var rerolled = false;
var rolledDoubles: bool = undefined;
var rolledValue: u32 = undefined;
while (true) {
rolledDoubles = false;
rolledValue = rollDie(&state.rng.random);
var rolledDice: u32 = 1;
if (currentPlayer.landmarks[@enumToInt(Landmark.TrainStation)] and state.bot.shouldRollTwoDiceFunc(state)) {
const secondRolledValue = rollDie(&state.rng.random);
if (secondRolledValue == rolledValue) {
rolledDoubles = true;
}
rolledValue += secondRolledValue;
rolledDice = 2;
if ((rolledValue >= 10) and (currentPlayer.landmarks[@enumToInt(Landmark.Harbor)]) and state.bot.shouldActivateHarborFunc(state)) {
rolledValue += 2;
}
}
if (verboseMode) {
std.debug.warn("Player {} rolled {} dice and got {}\n", state.currentPlayerIndex, rolledDice, rolledValue);
}
if (rerolled or !currentPlayer.landmarks[@enumToInt(Landmark.RadioTower)] or !state.bot.shouldReroll(state)) {
break;
}
rerolled = true;
}
// Activate red cards
{
var ownerIndex = (state.currentPlayerIndex + 1) % PlayerCount;
while (ownerIndex != state.currentPlayerIndex) {
defer ownerIndex = (ownerIndex + 1) % PlayerCount;
const owner = &state.players[ownerIndex];
for (owner.establishmentsOtherTurns.toSliceConst()) |est| {
if ((rolledValue < est.activationMin) or (rolledValue > est.activationMax)) {
continue;
}
if ((est.type == EstablishmentType.SushiBar) and !owner.landmarks[@enumToInt(Landmark.Harbor)]) {
continue;
}
var coinsRequestedByEstablishment = est.coinsGiven;
// NOTE: Technically we should also check (est.icon == CardIcon.Cup) but that should always be true
if (owner.landmarks[@enumToInt(Landmark.ShoppingMall)]) {
coinsRequestedByEstablishment += 1;
}
const coinsToSteal = std.math.min(coinsRequestedByEstablishment, currentPlayer.coins);
currentPlayer.coins -= coinsToSteal;
owner.coins += coinsToSteal;
owner.totalCoinsEarned[@enumToInt(est.type)] += coinsToSteal;
if (verboseMode) {
std.debug.warn("Activate player {}'s {} to steal {} coins\n", ownerIndex, est.type, coinsToSteal);
}
}
}
}
// Activate green cards
for (currentPlayer.establishmentsYourTurn.toSliceConst()) |est| {
if ((rolledValue < est.activationMin) or (rolledValue > est.activationMax)) {
continue;
}
var coinsToGive = est.coinsGiven;
if (est.multiplier) |multiplier| {
var multiplyFactor: i32 = 0;
switch (multiplier.type) {
MultiplyType.CardIcon => {
const multiplyIcon = @intToEnum(CardIcon, @intCast(@TagType(CardIcon), multiplier.index));
for (currentPlayer.establishmentsAnyTurn.toSliceConst()) |multiplyEst| {
if (multiplyEst.icon == multiplyIcon) multiplyFactor += 1;
}
for (currentPlayer.establishmentsYourTurn.toSliceConst()) |multiplyEst| {
if (multiplyEst.icon == multiplyIcon) multiplyFactor += 1;
}
for (currentPlayer.establishmentsOtherTurns.toSliceConst()) |multiplyEst| {
if (multiplyEst.icon == multiplyIcon) multiplyFactor += 1;
}
},
MultiplyType.EstablishmentType => {
const multiplyType = @intToEnum(EstablishmentType, @intCast(@TagType(EstablishmentType), multiplier.index));
for (currentPlayer.establishmentsAnyTurn.toSliceConst()) |multiplyEst| {
if (multiplyEst.type == multiplyType) multiplyFactor += 1;
}
for (currentPlayer.establishmentsYourTurn.toSliceConst()) |multiplyEst| {
if (multiplyEst.type == multiplyType) multiplyFactor += 1;
}
for (currentPlayer.establishmentsOtherTurns.toSliceConst()) |multiplyEst| {
if (multiplyEst.type == multiplyType) multiplyFactor += 1;
}
},
}
coinsToGive *= multiplyFactor;
}
if ((est.icon == CardIcon.Box) and currentPlayer.landmarks[@enumToInt(Landmark.ShoppingMall)]) {
coinsToGive += 1;
}
if (verboseMode) {
std.debug.warn("Activate player {}'s {} for {} coins\n", state.currentPlayerIndex, est.type, est.coinsGiven);
}
currentPlayer.coins += coinsToGive;
currentPlayer.totalCoinsEarned[@enumToInt(est.type)] += coinsToGive;
}
// Activate blue cards
var tunaBoatCoins = rollDie(&state.rng.random) + rollDie(&state.rng.random);
for (state.players) |player, pid| {
for (player.establishmentsAnyTurn.toSliceConst()) |est| {
if ((rolledValue < est.activationMin) or (rolledValue > est.activationMax)) {
continue;
}
if (((est.type == EstablishmentType.MackerelBoat) or (est.type == EstablishmentType.TunaBoat)) and !currentPlayer.landmarks[@enumToInt(Landmark.Harbor)]) {
continue;
}
if (verboseMode) {
std.debug.warn("Activate player {}'s {} for {} coins\n", pid, est.type, est.coinsGiven);
}
var coinsToGive = est.coinsGiven;
if (est.type == EstablishmentType.TunaBoat) {
coinsToGive += @intCast(i32, tunaBoatCoins);
}
currentPlayer.coins += coinsToGive;
currentPlayer.totalCoinsEarned[@enumToInt(est.type)] += coinsToGive;
}
}
// Activate purple cards
for (currentPlayer.establishmentsYourTurn.toSliceConst()) |est| {
if ((rolledValue < est.activationMin) or (rolledValue > est.activationMax)) {
continue;
}
switch (est.type) {
EstablishmentType.Stadium => {
for (state.players) |*player, pid| {
if (pid == state.currentPlayerIndex) continue;
const coinsToSteal = std.math.min(2, player.coins);
player.coins -= coinsToSteal;
currentPlayer.coins += coinsToSteal;
currentPlayer.totalCoinsEarned[@enumToInt(est.type)] += coinsToSteal;
}
},
EstablishmentType.TVStation => {
const stealPid = state.bot.getPlayerToStealCoinsFrom(state, 5);
const victim = &state.players[stealPid];
var coinsToSteal = std.math.min(victim.coins, 5);
victim.coins -= coinsToSteal;
currentPlayer.coins += coinsToSteal;
currentPlayer.totalCoinsEarned[@enumToInt(est.type)] += coinsToSteal;
},
EstablishmentType.BusinessCentre => {}, // TODO: Trade a non-major establishment with another player
EstablishmentType.Publisher => {
for (state.players) |*player, pid| {
if (pid == state.currentPlayerIndex) continue;
var coinsToSteal: i32 = 0;
for (player.establishmentsOtherTurns.toSliceConst()) |e| {
if (e.icon == CardIcon.Cup) coinsToSteal += 1;
}
for (player.establishmentsYourTurn.toSliceConst()) |e| {
if (e.icon == CardIcon.Box) coinsToSteal += 1;
}
coinsToSteal = std.math.min(coinsToSteal, player.coins);
player.coins -= coinsToSteal;
currentPlayer.coins += coinsToSteal;
currentPlayer.totalCoinsEarned[@enumToInt(est.type)] += coinsToSteal;
}
},
EstablishmentType.TaxOffice => {
for (state.players) |*player, pid| {
if (pid == state.currentPlayerIndex) continue;
if (player.coins < 10) continue;
const halfCoins = @divTrunc(player.coins, 2);
player.coins -= halfCoins;
currentPlayer.coins += halfCoins;
currentPlayer.totalCoinsEarned[@enumToInt(est.type)] += halfCoins;
}
},
else => {},
}
}
if (currentPlayer.coins < 0) {
std.debug.panic("Player has negative coins!");
} else if (currentPlayer.coins == 0) {
currentPlayer.coins = 1; // Town Hall
}
const possibleCardPurchase = state.bot.getCardToPurchaseFunc(state);
if (possibleCardPurchase) |cardToPurchase| {
switch (cardToPurchase.type) {
CardType.Landmark => {
currentPlayer.landmarks[cardToPurchase.index] = true;
const landmarkCost = switch (cardToPurchase.index) {
0 => 2,
1 => 4,
2 => 10,
3 => 16,
4 => 22,
5 => @intCast(i32, 30), // NOTE: Compiler bug. If everything is comptime_int it doesn't resolve to i32 and the compiler complains
else => std.debug.panic("Unexpected landmark {}", cardToPurchase.index),
};
currentPlayer.coins -= landmarkCost;
if (verboseMode) {
std.debug.warn("Player {} buys the {} landmark!\n", state.currentPlayerIndex, @intToEnum(Landmark, @intCast(@TagType(Landmark), cardToPurchase.index)));
}
},
CardType.Establishment => {
const est = &allEstablishments[cardToPurchase.index];
const pileCount = &state.establishmentPurchasePiles[cardToPurchase.index];
pileCount.* -= 1;
if (pileCount.* == 0) {
const deckToRefillFrom = switch (est.deck()) {
EstablishmentDeck.LowCost => &state.loEstablishmentDeck,
EstablishmentDeck.HighCost => &state.hiEstablishmentDeck,
EstablishmentDeck.Major => &state.majorEstablishmentDeck,
};
state.createEstablishmentPile(deckToRefillFrom);
}
try currentPlayer.addEstablishment(est);
if (verboseMode) {
std.debug.warn("Player {} buys a {}\n", state.currentPlayerIndex, @intToEnum(EstablishmentType, @intCast(@TagType(EstablishmentType), cardToPurchase.index)));
}
},
}
} else {
if (currentPlayer.landmarks[@enumToInt(Landmark.Airport)]) {
currentPlayer.coins += 10;
}
}
var currentPlayerHasWon = true;
for (currentPlayer.landmarks) |landmarkBuilt| {
if (!landmarkBuilt) {
currentPlayerHasWon = false;
break;
}
}
if (currentPlayerHasWon) {
if (verboseMode) {
std.debug.warn("Player {} won (on turn {})!\n", state.currentPlayerIndex, state.currentTurn);
}
return true;
}
if (rolledDoubles and currentPlayer.landmarks[@enumToInt(Landmark.AmusementPark)]) {
if (verboseMode) {
std.debug.warn("Player {} rolled doubles and owns the amusement park. Take another turn!\n", state.currentPlayerIndex);
}
} else {
state.currentPlayerIndex = (state.currentPlayerIndex + 1) % PlayerCount;
}
return false;
}
}; | src/game.zig |
// Enums
pub const Factor = enum(c_int) {
zero,
one,
srcColor,
oneMinusSrcColor,
dstColor,
oneMinusDstColor,
srcAlpha,
oneMinusSrcAlpha,
dstAlpha,
oneMinusDstAlpha
};
pub const Equation = enum(c_int) {
add,
subtract,
reverseSubtract
};
const BlendMode = @This();
// Preset blend modes
pub const BlendAlpha = BlendMode{
.color_src_factor = .srcAlpha,
.color_dst_factor = .oneMinusSrcAlpha,
.color_equation = .add,
.alpha_src_factor = .one,
.alpha_dst_factor = .oneMinusSrcAlpha,
.alpha_equation = .add
};
pub const BlendAdd = BlendMode{
.color_src_factor = .srcAlpha,
.color_dst_factor = .one,
.color_equation = .add,
.alpha_src_factor = .one,
.alpha_dst_factor = .one,
.alpha_equation = .add
};
pub const BlendMultiply = BlendMode{
.color_src_factor = .dstColor,
.color_dst_factor = .zero,
.color_equation = .add,
.alpha_src_factor = .dstColor,
.alpha_dst_factor = .zero,
.alpha_equation = .add
};
pub const BlendMin = BlendMode{
.color_src_factor = .one,
.color_dst_factor = .one,
.color_equation = .min,
.alpha_src_factor = .one,
.alpha_dst_factor = .one,
.alpha_equation = .min
};
pub const BlendMax = BlendMode{
.color_src_factor = .one,
.color_dst_factor = .one,
.color_equation = .max,
.alpha_src_factor = .one,
.alpha_dst_factor = .one,
.alpha_equation = .max
};
pub const BlendNone = BlendMode{
.color_src_factor = .one,
.color_dst_factor = .zero,
.color_equation = .add,
.alpha_src_factor = .one,
.alpha_dst_factor = .zero,
.alpha_equation = .add
};
const sfBlendMode = @import("../sfml_import.zig").c.sfBlendMode;
/// Bitcasts this blendmode to the csfml struct
/// For inner workings
pub fn _toCSFML(self: BlendMode) sfBlendMode {
return @bitCast(sfBlendMode, self);
}
color_src_factor: Factor,
color_dst_factor: Factor,
color_equation: Equation,
alpha_src_factor: Factor,
alpha_dst_factor: Factor,
alpha_equation: Equation | src/sfml/graphics/BlendMode.zig |
const std = @import("std");
const assert = std.debug.assert;
/// A variable length collection of characters
pub const String = struct {
/// The internal character buffer
buffer: ?[]u8,
/// The allocator used for managing the buffer
allocator: *std.mem.Allocator,
/// The total size of the String
size: usize,
/// Errors that may occur when using String
pub const Error = error{
OutOfMemory,
InvalidRange,
};
/// Creates a String with an Allocator
/// User is responsible for managing the new String
pub fn init(allocator: *std.mem.Allocator) String {
return .{
.buffer = null,
.allocator = allocator,
.size = 0,
};
}
/// Deallocates the internal buffer
pub fn deinit(self: *String) void {
if (self.buffer) |buffer| self.allocator.free(buffer);
}
/// Returns the size of the internal buffer
pub fn capacity(self: String) usize {
if (self.buffer) |buffer| return buffer.len;
return 0;
}
/// Allocates space for the internal buffer
pub fn allocate(self: *String, bytes: usize) Error!void {
if (self.buffer) |buffer| {
if (bytes < self.size) self.size = bytes; // Clamp size to capacity
self.buffer = self.allocator.realloc(buffer, bytes) catch {
return Error.OutOfMemory;
};
} else {
self.buffer = self.allocator.alloc(u8, bytes) catch {
return Error.OutOfMemory;
};
}
}
/// Reallocates the the internal buffer to size
pub fn truncate(self: *String) Error!void {
try self.allocate(self.size);
}
/// Appends a character onto the end of the String
pub fn concat(self: *String, char: []const u8) Error!void {
try self.insert(char, self.len());
}
/// Inserts a string literal into the String at an index
pub fn insert(self: *String, literal: []const u8, index: usize) Error!void {
// Make sure buffer has enough space
if (self.buffer) |buffer| {
if (self.size + literal.len > buffer.len) {
try self.allocate((self.size + literal.len) * 2);
}
} else {
try self.allocate((literal.len) * 2);
}
const buffer = self.buffer.?;
// If the index is >= len, then simply push to the end.
// If not, then copy contents over and insert literal.
if (index == self.len()) {
var i: usize = 0;
while (i < literal.len) : (i += 1) {
buffer[self.size + i] = literal[i];
}
} else {
if (String.getIndex(buffer, index, true)) |k| {
// Move existing contents over
var i: usize = buffer.len - 1;
while (i >= k) : (i -= 1) {
if (i + literal.len < buffer.len) {
buffer[i + literal.len] = buffer[i];
}
if (i == 0) break;
}
i = 0;
while (i < literal.len) : (i += 1) {
buffer[index + i] = literal[i];
}
}
}
self.size += literal.len;
}
/// Removes the last character from the String
pub fn pop(self: *String) ?[]const u8 {
if (self.size == 0) return null;
if (self.buffer) |buffer| {
var i: usize = 0;
while (i < self.size) {
const size = String.getUTF8Size(buffer[i]);
if (i + size >= self.size) break;
i += size;
}
const ret = buffer[i..self.size];
self.size -= (self.size - i);
return ret;
}
return null;
}
/// Compares this String with a string literal
pub fn cmp(self: String, literal: []const u8) bool {
if (self.buffer) |buffer| {
return std.mem.eql(u8, buffer[0..self.size], literal);
}
return false;
}
/// Returns the String as a string literal
pub fn str(self: String) []const u8 {
if (self.buffer) |buffer| return buffer[0..self.size];
return "";
}
/// Returns an owned slice of this string
pub fn toOwned(self: String) Error!?[]u8 {
if (self.buffer != null) {
const string = self.str();
if (self.allocator.alloc(u8, string.len)) |newStr| {
std.mem.copy(u8, newStr, string);
return newStr;
} else |_| {
return Error.OutOfMemory;
}
}
return null;
}
/// Returns a character at the specified index
pub fn charAt(self: String, index: usize) ?[]const u8 {
if (self.buffer) |buffer| {
if (String.getIndex(buffer, index, true)) |i| {
const size = String.getUTF8Size(buffer[i]);
return buffer[i..(i + size)];
}
}
return null;
}
/// Returns amount of characters in the String
pub fn len(self: String) usize {
if (self.buffer) |buffer| {
var length: usize = 0;
var i: usize = 0;
while (i < self.size) {
i += String.getUTF8Size(buffer[i]);
length += 1;
}
return length;
} else {
return 0;
}
}
/// Finds the first occurrence of the string literal
pub fn find(self: String, literal: []const u8) ?usize {
if (self.buffer) |buffer| {
const index = std.mem.indexOf(u8, buffer[0..self.size], literal);
if (index) |i| {
return String.getIndex(buffer, i, false);
}
}
return null;
}
/// Removes a character at the specified index
pub fn remove(self: *String, index: usize) Error!void {
try self.removeRange(index, index + 1);
}
/// Removes a range of character from the String
/// Start (inclusive) - End (Exclusive)
pub fn removeRange(self: *String, start: usize, end: usize) Error!void {
const length = self.len();
if (end < start or end > length) return Error.InvalidRange;
if (self.buffer) |buffer| {
const rStart = String.getIndex(buffer, start, true).?;
const rEnd = String.getIndex(buffer, end, true).?;
const difference = rEnd - rStart;
var i: usize = rEnd;
while (i < self.size) : (i += 1) {
buffer[i - difference] = buffer[i];
}
self.size -= difference;
}
}
/// Trims all whitelist characters at the start of the String.
pub fn trimStart(self: *String, whitelist: []const u8) void {
if (self.buffer) |buffer| {
var i: usize = 0;
while (i < self.size) : (i += 1) {
const size = String.getUTF8Size(buffer[i]);
if (size > 1 or !inWhitelist(buffer[i], whitelist)) break;
}
if (String.getIndex(buffer, i, false)) |k| {
self.removeRange(0, k) catch {};
}
}
}
/// Trims all whitelist characters at the end of the String.
pub fn trimEnd(self: *String, whitelist: []const u8) void {
self.reverse();
self.trimStart(whitelist);
self.reverse();
}
/// Trims all whitelist characters from both ends of the String
pub fn trim(self: *String, whitelist: []const u8) void {
self.trimStart(whitelist);
self.trimEnd(whitelist);
}
/// Copies this String into a new one
/// User is responsible for managing the new String
pub fn clone(self: String) Error!String {
var newString = String.init(self.allocator);
try newString.concat(self.str());
return newString;
}
/// Reverses the characters in this String
pub fn reverse(self: *String) void {
if (self.buffer) |buffer| {
var i: usize = 0;
while (i < self.size) {
const size = String.getUTF8Size(buffer[i]);
if (size > 1) std.mem.reverse(u8, buffer[i..(i + size)]);
i += size;
}
std.mem.reverse(u8, buffer[0..self.size]);
}
}
/// Repeats this String n times
pub fn repeat(self: *String, n: usize) Error!void {
try self.allocate(self.size * (n + 1));
if (self.buffer) |buffer| {
var i: usize = 1;
while (i <= n) : (i += 1) {
var j: usize = 0;
while (j < self.size) : (j += 1) {
buffer[((i * self.size) + j)] = buffer[j];
}
}
self.size *= (n + 1);
}
}
/// Checks the String is empty
pub inline fn isEmpty(self: String) bool {
return self.size == 0;
}
/// Splits the String into a slice, based on a delimiter and an index
pub fn split(self: *const String, delimiters: []const u8, index: usize) ?[]const u8 {
if (self.buffer) |buffer| {
var i: usize = 0;
var block: usize = 0;
var start: usize = 0;
while (i < self.size) {
const size = String.getUTF8Size(buffer[i]);
if (size == delimiters.len) {
if (std.mem.eql(u8, delimiters, buffer[i..(i + size)])) {
if (block == index) return buffer[start..i];
start = i + size;
block += 1;
}
}
i += size;
}
if (i >= self.size - 1 and block == index) {
return buffer[start..self.size];
}
}
return null;
}
/// Splits the String into a new string, based on delimiters and an index
/// The user of this function is in charge of the memory of the new String.
pub fn splitToString(self: *const String, delimiters: []const u8, index: usize) Error!?String {
if (self.split(delimiters, index)) |block| {
var string = String.init(self.allocator);
try string.concat(block);
return string;
}
return null;
}
/// Clears the contents of the String but leaves the capacity
pub fn clear(self: *String) void {
if (self.buffer) |buffer| {
for (buffer) |*ch| ch.* = 0;
self.size = 0;
}
}
/// Converts all (ASCII) uppercase letters to lowercase
pub fn toLowercase(self: *String) void {
if (self.buffer) |buffer| {
var i: usize = 0;
while (i < self.size) {
const size = String.getUTF8Size(buffer[i]);
if (size == 1) buffer[i] = std.ascii.toLower(buffer[i]);
i += size;
}
}
}
/// Converts all (ASCII) uppercase letters to lowercase
pub fn toUppercase(self: *String) void {
if (self.buffer) |buffer| {
var i: usize = 0;
while (i < self.size) {
const size = String.getUTF8Size(buffer[i]);
if (size == 1) buffer[i] = std.ascii.toUpper(buffer[i]);
i += size;
}
}
}
/// Creates a String from a given range
/// User is responsible for managing the new String
pub fn substr(self: String, start: usize, end: usize) Error!String {
var result = String.init(self.allocator);
if (self.buffer) |buffer| {
if (String.getIndex(buffer, start, true)) |rStart| {
if (String.getIndex(buffer, end, true)) |rEnd| {
if (rEnd < rStart or rEnd > self.size)
return Error.InvalidRange;
try result.concat(buffer[rStart..rEnd]);
}
}
}
return result;
}
// Writer functionality for the String.
pub usingnamespace struct {
pub const Writer = std.io.Writer(*String, Error, appendWrite);
pub fn writer(self: *String) Writer {
return .{ .context = self };
}
fn appendWrite(self: *String, m: []const u8) !usize {
try self.concat(m);
return m.len;
}
};
// Iterator support
pub usingnamespace struct {
pub const StringIterator = struct {
string: *String,
index: usize,
pub fn next(it: *StringIterator) ?[]const u8 {
if (it.string.buffer) |buffer| {
if (it.index == it.string.size) return null;
var i = it.index;
it.index += String.getUTF8Size(buffer[i]);
return buffer[i..it.index];
} else {
return null;
}
}
};
pub fn iterator(self: *String) StringIterator {
return StringIterator{
.string = self,
.index = 0,
};
}
};
/// Returns whether or not a character is whitelisted
fn inWhitelist(char: u8, whitelist: []const u8) bool {
var i: usize = 0;
while (i < whitelist.len) : (i += 1) {
if (whitelist[i] == char) return true;
}
return false;
}
/// Checks if byte is part of UTF-8 character
inline fn isUTF8Byte(byte: u8) bool {
return ((byte & 0x80) > 0) and (((byte << 1) & 0x80) == 0);
}
/// Returns the real index of a unicode string literal
fn getIndex(unicode: []const u8, index: usize, real: bool) ?usize {
var i: usize = 0;
var j: usize = 0;
while (i < unicode.len) {
if (real) {
if (j == index) return i;
} else {
if (i == index) return j;
}
i += String.getUTF8Size(unicode[i]);
j += 1;
}
return null;
}
/// Returns the UTF-8 character's size
inline fn getUTF8Size(char: u8) u3 {
return std.unicode.utf8ByteSequenceLength(char) catch {
return 1;
};
}
}; | zig-string.zig |
const std = @import("std");
const mem = std.mem;
pub const Token = struct {
const Self = @This();
token_type: TokenType,
lexeme: []const u8,
// Literal is either a string or a number
literal_string: ?[]const u8 = null,
literal_number: ?f64 = null,
line: usize,
column: usize,
offset: usize = 0,
pub fn identifier(name: []const u8) Self {
return .{
.token_type = .Identifier,
.lexeme = name,
.line = 0,
.column = 0,
};
}
pub fn clone(self: Self) Self {
return .{
.token_type = self.token_type,
.lexeme = self.lexeme,
.literal_string = self.literal_string,
.literal_number = self.literal_number,
.line = self.line,
.column = self.column,
};
}
};
// WARNING: don't reorder without reordering `rules` in compiler.zig
pub const TokenType = enum {
Pipe, // |
LeftBracket, // [
RightBracket, // ]
LeftParen, // (
RightParen, // )
LeftBrace, // {
RightBrace, // }
Dot, // .
Comma, // ,
Semicolon, // ;
Greater, // >
Less, // <
Plus, // +
Minus, // -
Star, // *
Slash, // /
Percent, // %
Question, // ?
Bang, // !
Colon, // :
Equal, // =
EqualEqual, // ==
BangEqual, // !=
GreaterEqual, // >=
LessEqual, // <=
QuestionQuestion, // ??
PlusEqual, // +=
MinusEqual, // -=
StarEqual, // *=
SlashEqual, // /=
Increment, // ++
Decrement, // --
Arrow, // ->
True, // true
False, // false
Null, // null
Str, // str
Num, // num
Type, // type
Bool, // bool
Function, // Function
ShiftRight, // >>
ShiftLeft, // <<
Xor, // xor
Or, // or
And, // and
Return, // return
If, // if
Else, // else
Do, // do
Until, // until
While, // while
For, // for
ForEach, // foreach
Switch, // switch
Break, // break
Continue, // continue
Default, // default
In, // in
Is, // is
Number, // 123
String, // "hello"
Identifier, // anIdentifier
Fun, // fun
Object, // object
Class, // class
Enum, // enum
Throw, // throw
Catch, // catch
Test, // test
Import, // import
Export, // export
Const, // const
Static, // static
Super, // super
From, // from
As, // as
Extern, // extern
Eof, // EOF
Error, // Error
Void, // void
};
pub const Keywords = [_]TokenType{
.True,
.False,
.Null,
.Or,
.And,
.Return,
.If,
.Else,
.While,
.For,
.ForEach,
.Switch,
.Break,
.Continue,
.Default,
.Fun,
.In,
.Function,
.Print,
.Throw,
.Catch,
.Test,
.Import,
.Export,
.Const,
.Static,
.Super,
.From,
.As,
.Continue,
.Extern,
.Void,
};
// TODO: must be a way to write that more elegantly
pub fn isKeyword(literal: []const u8) ?TokenType {
if (mem.eql(u8, literal, "void")) {
return .Void;
}
if (mem.eql(u8, literal, "true")) {
return .True;
}
if (mem.eql(u8, literal, "false")) {
return .False;
}
if (mem.eql(u8, literal, "null")) {
return .Null;
}
if (mem.eql(u8, literal, "or")) {
return .Or;
}
if (mem.eql(u8, literal, "and")) {
return .And;
}
if (mem.eql(u8, literal, "as")) {
return .As;
}
if (mem.eql(u8, literal, "return")) {
return .Return;
}
if (mem.eql(u8, literal, "if")) {
return .If;
}
if (mem.eql(u8, literal, "else")) {
return .Else;
}
if (mem.eql(u8, literal, "while")) {
return .While;
}
if (mem.eql(u8, literal, "for")) {
return .For;
}
if (mem.eql(u8, literal, "foreach")) {
return .ForEach;
}
if (mem.eql(u8, literal, "switch")) {
return .Switch;
}
if (mem.eql(u8, literal, "break")) {
return .Break;
}
if (mem.eql(u8, literal, "continue")) {
return .Continue;
}
if (mem.eql(u8, literal, "default")) {
return .Default;
}
if (mem.eql(u8, literal, "const")) {
return .Const;
}
if (mem.eql(u8, literal, "super")) {
return .Super;
}
if (mem.eql(u8, literal, "fun")) {
return .Fun;
}
if (mem.eql(u8, literal, "in")) {
return .In;
}
if (mem.eql(u8, literal, "str")) {
return .Str;
}
if (mem.eql(u8, literal, "num")) {
return .Num;
}
if (mem.eql(u8, literal, "type")) {
return .Type;
}
if (mem.eql(u8, literal, "bool")) {
return .Bool;
}
if (mem.eql(u8, literal, "xor")) {
return .Xor;
}
if (mem.eql(u8, literal, "do")) {
return .Do;
}
if (mem.eql(u8, literal, "until")) {
return .Until;
}
if (mem.eql(u8, literal, "is")) {
return .Is;
}
if (mem.eql(u8, literal, "object")) {
return .Object;
}
if (mem.eql(u8, literal, "static")) {
return .Static;
}
if (mem.eql(u8, literal, "class")) {
return .Class;
}
if (mem.eql(u8, literal, "enum")) {
return .Enum;
}
if (mem.eql(u8, literal, "throw")) {
return .Throw;
}
if (mem.eql(u8, literal, "catch")) {
return .Catch;
}
if (mem.eql(u8, literal, "test")) {
return .Test;
}
if (mem.eql(u8, literal, "Function")) {
return .Function;
}
if (mem.eql(u8, literal, "import")) {
return .Import;
}
if (mem.eql(u8, literal, "export")) {
return .Export;
}
if (mem.eql(u8, literal, "extern")) {
return .Extern;
}
if (mem.eql(u8, literal, "from")) {
return .From;
}
return null;
} | src/token.zig |
const net = std.net;
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const Connect = @import("./packet/connect.zig").Connect;
const Packet = @import("./packet.zig").Packet;
const Publish = @import("./packet/publish.zig").Publish;
const QoS = @import("../qos.zig").QoS;
const Subscribe = @import("./packet/subscribe.zig").Subscribe;
const Topic = @import("./packet/subscribe.zig").Topic;
pub const Will = @import("./packet/connect.zig").Will;
pub const ConnectOptions = struct {
clean_session: bool = false,
client_id: []const u8 = "zanzara", // TODO: this should be randomly generated if it's not passed by the user
keepalive: u16 = 30,
will: ?Will = null,
username: ?[]const u8 = null,
password: ?[]const u8 = null,
};
pub const PublishOptions = struct {
duplicate: bool = false,
qos: QoS = .qos0,
retain: bool = false,
};
pub const Error = error{
InvalidClientId,
MalformedCredentials,
NotImplemented,
ServerUnavailable,
Unauthorized,
UnexpectedResponse,
};
pub const Client = struct {
conn: net.Stream,
reader: net.Stream.Reader,
writer: net.Stream.Writer,
allocator: *Allocator,
packet_id: u16 = 0,
const Self = @This();
pub fn init(self: *Self, host: []const u8, port: u16, allocator: *Allocator) !void {
// Connect
const conn = try net.tcpConnectToHost(allocator, host, port);
self.conn = conn;
self.reader = conn.reader();
self.writer = conn.writer();
self.allocator = allocator;
}
pub fn connect(self: *Self, opts: ConnectOptions) !void {
const conn = Connect{
.clean_session = opts.clean_session,
.client_id = opts.client_id,
.keepalive = opts.keepalive,
.will = opts.will,
.username = opts.username,
.password = opts.password,
};
const pkt = Packet{ .connect = conn };
try pkt.serialize(self.writer);
var response = try Packet.parse(self.allocator, self.reader);
defer response.deinit(self.allocator);
if (response == .connack) {
const connack = response.connack;
switch (connack.return_code) {
.ok => return,
.invalid_client_id => return error.InvalidClientId,
.server_unavailable => return error.ServerUnavailable,
.malformed_credentials => return error.MalformedCredentials,
.unauthorized => return error.Unauthorized,
.unacceptable_protocol_version => unreachable, // This is an implementation error
}
} else {
return error.UnexpectedResponse;
}
}
pub fn publish(self: *Self, topic: []const u8, payload: []const u8, opts: PublishOptions) !void {
const packet_id =
switch (opts.qos) {
// TODO: add support for QoS1 and QoS2 and return nextPacketId()
.qos1, .qos2 => return error.NotImplemented,
else => null,
};
const publ = Publish{
.duplicate = opts.duplicate,
.qos = opts.qos,
.retain = opts.retain,
.packet_id = packet_id,
.topic = topic,
.payload = payload,
};
const pkt = Packet{ .publish = publ };
try pkt.serialize(self.writer);
}
pub fn subscribe(self: *Self, topic_filter: []const u8, qos: QoS) !void {
var topics = [_]Topic{.{
.topic_filter = topic_filter,
.qos = qos,
}};
const sub = Subscribe{
.packet_id = self.nextPacketId(),
.topics = &topics,
};
const pkt = Packet{ .subscribe = sub };
try pkt.serialize(self.writer);
}
fn nextPacketId(self: *Self) u16 {
self.packet_id = self.packet_id +% 1;
// TODO: mark this as unlikely when language support is there
if (self.packet_id == 0) {
self.packet_id = 1;
}
return self.packet_id;
}
}; | src/mqtt4/client.zig |
const std = @import("std");
const debug = std.debug;
const mem = std.mem;
const testing = std.testing;
const unicode = std.unicode;
const GBP = @import("../components.zig").GraphemeBreakProperty;
const CodePoint = @import("CodePoint.zig");
const CodePointIterator = CodePoint.CodePointIterator;
const Emoji = @import("../components.zig").EmojiData;
pub const Grapheme = @This();
bytes: []const u8,
offset: usize,
pub fn eql(self: Grapheme, str: []const u8) bool {
return mem.eql(u8, self.bytes, str);
}
const Type = enum {
control,
cr,
extend,
han_l,
han_lv,
han_lvt,
han_t,
han_v,
lf,
prepend,
regional,
spacing,
xpic,
zwj,
any,
fn get(cp: CodePoint) Type {
var ty: Type = .any;
if (0x000D == cp.scalar) ty = .cr;
if (0x000A == cp.scalar) ty = .lf;
if (0x200D == cp.scalar) ty = .zwj;
if (GBP.isControl(cp.scalar)) ty = .control;
if (GBP.isExtend(cp.scalar)) ty = .extend;
if (GBP.isL(cp.scalar)) ty = .han_l;
if (GBP.isLV(cp.scalar)) ty = .han_lv;
if (GBP.isLVT(cp.scalar)) ty = .han_lvt;
if (GBP.isT(cp.scalar)) ty = .han_t;
if (GBP.isV(cp.scalar)) ty = .han_v;
if (GBP.isPrepend(cp.scalar)) ty = .prepend;
if (GBP.isRegionalIndicator(cp.scalar)) ty = .regional;
if (GBP.isSpacingMark(cp.scalar)) ty = .spacing;
if (Emoji.isExtendedPictographic(cp.scalar)) ty = .xpic;
return ty;
}
};
const Token = struct {
ty: Type,
code_point: CodePoint,
offset: usize = 0,
fn is(self: Token, ty: Type) bool {
return self.ty == ty;
}
};
const TokenList = std.ArrayList(Token);
pub const GraphemeIterator = struct {
bytes: []const u8,
i: ?usize = null,
start: ?Token = null,
tokens: TokenList,
const Self = @This();
pub fn init(allocator: *mem.Allocator, str: []const u8) !Self {
if (!unicode.utf8ValidateSlice(str)) return error.InvalidUtf8;
var self = Self{
.bytes = str,
.tokens = TokenList.init(allocator),
};
try self.lex();
if (self.tokens.items.len == 0) return error.NoTokens;
self.start = self.tokens.items[0];
// Set token offsets.
for (self.tokens.items) |*token, i| {
token.offset = i;
}
return self;
}
pub fn deinit(self: *Self) void {
self.tokens.deinit();
}
fn lex(self: *Self) !void {
var iter = CodePointIterator{
.bytes = self.bytes,
.i = 0,
};
while (iter.next()) |cp| {
try self.tokens.append(.{
.ty = Type.get(cp),
.code_point = cp,
});
}
}
// Main API.
pub fn next(self: *Self) ?Grapheme {
if (self.advance()) |current_token| {
var end = self.current();
if (isBreaker(current_token)) {
if (current_token.is(.cr)) {
if (self.peek()) |p| {
// GB3
if (p.is(.lf)) {
_ = self.advance();
end = self.current();
}
}
}
}
if (current_token.is(.regional)) {
if (self.peek()) |p| {
// GB12
if (p.is(.regional) and !isIgnorable(end)) {
_ = self.advance();
end = self.current();
}
}
}
if (current_token.is(.han_l)) {
if (self.peek()) |p| {
// GB6
if ((p.is(.han_l) or p.is(.han_v) or p.is(.han_lv) or p.is(.han_lvt)) and
!isIgnorable(end))
{
_ = self.advance();
end = self.current();
}
}
}
if (current_token.is(.han_lv) or current_token.is(.han_v)) {
if (self.peek()) |p| {
// GBy
if ((p.is(.han_v) or p.is(.han_t)) and !isIgnorable(end)) {
_ = self.advance();
end = self.current();
}
}
}
if (current_token.is(.han_lvt) or current_token.is(.han_t)) {
if (self.peek()) |p| {
// GB8
if (p.is(.han_t) and !isIgnorable(end)) {
_ = self.advance();
end = self.current();
}
}
}
if (current_token.is(.xpic)) {
if (self.peek()) |p| {
// GB11
if (p.is(.xpic) and end.is(.zwj)) {
_ = self.advance();
end = self.current();
}
}
}
const start = self.start.?;
self.start = self.peek();
// GB999
return self.emit(start, end);
}
return null;
}
// Token array movement.
fn forward(self: *Self) bool {
if (self.i) |*index| {
index.* += 1;
if (index.* >= self.tokens.items.len) return false;
} else {
self.i = 0;
}
return true;
}
// Token array movement.
fn getRelative(self: Self, n: isize) ?Token {
var index: usize = self.i orelse 0;
if (n < 0) {
if (index == 0 or -%n > index) return null;
index -= @intCast(usize, -%n);
} else {
const un = @intCast(usize, n);
if (index + un >= self.tokens.items.len) return null;
index += un;
}
return self.tokens.items[index];
}
fn prevAfterSkip(self: *Self, predicate: TokenPredicate) ?Token {
if (self.i == null or self.i.? == 0) return null;
var i: isize = 1;
while (self.getRelative(-i)) |token| : (i += 1) {
if (!predicate(token)) return token;
}
return null;
}
fn current(self: Self) Token {
// Assumes self.i is not null.
return self.tokens.items[self.i.?];
}
fn last(self: Self) Token {
return self.tokens.items[self.tokens.items.len - 1];
}
fn peek(self: Self) ?Token {
return self.getRelative(1);
}
fn peekAfterSkip(self: *Self, predicate: TokenPredicate) ?Token {
var i: isize = 1;
while (self.getRelative(i)) |token| : (i += 1) {
if (!predicate(token)) return token;
}
return null;
}
fn advance(self: *Self) ?Token {
const token = if (self.forward()) self.current() else return null;
// GB9b
if (token.is(.prepend)) {
if (self.peek()) |p| {
if (!isBreaker(p)) return self.advance();
}
}
// GB9, GBia
if (!isBreaker(token)) _ = self.skipIgnorables(token);
return token;
}
fn run(self: *Self, predicate: TokenPredicate) void {
while (self.peek()) |token| {
if (!predicate(token)) break;
_ = self.advance();
}
}
fn skipIgnorables(self: *Self, end: Token) Token {
if (self.peek()) |p| {
if (isIgnorable(p)) {
self.run(isIgnorable);
return self.current();
}
}
return end;
}
// Production.
fn emit(self: Self, start_token: Token, end_token: Token) Grapheme {
const start = start_token.code_point.offset;
const end = end_token.code_point.end();
return .{
.bytes = self.bytes[start..end],
.offset = start,
};
}
};
// Predicates
const TokenPredicate = fn (Token) bool;
fn isBreaker(token: Token) bool {
return token.ty == .control or token.ty == .cr or token.ty == .lf;
}
fn isControl(token: Token) bool {
return token.ty == .control;
}
fn isIgnorable(token: Token) bool {
return token.ty == .extend or token.ty == .spacing or token.ty == .zwj;
}
test "Segmentation GraphemeIterator" {
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;
var allocator = std.testing.allocator;
var file = try std.fs.cwd().openFile("src/data/ucd/GraphemeBreakTest.txt", .{});
defer file.close();
var buf_reader = std.io.bufferedReader(file.reader());
var input_stream = buf_reader.reader();
var buf: [4096]u8 = undefined;
var line_no: usize = 1;
while (try input_stream.readUntilDelimiterOrEof(&buf, '\n')) |raw| : (line_no += 1) {
// Skip comments or empty lines.
if (raw.len == 0 or raw[0] == '#' or raw[0] == '@') continue;
// Clean up.
var line = mem.trimLeft(u8, raw, "÷ ");
if (mem.indexOf(u8, line, " ÷\t#")) |octo| {
line = line[0..octo];
}
//debug.print("\nline {}: {s}\n", .{ line_no, line });
// Iterate over fields.
var want = std.ArrayList(Grapheme).init(allocator);
defer {
for (want.items) |snt| {
allocator.free(snt.bytes);
}
want.deinit();
}
var all_bytes = std.ArrayList(u8).init(allocator);
defer all_bytes.deinit();
var sentences = mem.split(u8, line, " ÷ ");
var bytes_index: usize = 0;
while (sentences.next()) |field| {
var code_points = mem.split(u8, field, " ");
var cp_buf: [4]u8 = undefined;
var cp_index: usize = 0;
var first: u21 = undefined;
var cp_bytes = std.ArrayList(u8).init(allocator);
defer cp_bytes.deinit();
while (code_points.next()) |code_point| {
if (mem.eql(u8, code_point, "×")) continue;
const cp: u21 = try std.fmt.parseInt(u21, code_point, 16);
if (cp_index == 0) first = cp;
const len = try unicode.utf8Encode(cp, &cp_buf);
try all_bytes.appendSlice(cp_buf[0..len]);
try cp_bytes.appendSlice(cp_buf[0..len]);
cp_index += len;
}
try want.append(Grapheme{
.bytes = cp_bytes.toOwnedSlice(),
.offset = bytes_index,
});
bytes_index += cp_index;
}
//debug.print("\nline {}: {s}\n", .{ line_no, all_bytes.items });
var iter = try GraphemeIterator.init(allocator, all_bytes.items);
defer iter.deinit();
// Chaeck.
for (want.items) |w| {
const g = (iter.next()).?;
//debug.print("\n", .{});
//for (w.bytes) |b| {
// debug.print("line {}: w:({x})\n", .{ line_no, b });
//}
//for (g.bytes) |b| {
// debug.print("line {}: g:({x})\n", .{ line_no, b });
//}
//debug.print("line {}: w:({s}), g:({s})\n", .{ line_no, w.bytes, g.bytes });
try testing.expectEqualStrings(w.bytes, g.bytes);
try testing.expectEqual(w.offset, g.offset);
}
}
}
// Comptime
fn getTokens(comptime str: []const u8, comptime n: usize) [n]Token {
var i: usize = 0;
var cp_iter = CodePointIterator{ .bytes = str };
var tokens: [n]Token = undefined;
while (cp_iter.next()) |cp| : (i += 1) {
tokens[i] = .{
.ty = Type.get(cp),
.code_point = cp,
.offset = i,
};
}
return tokens;
}
pub fn ComptimeGraphemeIterator(comptime str: []const u8) type {
const cp_count: usize = unicode.utf8CountCodepoints(str) catch @compileError("Invalid UTF-8.");
if (cp_count == 0) @compileError("No code points?");
const tokens = getTokens(str, cp_count);
return struct {
bytes: []const u8 = str,
i: ?usize = null,
start: ?Token = tokens[0],
tokens: [cp_count]Token = tokens,
const Self = @This();
// Main API.
pub fn next(self: *Self) ?Grapheme {
if (self.advance()) |current_token| {
var end = self.current();
if (isBreaker(current_token)) {
if (current_token.is(.cr)) {
if (self.peek()) |p| {
// GB3
if (p.is(.lf)) {
_ = self.advance();
end = self.current();
}
}
}
}
if (current_token.is(.regional)) {
if (self.peek()) |p| {
// GB12
if (p.is(.regional) and !isIgnorable(end)) {
_ = self.advance();
end = self.current();
}
}
}
if (current_token.is(.han_l)) {
if (self.peek()) |p| {
// GB6
if ((p.is(.han_l) or p.is(.han_v) or p.is(.han_lv) or p.is(.han_lvt)) and
!isIgnorable(end))
{
_ = self.advance();
end = self.current();
}
}
}
if (current_token.is(.han_lv) or current_token.is(.han_v)) {
if (self.peek()) |p| {
// GBy
if ((p.is(.han_v) or p.is(.han_t)) and !isIgnorable(end)) {
_ = self.advance();
end = self.current();
}
}
}
if (current_token.is(.han_lvt) or current_token.is(.han_t)) {
if (self.peek()) |p| {
// GB8
if (p.is(.han_t) and !isIgnorable(end)) {
_ = self.advance();
end = self.current();
}
}
}
if (current_token.is(.xpic)) {
if (self.peek()) |p| {
// GB11
if (p.is(.xpic) and end.is(.zwj)) {
_ = self.advance();
end = self.current();
}
}
}
const start = self.start.?;
self.start = self.peek();
// GB999
return self.emit(start, end);
}
return null;
}
// Token array movement.
fn forward(self: *Self) bool {
if (self.i) |*index| {
index.* += 1;
if (index.* >= self.tokens.len) return false;
} else {
self.i = 0;
}
return true;
}
pub fn count(self: *Self) usize {
const original_i = self.i;
const original_start = self.start;
defer {
self.i = original_i;
self.start = original_start;
}
self.rewind();
var i: usize = 0;
while (self.next()) |_| : (i += 1) {}
return i;
}
// Token array movement.
pub fn rewind(self: *Self) void {
self.i = null;
self.start = self.tokens[0];
}
fn getRelative(self: Self, n: isize) ?Token {
var index: usize = self.i orelse 0;
if (n < 0) {
if (index == 0 or -%n > index) return null;
index -= @intCast(usize, -%n);
} else {
const un = @intCast(usize, n);
if (index + un >= self.tokens.len) return null;
index += un;
}
return self.tokens[index];
}
fn prevAfterSkip(self: *Self, predicate: TokenPredicate) ?Token {
if (self.i == null or self.i.? == 0) return null;
var i: isize = 1;
while (self.getRelative(-i)) |token| : (i += 1) {
if (!predicate(token)) return token;
}
return null;
}
fn current(self: Self) Token {
// Assumes self.i is not null.
return self.tokens[self.i.?];
}
fn last(self: Self) Token {
return self.tokens[self.tokens.len - 1];
}
fn peek(self: Self) ?Token {
return self.getRelative(1);
}
fn peekAfterSkip(self: *Self, predicate: TokenPredicate) ?Token {
var i: isize = 1;
while (self.getRelative(i)) |token| : (i += 1) {
if (!predicate(token)) return token;
}
return null;
}
fn advance(self: *Self) ?Token {
const token = if (self.forward()) self.current() else return null;
// GB9b
if (token.is(.prepend)) {
if (self.peek()) |p| {
if (!isBreaker(p)) return self.advance();
}
}
// GB9, GBia
if (!isBreaker(token)) _ = self.skipIgnorables(token);
return token;
}
fn run(self: *Self, predicate: TokenPredicate) void {
while (self.peek()) |token| {
if (!predicate(token)) break;
_ = self.advance();
}
}
fn skipIgnorables(self: *Self, end: Token) Token {
if (self.peek()) |p| {
if (isIgnorable(p)) {
self.run(isIgnorable);
return self.current();
}
}
return end;
}
// Production.
fn emit(self: Self, start_token: Token, end_token: Token) Grapheme {
const start = start_token.code_point.offset;
const end = end_token.code_point.end();
return .{
.bytes = self.bytes[start..end],
.offset = start,
};
}
};
}
test "Segmentation ComptimeGraphemeIterator" {
comptime var ct_iter = ComptimeGraphemeIterator("Héllo"){};
const n = comptime ct_iter.count();
var graphemes: [n]Grapheme = undefined;
comptime {
var i: usize = 0;
while (ct_iter.next()) |grapheme| : (i += 1) {
graphemes[i] = grapheme;
}
}
const want = [_][]const u8{ "H", "é", "l", "l", "o" };
for (graphemes) |grapheme, i| {
try testing.expect(grapheme.eql(want[i]));
}
} | src/segmenter/Grapheme.zig |
const std = @import("std");
const helper = @import("helper.zig");
const Allocator = std.mem.Allocator;
const Grid = helper.Grid;
const BinaryHeap = helper.BinaryHeap;
const input = @embedFile("../inputs/day15.txt");
pub fn run(alloc: Allocator, stdout_: anytype) !void {
const grid = try parseInput(alloc, input);
defer grid.deinit();
var dijkstra = try DijkstraGrid.init(alloc, grid);
defer dijkstra.deinit();
dijkstra.calculate();
const res1 = dijkstra.nodes[0].priority - grid.data[0];
const grid5 = try genGrid5(alloc, grid);
defer grid5.deinit();
var dijkstra5 = try DijkstraGrid.init(alloc, grid5);
defer dijkstra5.deinit();
dijkstra5.calculate();
const res2 = dijkstra5.nodes[0].priority - grid5.data[0];
if (stdout_) |stdout| {
try stdout.print("Part 1: {}\n", .{res1});
try stdout.print("Part 2: {}\n", .{res2});
}
}
fn genGrid5(alloc: Allocator, grid: Grid(u8)) !Grid(u8) {
var grid5 = try Grid(u8).init(alloc, grid.m * 5, grid.n * 5);
var i: usize = 0;
while (i < grid5.m) : (i += 1) {
var j: usize = 0;
while (j < grid5.n) : (j += 1) {
const increases = @intCast(u8, (i / grid.m) + (j / grid.n));
const ii = i % grid.m;
const jj = j % grid.n;
const val = (grid.get(ii, jj) + increases - 1) % 9 + 1;
grid5.set(i, j, val);
}
}
return grid5;
}
const DijkstraGrid = struct {
grid: Grid(u8),
nodes: []Node,
heap: BinaryHeap(Point),
allocator: Allocator,
const Self = @This();
pub fn init(alloc: Allocator, grid: Grid(u8)) !Self {
var nodes = try alloc.alloc(Node, grid.data.len);
var i: usize = 0;
while (i < grid.m) : (i += 1) {
var j: usize = 0;
while (j < grid.n) : (j += 1) {
const node = &nodes[grid.getIdx(i, j)];
node.priority = std.math.maxInt(i32);
node.data = Point{ .x = i, .y = j };
}
}
nodes[nodes.len - 1].priority = grid.data[grid.data.len - 1];
var heap = try BinaryHeap(Point).init(alloc, nodes);
return Self{ .grid = grid, .nodes = nodes, .heap = heap, .allocator = alloc };
}
pub fn calculate(self: *Self) void {
while (self.heap.len > 0) {
const min = self.heap.pop();
var neighbors = self.neighbors_iter(min.data);
while (neighbors.next()) |neighbor| {
const node = &self.nodes[self.grid.getIdx(neighbor.x, neighbor.y)];
if (node.idx == null) continue;
const alt: i32 = min.priority + self.grid.get(neighbor.x, neighbor.y);
if (alt < node.priority) {
self.heap.changePriority(node.idx.?, alt);
}
}
}
}
pub fn deinit(self: Self) void {
self.allocator.free(self.nodes);
self.heap.deinit();
}
fn neighbors_iter(self: *const Self, pt: Point) NeighborIterator {
return NeighborIterator{
.dg = self,
.point = NeighborIterator.SignedPoint{
.x = @intCast(isize, pt.x),
.y = @intCast(isize, pt.y),
},
};
}
const NeighborIterator = struct {
dg: *const DijkstraGrid,
point: SignedPoint,
index: usize = 0,
const offsets: [4]SignedPoint = .{
.{ .x = -1, .y = 0 },
.{ .x = 0, .y = -1 },
.{ .x = 1, .y = 0 },
.{ .x = 0, .y = 1 },
};
pub fn next(self: *@This()) ?Point {
const pt = self.point;
const grid = self.dg.grid;
while (self.index < 4) {
const of = offsets[self.index];
self.index += 1;
const newpoint = SignedPoint{ .x = of.x + pt.x, .y = of.y + pt.y };
if (newpoint.x < 0 or newpoint.x >= grid.m) continue;
if (newpoint.y < 0 or newpoint.y >= grid.n) continue;
return Point{
.x = @intCast(usize, newpoint.x),
.y = @intCast(usize, newpoint.y),
};
}
return null;
}
const SignedPoint = struct { x: isize, y: isize };
};
const Point = struct { x: usize, y: usize };
const Node = BinaryHeap(Point).Node;
};
fn parseInput(alloc: Allocator, inp: []const u8) !Grid(u8) {
var lines = getlines(inp);
const m = count(u8, inp, "\n");
const n = lines.next().?.len;
if (m != n) unreachable; // the input should be a square
var grid = try Grid(u8).init(alloc, m, n);
const items = grid.data;
var i: usize = 0;
for (inp) |ch| {
if (!std.ascii.isDigit(ch)) continue;
items[i] = ch - '0';
i += 1;
}
if (i != items.len) unreachable;
return grid;
}
const eql = std.mem.eql;
const tokenize = std.mem.tokenize;
const split = std.mem.split;
const count = std.mem.count;
const parseUnsigned = std.fmt.parseUnsigned;
const parseInt = std.fmt.parseInt;
const sort = std.sort.sort;
const getlines = helper.getlines; | src/day15.zig |
const std = @import("std");
const Answer = struct { @"0": u32, @"1": u64 };
fn charCorruptionScore(c: u8) ?u32 {
return switch (c) {
')' => 3,
']' => 57,
'}' => 1197,
'>' => 25137,
else => null,
};
}
fn charCompletionScore(c: u8) ?u32 {
return switch (c) {
')' => 1,
']' => 2,
'}' => 3,
'>' => 4,
else => null,
};
}
fn isClosing(c: u8) bool {
return switch (c) {
')', ']', '}', '>' => true,
else => false,
};
}
fn matchBracket(c: u8) ?u8 {
return switch (c) {
')' => '(',
']' => '[',
'}' => '{',
'>' => '<',
'(' => ')',
'[' => ']',
'{' => '}',
'<' => '>',
else => null,
};
}
fn run(filename: []const u8) !Answer {
const file = try std.fs.cwd().openFile(filename, .{ .read = true });
defer file.close();
var reader = std.io.bufferedReader(file.reader()).reader();
var buffer: [4096]u8 = undefined;
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
var arena = std.heap.ArenaAllocator.init(&gpa.allocator);
defer arena.deinit();
var stack = std.ArrayList(u8).init(&gpa.allocator);
defer stack.deinit();
var total: u32 = 0;
var scores = std.ArrayList(u64).init(&gpa.allocator);
defer scores.deinit();
while (try reader.readUntilDelimiterOrEof(&buffer, '\n')) |line| {
try stack.resize(line.len);
var i: usize = 0;
for (line) |c| {
if (isClosing(c)) {
if (stack.items[i - 1] == matchBracket(c).?) {
i -= 1;
} else {
total += charCorruptionScore(c).?;
break;
}
} else {
stack.items[i] = c;
i += 1;
}
} else {
var score: u64 = 0;
while (i > 0) : (i -= 1) {
score = 5 * score + charCompletionScore(matchBracket(stack.items[i - 1]).?).?;
}
try scores.append(score);
}
}
std.sort.sort(u64, scores.items, {}, comptime std.sort.asc(u64));
const middle_score = scores.items[scores.items.len / 2];
return Answer{ .@"0" = total, .@"1" = middle_score };
}
pub fn main() !void {
const answer = try run("inputs/" ++ @typeName(@This()) ++ ".txt");
std.debug.print("{d}\n", .{answer.@"0"});
std.debug.print("{d}\n", .{answer.@"1"});
}
test {
const answer = try run("test-inputs/" ++ @typeName(@This()) ++ ".txt");
try std.testing.expectEqual(@as(u32, 26397), answer.@"0");
try std.testing.expectEqual(@as(u64, 288957), answer.@"1");
} | src/day10.zig |
const std = @import("std");
const assert = std.debug.assert;
const window = @import("Window.zig");
const c = @import("c.zig").c;
const expect = std.testing.expect;
const ReferenceCounter = @import("../RefCount.zig").ReferenceCounter;
pub const Buffer = struct {
ref_count: ReferenceCounter = ReferenceCounter{},
const buffer_type_gl = [_]c_uint{
c.GL_ARRAY_BUFFER,
c.GL_ELEMENT_ARRAY_BUFFER,
c.GL_UNIFORM_BUFFER,
};
pub const BufferType = enum(u32) {
VertexData = 0,
IndexData = 1,
Uniform = 2,
};
id: u32,
data_size: u32,
pub fn init() !Buffer {
var id: u32 = 0;
c.glGenBuffers(1, @ptrCast([*c]c_uint, &id));
if (id == 0) {
return error.OpenGLError;
}
return Buffer{
.id = id,
.data_size = 0,
};
}
// Buffer will be bound to target buffer_type
pub fn upload(self: *Buffer, buffer_type: BufferType, data: []const u8, dynamic: bool) !void {
if (data.len > 0xffffffff) {
return error.ArrayTooLarge;
}
try self.bind(buffer_type);
var usage: u32 = c.GL_STATIC_DRAW;
if (dynamic) {
usage = c.GL_DYNAMIC_DRAW;
}
c.glBufferData(buffer_type_gl[@enumToInt(buffer_type)], @intCast(u32, data.len), data.ptr, usage);
self.data_size = @intCast(u32, data.len);
}
// Wipes the buffer contents and allocates data-size bytes of vram
pub fn reserveMemory(self: *Buffer, buffer_type: BufferType, data_size: u32, dynamic: bool) !void {
if (data_size == 0) {
return error.InvalidParameter;
}
try self.bind(buffer_type);
var usage: u32 = c.GL_STATIC_DRAW;
if (dynamic) {
usage = c.GL_DYNAMIC_DRAW;
}
c.glBufferData(buffer_type_gl[@enumToInt(buffer_type)], data_size, null, usage);
self.data_size = data_size;
}
pub fn uploadRegion(self: *Buffer, buffer_type: BufferType, data: []const u8, offset: u32, dynamic: bool) !void {
if (offset + data.len > self.data_size) {
return error.ArrayTooLarge;
}
if (data.len == 0) {
return error.InvalidParameter;
}
try self.bind(buffer_type);
var usage: u32 = c.GL_STATIC_DRAW;
if (dynamic) {
usage = c.GL_DYNAMIC_DRAW;
}
c.glBufferSubData(buffer_type_gl[@enumToInt(buffer_type)], offset, @intCast(u32, data.len), data.ptr);
}
pub fn bind(self: Buffer, bindAs: BufferType) !void {
if (self.id == 0) {
assert(false);
return error.InvalidState;
}
c.glBindBuffer(buffer_type_gl[@enumToInt(bindAs)], self.id);
}
pub fn unbind(target: BufferType) void {
c.glBindBuffer(buffer_type_gl[@enumToInt(bindAs)], 0);
}
pub fn bindUniform(self: *Buffer, bindingPoint: u32, offset: u32, length: u32) !void {
if (self.id == 0) {
assert(false);
return error.InvalidState;
}
c.glBindBufferRange(c.GL_UNIFORM_BUFFER, bindingPoint, self.id, offset, length);
}
pub fn free(self: *Buffer) void {
if (self.id == 0) {
assert(false);
return;
}
self.ref_count.deinit();
c.glDeleteBuffers(1, @ptrCast([*c]const c_uint, &self.id));
self.id = 0;
}
// For uniform buffers
pub fn bindBufferBase(self: *Buffer, index: u32) !void {
if (self.id == 0) {
assert(false);
return error.InvalidState;
}
c.glBindBufferBase(c.GL_UNIFORM_BUFFER, index, self.id);
}
};
test "Buffer" {
try window.createWindow(false, 200, 200, "test", true, 0);
defer window.closeWindow();
const inData = [4]u8{ 1, 2, 3, 4 };
var buf: Buffer = try Buffer.init();
try buf.upload(Buffer.BufferType.VertexData, inData[0..], false);
// GL_ARRAY_BUFFER, GL_READ_ONLY
var ptr: [*]const u8 = @ptrCast([*]const u8, c.glMapBuffer(0x8892, 0x88B8).?);
expect(ptr[0] == 1 and ptr[1] == 2 and ptr[2] == 3 and ptr[3] == 4);
buf.free();
} | src/WindowGraphicsInput/Buffer.zig |
const std = @import("std");
const audiometa = @import("audiometa");
const Allocator = std.mem.Allocator;
pub const log_level: std.log.Level = .warn;
pub export fn main() void {
zigMain() catch unreachable;
}
pub fn zigMain() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer std.debug.assert(gpa.deinit() == false);
const allocator = gpa.allocator();
const stdin = std.io.getStdIn();
const data = try stdin.readToEndAlloc(allocator, std.math.maxInt(usize));
defer allocator.free(data);
var stream_source = std.io.StreamSource{ .buffer = std.io.fixedBufferStream(data) };
// default to 50kb minimum just in case we get very small files that need to allocate
// fairly large sizes for things like ArrayList(ID3v2Metadata)
const max_allocation_size = std.math.max(50 * 1024, data.len * 10);
var max_size_allocator = MaxSizeAllocator.init(allocator, max_allocation_size).allocator();
var metadata = try audiometa.metadata.readAll(max_size_allocator, &stream_source);
defer metadata.deinit();
}
/// Allocator that checks that individual allocations never go over
/// a certain size, and panics if they do
const MaxSizeAllocator = struct {
parent_allocator: Allocator,
max_alloc_size: usize,
const Self = @This();
pub fn init(parent_allocator: Allocator, max_alloc_size: usize) Self {
return .{
.parent_allocator = parent_allocator,
.max_alloc_size = max_alloc_size,
};
}
pub fn allocator(self: *Self) Allocator {
return Allocator.init(self, alloc, resize, free);
}
fn alloc(self: *Self, len: usize, ptr_align: u29, len_align: u29, ra: usize) error{OutOfMemory}![]u8 {
if (len > self.max_alloc_size) {
std.debug.print("trying to allocate size: {}\n", .{len});
@panic("allocation exceeds max alloc size");
}
return self.parent_allocator.rawAlloc(len, ptr_align, len_align, ra);
}
fn resize(self: *Self, buf: []u8, buf_align: u29, new_len: usize, len_align: u29, ra: usize) ?usize {
if (new_len > self.max_alloc_size) {
std.debug.print("trying to resize to size: {}\n", .{new_len});
@panic("allocation exceeds max alloc size");
}
return self.parent_allocator.rawResize(buf, buf_align, new_len, len_align, ra);
}
fn free(self: *Self, buf: []u8, buf_align: u29, ret_addr: usize) void {
return self.parent_allocator.rawFree(buf, buf_align, ret_addr);
}
}; | test/fuzz.zig |
const std = @import("std");
const builtin = @import("builtin");
pub const pkg = std.build.Pkg{
.name = "openssl",
.source = .{ .path = srcPath() ++ "/openssl.zig" },
};
pub fn addPackage(step: *std.build.LibExeObjStep) void {
step.addPackage(pkg);
step.addIncludeDir(srcPath() ++ "/vendor/include");
}
/// The crypto package has optional assembly files. They are generated by perl scripts during make
/// and the output depends on the target platform. For now, just don't opt in.
/// If we do opt in, we'd need to save the assembly for each target platform. It would have to live
/// in a new folder tree separated by target. The vendor directory should be simple and be one to one with the openssl repo.
pub fn createCrypto(
b: *std.build.Builder,
target: std.zig.CrossTarget,
mode: std.builtin.Mode,
) !*std.build.LibExeObjStep {
const lib = b.addStaticLibrary("crypto", null);
lib.setTarget(target);
lib.setBuildMode(mode);
var c_flags = std.ArrayList([]const u8).init(b.allocator);
if (target.getOsTag() == .macos) {
try c_flags.append("-DOPENSSL_SYS_MACOSX=1");
}
// Don't include wincrypt.h from window.h which has conflicting declarations with crypto X509_EXTENSIONS.
// Only when compiling to windows-gnu.
if (target.getOsTag() == .windows and target.getAbi() == .gnu) {
try c_flags.append("-DNOCRYPT=1");
}
const c_files = &[_][]const u8{
// openssl/crypto/bio/build.info
// base
"bio/bio_lib.c",
"bio/bio_cb.c",
"bio/bio_err.c",
"bio/bio_print.c",
"bio/bio_dump.c",
"bio/bio_addr.c",
"bio/bio_sock.c",
"bio/bio_sock2.c",
"bio/bio_meth.c",
"bio/ossl_core_bio.c",
// source/sink
"bio/bss_null.c",
"bio/bss_mem.c",
"bio/bss_bio.c",
"bio/bss_fd.c",
"bio/bss_file.c",
"bio/bss_sock.c",
"bio/bss_conn.c",
"bio/bss_acpt.c",
"bio/bss_dgram.c",
"bio/bss_log.c",
"bio/bss_core.c",
// filters
"bio/bf_null.c",
"bio/bf_buff.c",
"bio/bf_lbuf.c",
"bio/bf_nbio.c",
"bio/bf_prefix.c",
"bio/bf_readbuff.c",
// openssl/crypto/buffer/build.info
"buffer/buffer.c",
"buffer/buf_err.c",
// openssl/crypto/err/build.info
"err/err_blocks.c",
"err/err.c",
"err/err_all.c",
"err/err_all_legacy.c",
"err/err_prn.c",
// openssl/crypto/encode_decode/build.info
"encode_decode/encoder_meth.c",
"encode_decode/encoder_lib.c",
"encode_decode/encoder_pkey.c",
"encode_decode/decoder_meth.c",
"encode_decode/decoder_lib.c",
"encode_decode/decoder_pkey.c",
"encode_decode/encoder_err.c",
"encode_decode/decoder_err.c",
// openssl/crypto/property/build.info
"property/property_string.c",
"property/property_parse.c",
"property/property_query.c",
"property/property.c",
"property/defn_cache.c",
"property/property_err.c",
// openssl/crypto/build.info
// util common
"cryptlib.c",
"params.c",
"params_from_text.c",
"bsearch.c",
"ex_data.c",
"o_str.c",
"threads_pthread.c",
"threads_win.c",
"threads_none.c",
"initthread.c",
"context.c",
"sparse_array.c",
"asn1_dsa.c",
"packet.c",
"param_build.c",
"param_build_set.c",
"der_writer.c",
"threads_lib.c",
"params_dup.c",
// source
"mem.c",
"mem_sec.c",
"cversion.c",
"info.c",
"cpt_err.c",
"ebcdic.c",
"uid.c",
"o_time.c",
"o_dir.c",
"o_fopen.c",
"getenv.c",
"o_init.c",
"init.c",
"trace.c",
"provider.c",
"provider_child.c",
"punycode.c",
"passphrase.c",
// core
"provider_core.c",
"provider_predefined.c",
"core_fetch.c",
"core_algorithm.c",
"core_namemap.c",
"self_test_core.c",
"provider_conf.c",
// cpuid
"mem_clr.c",
"cpuid.c",
"ctype.c",
// openssl/crypto/lhash/build.info
"lhash/lhash.c",
"lhash/lh_stats.c",
// openssl/crypto/objects/build.info
"objects/o_names.c",
"objects/obj_dat.c",
"objects/obj_lib.c",
"objects/obj_err.c",
"objects/obj_xref.c",
// openssl/crypto/evp/build.info
// common
"evp/digest.c",
"evp/evp_enc.c",
"evp/evp_lib.c",
"evp/evp_fetch.c",
"evp/evp_utils.c",
"evp/mac_lib.c",
"evp/mac_meth.c",
"evp/keymgmt_meth.c",
"evp/keymgmt_lib.c",
"evp/kdf_lib.c",
"evp/kdf_meth.c",
"evp/m_sigver.c",
"evp/pmeth_lib.c",
"evp/signature.c",
"evp/p_lib.c",
"evp/pmeth_gn.c",
"evp/exchange.c",
"evp/evp_rand.c",
"evp/asymcipher.c",
"evp/kem.c",
"evp/dh_support.c",
"evp/ec_support.c",
"evp/pmeth_check.c",
// source
"evp/encode.c",
"evp/evp_key.c",
"evp/evp_cnf.c",
"evp/e_des.c",
"evp/e_bf.c",
"evp/e_idea.c",
"evp/e_des3.c",
"evp/e_rc4.c",
"evp/e_aes.c",
"evp/names.c",
"evp/e_aria.c",
"evp/e_sm4.c",
"evp/e_xcbc_d.c",
"evp/e_rc2.c",
"evp/e_cast.c",
"evp/e_rc5.c",
"evp/m_null.c",
"evp/p_seal.c",
"evp/p_sign.c",
"evp/p_verify.c",
"evp/p_legacy.c",
"evp/bio_md.c",
"evp/bio_b64.c",
"evp/bio_enc.c",
"evp/evp_err.c",
"evp/e_null.c",
"evp/c_allc.c",
"evp/c_alld.c",
"evp/bio_ok.c",
"evp/evp_pkey.c",
"evp/evp_pbe.c",
"evp/p5_crpt.c",
"evp/p5_crpt2.c",
"evp/pbe_scrypt.c",
"evp/e_aes_cbc_hmac_sha1.c",
"evp/e_aes_cbc_hmac_sha256.c",
"evp/e_rc4_hmac_md5.c",
"evp/e_chacha20_poly1305.c",
"evp/legacy_sha.c",
"evp/ctrl_params_translate.c",
"evp/cmeth_lib.c",
"evp/dh_ctrl.c",
"evp/dsa_ctrl.c",
"evp/ec_ctrl.c",
"evp/legacy_md5.c",
"evp/legacy_md5_sha1.c",
"evp/e_camellia.c",
// openssl/crypto/conf/build.info
"conf/conf_err.c",
"conf/conf_lib.c",
"conf/conf_api.c",
"conf/conf_def.c",
"conf/conf_mod.c",
"conf/conf_mall.c",
"conf/conf_sap.c",
"conf/conf_ssl.c",
// openssl/crypto/x509/build.info
"x509/x509_def.c",
"x509/x509_d2.c",
"x509/x509_r2x.c",
"x509/x509_cmp.c",
"x509/x509_obj.c",
"x509/x509_req.c",
"x509/x509spki.c",
"x509/x509_vfy.c",
"x509/x509_set.c",
"x509/x509cset.c",
"x509/x509rset.c",
"x509/x509_err.c",
"x509/x509name.c",
"x509/x509_v3.c",
"x509/x509_ext.c",
"x509/x509_att.c",
"x509/x509_meth.c",
"x509/x509_lu.c",
"x509/x_all.c",
"x509/x509_txt.c",
"x509/x509_trust.c",
"x509/by_file.c",
"x509/by_dir.c",
"x509/by_store.c",
"x509/x509_vpm.c",
"x509/x_crl.c",
"x509/t_crl.c",
"x509/x_req.c",
"x509/t_req.c",
"x509/x_x509.c",
"x509/t_x509.c",
"x509/x_pubkey.c",
"x509/x_x509a.c",
"x509/x_attrib.c",
"x509/x_exten.c",
"x509/x_name.c",
"x509/v3_bcons.c",
"x509/v3_bitst.c",
"x509/v3_conf.c",
"x509/v3_extku.c",
"x509/v3_ia5.c",
"x509/v3_utf8.c",
"x509/v3_lib.c",
"x509/v3_prn.c",
"x509/v3_utl.c",
"x509/v3err.c",
"x509/v3_genn.c",
"x509/v3_san.c",
"x509/v3_skid.c",
"x509/v3_akid.c",
"x509/v3_pku.c",
"x509/v3_int.c",
"x509/v3_enum.c",
"x509/v3_sxnet.c",
"x509/v3_cpols.c",
"x509/v3_crld.c",
"x509/v3_purp.c",
"x509/v3_info.c",
"x509/v3_akeya.c",
"x509/v3_pmaps.c",
"x509/v3_pcons.c",
"x509/v3_ncons.c",
"x509/v3_pcia.c",
"x509/v3_pci.c",
"x509/v3_ist.c",
"x509/pcy_cache.c",
"x509/pcy_node.c",
"x509/pcy_data.c",
"x509/pcy_map.c",
"x509/pcy_tree.c",
"x509/pcy_lib.c",
"x509/v3_asid.c",
"x509/v3_addr.c",
"x509/v3_tlsf.c",
"x509/v3_admis.c",
// openssl/crypto/store/build.info
"store/store_err.c",
"store/store_lib.c",
"store/store_result.c",
"store/store_strings.c",
"store/store_meth.c",
// openssl/crypto/pem/build.info
"pem/pem_sign.c",
"pem/pem_info.c",
"pem/pem_lib.c",
"pem/pem_all.c",
"pem/pem_err.c",
"pem/pem_x509.c",
"pem/pem_xaux.c",
"pem/pem_oth.c",
"pem/pem_pk8.c",
"pem/pem_pkey.c",
"pem/pvkfmt.c",
// openssl/crypto/asn1/build.info
"asn1/a_object.c",
"asn1/a_bitstr.c",
"asn1/a_utctm.c",
"asn1/a_gentm.c",
"asn1/a_time.c",
"asn1/a_int.c",
"asn1/a_octet.c",
"asn1/a_print.c",
"asn1/a_type.c",
"asn1/a_dup.c",
"asn1/a_d2i_fp.c",
"asn1/a_i2d_fp.c",
"asn1/a_utf8.c",
"asn1/a_sign.c",
"asn1/a_digest.c",
"asn1/a_verify.c",
"asn1/a_mbstr.c",
"asn1/a_strex.c",
"asn1/x_algor.c",
"asn1/x_val.c",
"asn1/x_sig.c",
"asn1/x_bignum.c",
"asn1/x_int64.c",
"asn1/x_info.c",
"asn1/x_spki.c",
"asn1/nsseq.c",
"asn1/d2i_pu.c",
"asn1/d2i_pr.c",
"asn1/i2d_evp.c",
"asn1/t_pkey.c",
"asn1/t_spki.c",
"asn1/t_bitst.c",
"asn1/tasn_new.c",
"asn1/tasn_fre.c",
"asn1/tasn_enc.c",
"asn1/tasn_dec.c",
"asn1/tasn_utl.c",
"asn1/tasn_typ.c",
"asn1/tasn_prn.c",
"asn1/tasn_scn.c",
"asn1/ameth_lib.c",
"asn1/f_int.c",
"asn1/f_string.c",
"asn1/x_pkey.c",
"asn1/bio_asn1.c",
"asn1/bio_ndef.c",
"asn1/asn_mime.c",
"asn1/asn1_gen.c",
"asn1/asn1_parse.c",
"asn1/asn1_lib.c",
"asn1/asn1_err.c",
"asn1/a_strnid.c",
"asn1/evp_asn1.c",
"asn1/asn_pack.c",
"asn1/p5_pbe.c",
"asn1/p5_pbev2.c",
"asn1/p5_scrypt.c",
"asn1/p8_pkey.c",
"asn1/asn_moid.c",
"asn1/asn_mstbl.c",
"asn1/asn1_item_list.c",
"asn1/d2i_param.c",
// openssl/crypto/hmac/build.info
"hmac/hmac.c",
// openssl/crypto/dh/build.info
// common
"dh/dh_lib.c",
"dh/dh_key.c",
"dh/dh_group_params.c",
"dh/dh_check.c",
"dh/dh_backend.c",
"dh/dh_gen.c",
"dh/dh_kdf.c",
// source
"dh/dh_asn1.c",
"dh/dh_err.c",
"dh/dh_ameth.c",
"dh/dh_pmeth.c",
"dh/dh_prn.c",
"dh/dh_rfc5114.c",
"dh/dh_meth.c",
// openssl/crypto/ec/build.info
// common
"ec/ec_lib.c",
"ec/ecp_smpl.c",
"ec/ecp_mont.c",
"ec/ecp_nist.c",
"ec/ec_cvt.c",
"ec/ec_mult.c",
"ec/ec_curve.c",
"ec/ec_check.c",
"ec/ec_key.c",
"ec/ec_kmeth.c",
"ec/ecx_key.c",
"ec/ec_asn1.c",
"ec/ec2_smpl.c",
"ec/ecp_oct.c",
"ec/ec2_oct.c",
"ec/ec_oct.c",
"ec/ecdh_ossl.c",
"ec/ecdsa_ossl.c",
"ec/ecdsa_sign.c",
"ec/ecdsa_vrf.c",
"ec/curve25519.c",
"ec/curve448/f_generic.c",
"ec/curve448/scalar.c",
"ec/curve448/curve448_tables.c",
"ec/curve448/eddsa.c",
"ec/curve448/curve448.c",
// $ECASM
"ec/ec_backend.c",
"ec/ecx_backend.c",
"ec/ecdh_kdf.c",
"ec/curve448/arch_64/f_impl64.c",
"ec/curve448/arch_32/f_impl32.c",
// source
"ec/ec_ameth.c",
"ec/ec_pmeth.c",
"ec/ecx_meth.c",
"ec/ec_err.c",
"ec/eck_prn.c",
"ec/ec_deprecated.c",
"ec/ec_print.c",
// openssl/crypto/dsa/build.info
// common
"dsa/dsa_sign.c",
"dsa/dsa_vrf.c",
"dsa/dsa_lib.c",
"dsa/dsa_ossl.c",
"dsa/dsa_check.c",
"dsa/dsa_key.c",
"dsa/dsa_backend.c",
"dsa/dsa_gen.c",
// source
"dsa/dsa_asn1.c",
"dsa/dsa_err.c",
"dsa/dsa_ameth.c",
"dsa/dsa_pmeth.c",
"dsa/dsa_prn.c",
"dsa/dsa_meth.c",
// openssl/crypto/rsa/build.info
// common
"rsa/rsa_ossl.c",
"rsa/rsa_gen.c",
"rsa/rsa_lib.c",
"rsa/rsa_sign.c",
"rsa/rsa_pk1.c",
"rsa/rsa_none.c",
"rsa/rsa_oaep.c",
"rsa/rsa_chk.c",
"rsa/rsa_pss.c",
"rsa/rsa_x931.c",
"rsa/rsa_crpt.c",
"rsa/rsa_sp800_56b_gen.c",
"rsa/rsa_sp800_56b_check.c",
"rsa/rsa_backend.c",
"rsa/rsa_mp_names.c",
"rsa/rsa_schemes.c",
// source
"rsa/rsa_saos.c",
"rsa/rsa_err.c",
"rsa/rsa_asn1.c",
"rsa/rsa_ameth.c",
"rsa/rsa_prn.c",
"rsa/rsa_pmeth.c",
"rsa/rsa_meth.c",
"rsa/rsa_mp.c",
// openssl/crypto/pkcs7/build.info
"pkcs7/pk7_asn1.c",
"pkcs7/pk7_lib.c",
"pkcs7/pkcs7err.c",
"pkcs7/pk7_doit.c",
"pkcs7/pk7_smime.c",
"pkcs7/pk7_attr.c",
"pkcs7/pk7_mime.c",
"pkcs7/bio_pk7.c",
// openssl/crypto/pkcs12/build.info
"pkcs12/p12_add.c",
"pkcs12/p12_asn.c",
"pkcs12/p12_attr.c",
"pkcs12/p12_crpt.c",
"pkcs12/p12_crt.c",
"pkcs12/p12_decr.c",
"pkcs12/p12_init.c",
"pkcs12/p12_key.c",
"pkcs12/p12_kiss.c",
"pkcs12/p12_mutl.c",
"pkcs12/p12_sbag.c",
"pkcs12/p12_utl.c",
"pkcs12/p12_npas.c",
"pkcs12/pk12err.c",
"pkcs12/p12_p8d.c",
"pkcs12/p12_p8e.c",
// openssl/crypto/ocsp/build.info
"ocsp/ocsp_asn.c",
"ocsp/ocsp_ext.c",
"ocsp/ocsp_http.c",
"ocsp/ocsp_lib.c",
"ocsp/ocsp_cl.c",
"ocsp/ocsp_srv.c",
"ocsp/ocsp_prn.c",
"ocsp/ocsp_vfy.c",
"ocsp/ocsp_err.c",
"ocsp/v3_ocsp.c",
// openssl/crypto/stack/build.info
"stack/stack.c",
// openssl/crypto/bn/build.info
// common
"bn/bn_add.c",
"bn/bn_div.c",
"bn/bn_exp.c",
"bn/bn_lib.c",
"bn/bn_ctx.c",
"bn/bn_mul.c",
"bn/bn_mod.c",
"bn/bn_conv.c",
"bn/bn_rand.c",
"bn/bn_shift.c",
"bn/bn_word.c",
"bn/bn_blind.c",
"bn/bn_kron.c",
"bn/bn_sqrt.c",
"bn/bn_gcd.c",
"bn/bn_prime.c",
"bn/bn_sqr.c",
"bn/bn_recp.c",
"bn/bn_mont.c",
"bn/bn_mpi.c",
"bn/bn_exp2.c",
"bn/bn_gf2m.c",
"bn/bn_nist.c",
"bn/bn_intern.c",
"bn/bn_dh.c",
"bn/bn_rsa_fips186_4.c",
"bn/bn_const.c",
// $BNASM
"bn/bn_asm.c",
// source
"bn/bn_print.c",
"bn/bn_err.c",
"bn/bn_srp.c", // SRP is deprecated in openssl v3.0
// openssl/crypto/comp/build.info
"comp/comp_lib.c",
"comp/comp_err.c",
"comp/c_zlib.c",
// openssl/crypto/ct/build.info
"ct/ct_b64.c",
"ct/ct_err.c",
"ct/ct_log.c",
"ct/ct_oct.c",
"ct/ct_policy.c",
"ct/ct_prn.c",
"ct/ct_sct.c",
"ct/ct_sct_ctx.c",
"ct/ct_vfy.c",
"ct/ct_x509v3.c",
// openssl/crypto/async/build.info
"async/async.c",
"async/async_wait.c",
"async/async_err.c",
"async/arch/async_posix.c",
"async/arch/async_win.c",
"async/arch/async_null.c",
// openssl/crypto/rand/build.info
// common
"rand/rand_lib.c",
// crypto
"rand/randfile.c",
"rand/rand_err.c",
"rand/rand_deprecated.c",
"rand/prov_seed.c",
"rand/rand_pool.c",
// openssl/crypto/md5/build.info
// common
"md5/md5_dgst.c",
"md5/md5_one.c",
"md5/md5_sha1.c",
//$MD5ASM
// openssl/crypto/poly1305/build.info
"poly1305/poly1305.c",
//$POLY1305ASM
// openssl/crypto/chacha/build.info
"chacha/chacha_enc.c",
//$CHACHAASM
// openssl/crypto/aria/build.info
"aria/aria.c",
// openssl/crypto/modes/build.info
// common
"modes/cbc128.c",
"modes/ctr128.c",
"modes/cfb128.c",
"modes/ofb128.c",
"modes/gcm128.c",
"modes/ccm128.c",
"modes/xts128.c",
"modes/wrap128.c",
// $MODESASM
// source
"modes/cts128.c",
"modes/ocb128.c",
"modes/siv128.c",
// openssl/crypto/aes/build.info
// AESASM
"aes/aes_core.c",
"aes/aes_cbc.c",
// common
"aes/aes_misc.c",
"aes/aes_ecb.c",
// source
"aes/aes_cfb.c",
"aes/aes_ofb.c",
"aes/aes_wrap.c",
// openssl/crypto/cast/build.info
// CASTASM
"cast/c_enc.c",
// source
"cast/c_skey.c",
"cast/c_ecb.c",
"cast/c_cfb64.c",
"cast/c_ofb64.c",
// openssl/crypto/bf/build.info
// BFASM
"bf/bf_enc.c",
// source
"bf/bf_skey.c",
"bf/bf_ecb.c",
"bf/bf_cfb64.c",
"bf/bf_ofb64.c",
// openssl/crypto/rc2/build.info
// "rc2/rc2_ecb.c",
// "rc2/rc2_skey.c",
// "rc2/rc2_cbc.c",
// "rc2/rc2cfb64.c",
// "rc2/rc2ofb64.c",
// openssl/crypto/sm4/build.info
"sm4/sm4.c",
// openssl/crypto/camellia/build.info
// CMLLASM
"camellia/camellia.c",
"camellia/cmll_misc.c",
"camellia/cmll_cbc.c",
// source
"camellia/cmll_ecb.c",
"camellia/cmll_ofb.c",
"camellia/cmll_cfb.c",
"camellia/cmll_ctr.c",
// openssl/crypto/ess/build.info
"ess/ess_asn1.c",
"ess/ess_err.c",
"ess/ess_lib.c",
// openssl/crypto/cmp/build.info
"cmp/cmp_asn.c",
"cmp/cmp_ctx.c",
"cmp/cmp_err.c",
"cmp/cmp_util.c",
"cmp/cmp_status.c",
"cmp/cmp_hdr.c",
"cmp/cmp_protect.c",
"cmp/cmp_msg.c",
"cmp/cmp_vfy.c",
"cmp/cmp_server.c",
"cmp/cmp_client.c",
"cmp/cmp_http.c",
// openssl/crypto/crmf/build.info
"crmf/crmf_asn.c",
"crmf/crmf_err.c",
"crmf/crmf_lib.c",
"crmf/crmf_pbm.c",
// openssl/crypto/cms/build.info
"cms/cms_lib.c",
"cms/cms_asn1.c",
"cms/cms_att.c",
"cms/cms_io.c",
"cms/cms_smime.c",
"cms/cms_err.c",
"cms/cms_sd.c",
"cms/cms_dd.c",
"cms/cms_cd.c",
"cms/cms_env.c",
"cms/cms_enc.c",
"cms/cms_ess.c",
"cms/cms_pwri.c",
"cms/cms_kari.c",
"cms/cms_rsa.c",
"cms/cms_dh.c",
"cms/cms_ec.c",
// openssl/crypto/ui/build.info
"ui/ui_err.c",
"ui/ui_lib.c",
"ui/ui_openssl.c",
"ui/ui_null.c",
"ui/ui_util.c",
// openssl/crypto/http/build.info
"http/http_client.c",
"http/http_err.c",
"http/http_lib.c",
// openssl/crypto/ts/build.info
"ts/ts_err.c",
"ts/ts_req_utils.c",
"ts/ts_req_print.c",
"ts/ts_rsp_utils.c",
"ts/ts_rsp_print.c",
"ts/ts_rsp_sign.c",
"ts/ts_rsp_verify.c",
"ts/ts_verify_ctx.c",
"ts/ts_lib.c",
"ts/ts_conf.c",
"ts/ts_asn1.c",
// openssl/crypto/dso/build.info
"dso/dso_dl.c",
"dso/dso_dlfcn.c",
"dso/dso_err.c",
"dso/dso_lib.c",
"dso/dso_openssl.c",
"dso/dso_win32.c",
"dso/dso_vms.c",
// openssl/crypto/ffc/build.info
"ffc/ffc_params.c",
"ffc/ffc_params_generate.c",
"ffc/ffc_key_generate.c",
"ffc/ffc_params_validate.c",
"ffc/ffc_key_validate.c",
"ffc/ffc_backend.c",
"ffc/ffc_dh.c",
// openssl/crypto/sha/build.info
// KECCAK1600ASM
"sha/keccak1600.c",
// SHA1ASM
// source
"sha/sha1dgst.c",
"sha/sha256.c",
"sha/sha512.c",
"sha/sha3.c",
"sha/sha1_one.c",
// openssl/crypto/siphash/build.info
"siphash/siphash.c",
};
for (c_files) |file| {
const path = b.fmt("{s}/vendor/crypto/{s}", .{ srcPath(), file });
lib.addCSourceFile(path, c_flags.items);
}
const digest_cfiles = &[_][]const u8{
// openssl/providers/implementations/digests/build.info
// common
"implementations/digests/digestcommon.c",
"implementations/digests/null_prov.c",
"implementations/digests/sha2_prov.c",
"implementations/digests/sha3_prov.c",
"implementations/digests/md5_prov.c",
"implementations/digests/md5_sha1_prov.c",
// openssl/providers/implementations/kdfs/build.info
"implementations/kdfs/tls1_prf.c",
"implementations/kdfs/hkdf.c",
"implementations/kdfs/kbkdf.c",
"implementations/kdfs/krb5kdf.c",
"implementations/kdfs/pbkdf1.c",
"implementations/kdfs/pbkdf2.c",
"implementations/kdfs/pbkdf2_fips.c",
"implementations/kdfs/pkcs12kdf.c",
"implementations/kdfs/sskdf.c",
"implementations/kdfs/sshkdf.c",
"implementations/kdfs/x942kdf.c",
"implementations/kdfs/scrypt.c",
// openssl/providers/implementations/macs/build.info
"implementations/macs/gmac_prov.c",
"implementations/macs/hmac_prov.c",
"implementations/macs/kmac_prov.c",
"implementations/macs/siphash_prov.c",
"implementations/macs/poly1305_prov.c",
// openssl/providers/implementations/rands/build.info
"implementations/rands/drbg.c",
"implementations/rands/test_rng.c",
"implementations/rands/drbg_ctr.c",
"implementations/rands/drbg_hash.c",
"implementations/rands/drbg_hmac.c",
"implementations/rands/crngt.c",
"implementations/rands/seed_src.c",
// openssl/providers/implementations/rands/seedings/build.info
"implementations/rands/seeding/rand_unix.c",
"implementations/rands/seeding/rand_win.c",
"implementations/rands/seeding/rand_tsc.c",
// openssl/providers/common/build.info
"common/provider_util.c",
"common/capabilities.c",
"common/bio_prov.c",
"common/digest_to_nid.c",
"common/securitycheck.c",
"common/provider_seeding.c",
"common/provider_err.c",
"common/provider_ctx.c",
"common/securitycheck_fips.c",
// openssl/providers/common/der/build.info
// DER_RSA_COMMON
"common/der/der_rsa_gen.c",
"common/der/der_rsa_key.c",
"common/der/der_rsa_sig.c",
"common/der/der_ecx_gen.c",
"common/der/der_ecx_key.c",
"common/der/der_dsa_gen.c",
"common/der/der_dsa_sig.c",
"common/der/der_ec_gen.c",
"common/der/der_ec_sig.c",
"common/der/der_wrap_gen.c",
// openssl/providers/implementations/exchange/build.info
"implementations/exchange/dh_exch.c",
"implementations/exchange/ecdh_exch.c",
"implementations/exchange/ecx_exch.c",
"implementations/exchange/kdf_exch.c",
// openssl/providers/implementations/keymgmt/build.info
"implementations/keymgmt/dh_kmgmt.c",
"implementations/keymgmt/dsa_kmgmt.c",
"implementations/keymgmt/ec_kmgmt.c",
"implementations/keymgmt/ecx_kmgmt.c",
"implementations/keymgmt/rsa_kmgmt.c",
"implementations/keymgmt/kdf_legacy_kmgmt.c",
"implementations/keymgmt/mac_legacy_kmgmt.c",
// openssl/providers/implementations/encode_decode/build.info
// encoder
"implementations/encode_decode/endecoder_common.c",
"implementations/encode_decode/encode_key2any.c",
"implementations/encode_decode/encode_key2text.c",
"implementations/encode_decode/encode_key2ms.c",
"implementations/encode_decode/encode_key2blob.c",
// decoder
"implementations/encode_decode/decode_der2key.c",
"implementations/encode_decode/decode_epki2pki.c",
"implementations/encode_decode/decode_pem2der.c",
"implementations/encode_decode/decode_msblob2key.c",
"implementations/encode_decode/decode_pvk2key.c",
"implementations/encode_decode/decode_spki2typespki.c",
// openssl/providers/build.info
"nullprov.c",
"prov_running.c",
"baseprov.c",
"defltprov.c",
// openssl/providers/implementations/ciphers/build.info
// common
"implementations/ciphers/ciphercommon.c",
"implementations/ciphers/ciphercommon_hw.c",
"implementations/ciphers/ciphercommon_block.c",
"implementations/ciphers/ciphercommon_gcm.c",
"implementations/ciphers/ciphercommon_gcm_hw.c",
"implementations/ciphers/ciphercommon_ccm.c",
"implementations/ciphers/ciphercommon_ccm_hw.c",
"implementations/ciphers/cipher_null.c",
// camellia
"implementations/ciphers/cipher_camellia.c",
"implementations/ciphers/cipher_camellia_hw.c",
// aria
"implementations/ciphers/cipher_aria.c",
"implementations/ciphers/cipher_aria_hw.c",
"implementations/ciphers/cipher_aria_gcm.c",
"implementations/ciphers/cipher_aria_gcm_hw.c",
"implementations/ciphers/cipher_aria_ccm.c",
"implementations/ciphers/cipher_aria_ccm_hw.c",
// chacha
"implementations/ciphers/cipher_chacha20.c",
"implementations/ciphers/cipher_chacha20_hw.c",
"implementations/ciphers/cipher_chacha20_poly1305.c",
"implementations/ciphers/cipher_chacha20_poly1305_hw.c",
// sm4
"implementations/ciphers/cipher_sm4.c",
"implementations/ciphers/cipher_sm4_hw.c",
"implementations/ciphers/cipher_sm4_gcm.c",
"implementations/ciphers/cipher_sm4_gcm_hw.c",
"implementations/ciphers/cipher_sm4_ccm.c",
"implementations/ciphers/cipher_sm4_ccm_hw.c",
// aes
"implementations/ciphers/cipher_aes.c",
"implementations/ciphers/cipher_aes_hw.c",
"implementations/ciphers/cipher_aes_xts.c",
"implementations/ciphers/cipher_aes_xts_hw.c",
"implementations/ciphers/cipher_aes_gcm.c",
"implementations/ciphers/cipher_aes_gcm_hw.c",
"implementations/ciphers/cipher_aes_ccm.c",
"implementations/ciphers/cipher_aes_ccm_hw.c",
"implementations/ciphers/cipher_aes_wrp.c",
"implementations/ciphers/cipher_aes_cbc_hmac_sha.c",
"implementations/ciphers/cipher_aes_cbc_hmac_sha256_hw.c",
"implementations/ciphers/cipher_aes_cbc_hmac_sha1_hw.c",
"implementations/ciphers/cipher_cts.c",
"implementations/ciphers/cipher_aes_xts_fips.c",
"implementations/ciphers/cipher_aes_ocb.c",
"implementations/ciphers/cipher_aes_ocb_hw.c",
// siv
"implementations/ciphers/cipher_aes_siv.c",
"implementations/ciphers/cipher_aes_siv_hw.c",
// openssl/providers/implementations/asymciphers/build.info
"implementations/asymciphers/rsa_enc.c",
// openssl/providers/implementations/kem/build.info
"implementations/kem/rsa_kem.c",
// openssl/providers/implementations/storemgmt/build.info
"implementations/storemgmt/file_store.c",
"implementations/storemgmt/file_store_any2obj.c",
// openssl/providers/implementations/signature/build.info
"implementations/signature/ecdsa_sig.c",
"implementations/signature/dsa_sig.c",
"implementations/signature/eddsa_sig.c",
"implementations/signature/rsa_sig.c",
"implementations/signature/mac_legacy_sig.c",
};
for (digest_cfiles) |file| {
const path = b.fmt("{s}/vendor/providers/{s}", .{ srcPath(), file });
lib.addCSourceFile(path, c_flags.items);
}
lib.disable_sanitize_c = true;
lib.linkLibC();
// Point to either unix or windows config.
// It's better to keep cflags small: https://github.com/ziglang/zig/issues/10693
if (target.getOsTag() == .windows) {
lib.addIncludeDir(fromRoot(b, "windows/include"));
} else {
lib.addIncludeDir(fromRoot(b, "unix/include"));
}
lib.addIncludeDir(fromRoot(b, "vendor/providers/implementations/include"));
lib.addIncludeDir(fromRoot(b, "vendor/providers/common/include"));
lib.addIncludeDir(fromRoot(b, "vendor/include"));
lib.addIncludeDir(fromRoot(b, "vendor"));
if (builtin.os.tag == .macos and target.getOsTag() == .macos) {
if (target.isNativeOs()) {
// Force use native headers since it wants to find CommonCrypto headers.
lib.linkFramework("CoreServices");
} else {
lib.setLibCFile(std.build.FileSource.relative("./lib/macos.libc"));
lib.addSystemIncludeDir("/usr/include");
}
}
return lib;
}
pub const CryptoOptions = struct {
lib_path: ?[]const u8 = null,
};
pub fn buildAndLinkCrypto(step: *std.build.LibExeObjStep, opts: CryptoOptions) void {
if (opts.lib_path) |path| {
linkLibCryptoPath(step, path);
} else {
if (builtin.os.tag == .windows) {
// Can't build, too many args in build-lib will break zig :)
step.addAssemblyFile(srcPath() ++ "/../extras/prebuilt/win64/crypto.lib");
return;
}
const lib = createCrypto(step.builder, step.target, step.build_mode) catch unreachable;
linkLibCrypto(step, lib);
}
}
pub fn linkLibCrypto(step: *std.build.LibExeObjStep, lib: *std.build.LibExeObjStep) void {
linkLibCryptoDeps(step);
step.linkLibrary(lib);
}
pub fn linkLibCryptoPath(step: *std.build.LibExeObjStep, path: []const u8) void {
linkLibCryptoDeps(step);
step.addAssemblyFile(path);
}
fn linkLibCryptoDeps(step: *std.build.LibExeObjStep) void {
const target = step.target;
if (target.getOsTag() == .windows and target.getAbi() == .gnu) {
step.linkSystemLibrary("ws2_32");
}
}
// TODO: Don't build support for tls1.0 and tls1.1 https://github.com/openssl/openssl/issues/7048
pub fn createSsl(
b: *std.build.Builder,
target: std.zig.CrossTarget,
mode: std.builtin.Mode,
) !*std.build.LibExeObjStep {
const lib = b.addStaticLibrary("ssl", null);
lib.setTarget(target);
lib.setBuildMode(mode);
const alloc = b.allocator;
var c_flags = std.ArrayList([]const u8).init(alloc);
// ssl doesn't seem to use opensslconf.h/configuration.h so some of this is duped.
try c_flags.appendSlice(&.{
// Don't include deprecated.
"-DOPENSSL_NO_DEPRECATED",
// Engine api is deprecated in openssl v3.0
"-DOPENSSL_NO_ENGINE",
// SRP is deprecated in openssl v3.0
"-DOPENSSL_NO_SRP",
// Disable console related code.
"-DOPENSSL_NO_UI_CONSOLE",
});
// Don't include wincrypt.h from window.h which has conflicting declarations with crypto X509_EXTENSIONS.
// Only when compiling to windows-gnu.
if (target.getOsTag() == .windows and target.getAbi() == .gnu) {
try c_flags.append("-DNOCRYPT=1");
}
const c_files = &[_][]const u8{
// Copied from openssl/ssl/build.info
"pqueue.c",
"statem/statem_srvr.c",
"statem/statem_clnt.c",
"s3_lib.c",
"s3_enc.c",
"record/rec_layer_s3.c",
"statem/statem_lib.c",
"statem/extensions.c",
"statem/extensions_srvr.c",
"statem/extensions_clnt.c",
"statem/extensions_cust.c",
"s3_msg.c",
"methods.c",
"t1_lib.c",
"t1_enc.c",
"tls13_enc.c",
"d1_lib.c",
"record/rec_layer_d1.c",
"d1_msg.c",
"statem/statem_dtls.c",
"d1_srtp.c",
"ssl_lib.c",
"ssl_cert.c",
"ssl_sess.c",
"ssl_ciph.c",
"ssl_stat.c",
"ssl_rsa.c",
"ssl_asn1.c",
"ssl_txt.c",
"ssl_init.c",
"ssl_conf.c",
"ssl_mcnf.c",
"bio_ssl.c",
"ssl_err.c",
"ssl_err_legacy.c",
"tls_srp.c",
"t1_trce.c",
"ssl_utst.c",
"record/ssl3_buffer.c",
"record/ssl3_record.c",
"record/dtls1_bitmap.c",
"statem/statem.c",
"record/ssl3_record_tls13.c",
"tls_depr.c",
// shared
"record/tls_pad.c",
"s3_cbc.c",
};
for (c_files) |file| {
const path = b.fmt("{s}/vendor/ssl/{s}", .{ srcPath(), file });
lib.addCSourceFile(path, c_flags.items);
}
lib.disable_sanitize_c = true;
lib.linkLibC();
// openssl headers need to be generated with:
// ./Configure
// make build_all_generated
lib.addIncludeDir(fromRoot(b, "vendor/include"));
lib.addIncludeDir(fromRoot(b, "vendor"));
return lib;
}
pub const SslOptions = struct {
lib_path: ?[]const u8 = null,
};
pub fn buildAndLinkSsl(step: *std.build.LibExeObjStep, opts: SslOptions) void {
if (opts.lib_path) |path| {
linkLibSslPath(step, path);
} else {
if (builtin.os.tag == .windows) {
step.addAssemblyFile(srcPath() ++ "/../extras/prebuilt/win64/ssl.lib");
return;
}
const lib = createSsl(step.builder, step.target, step.build_mode) catch unreachable;
linkLibSsl(step, lib);
}
}
pub fn linkLibSsl(step: *std.build.LibExeObjStep, lib: *std.build.LibExeObjStep) void {
step.linkLibrary(lib);
}
pub fn linkLibSslPath(step: *std.build.LibExeObjStep, path: []const u8) void {
step.addAssemblyFile(path);
}
fn srcPath() []const u8 {
return (std.fs.path.dirname(@src().file) orelse unreachable);
}
fn fromRoot(b: *std.build.Builder, rel_path: []const u8) []const u8 {
return std.fs.path.resolve(b.allocator, &.{ srcPath(), rel_path }) catch unreachable;
} | lib/openssl/lib.zig |
const std = @import("std");
const builtin = @import("builtin");
const testing = std.testing;
const expect = testing.expect;
const expectEqual = testing.expectEqual;
test "one param, explicit comptime" {
var x: usize = 0;
x += checkSize(i32);
x += checkSize(bool);
x += checkSize(bool);
try expect(x == 6);
}
fn checkSize(comptime T: type) usize {
return @sizeOf(T);
}
test "simple generic fn" {
if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest;
try expect(max(i32, 3, -1) == 3);
try expect(max(u8, 1, 100) == 100);
if (builtin.zig_backend == .stage1) {
// TODO: stage2 is incorrectly emitting the following:
// error: cast of value 1.23e-01 to type 'f32' loses information
try expect(max(f32, 0.123, 0.456) == 0.456);
}
try expect(add(2, 3) == 5);
}
fn max(comptime T: type, a: T, b: T) T {
return if (a > b) a else b;
}
fn add(comptime a: i32, b: i32) i32 {
return (comptime a) + b;
}
const the_max = max(u32, 1234, 5678);
test "compile time generic eval" {
try expect(the_max == 5678);
}
fn gimmeTheBigOne(a: u32, b: u32) u32 {
return max(u32, a, b);
}
fn shouldCallSameInstance(a: u32, b: u32) u32 {
return max(u32, a, b);
}
fn sameButWithFloats(a: f64, b: f64) f64 {
return max(f64, a, b);
}
test "fn with comptime args" {
if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest;
if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest;
if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest;
try expect(gimmeTheBigOne(1234, 5678) == 5678);
try expect(shouldCallSameInstance(34, 12) == 34);
try expect(sameButWithFloats(0.43, 0.49) == 0.49);
}
test "anytype params" {
if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest;
if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest;
if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest;
try expect(max_i32(12, 34) == 34);
try expect(max_f64(1.2, 3.4) == 3.4);
comptime {
try expect(max_i32(12, 34) == 34);
try expect(max_f64(1.2, 3.4) == 3.4);
}
}
fn max_anytype(a: anytype, b: anytype) @TypeOf(a, b) {
return if (a > b) a else b;
}
fn max_i32(a: i32, b: i32) i32 {
return max_anytype(a, b);
}
fn max_f64(a: f64, b: f64) f64 {
return max_anytype(a, b);
}
test "type constructed by comptime function call" {
if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest;
if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest;
if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest;
var l: SimpleList(10) = undefined;
l.array[0] = 10;
l.array[1] = 11;
l.array[2] = 12;
const ptr = @ptrCast([*]u8, &l.array);
try expect(ptr[0] == 10);
try expect(ptr[1] == 11);
try expect(ptr[2] == 12);
}
fn SimpleList(comptime L: usize) type {
var mutable_T = u8;
const T = mutable_T;
return struct {
array: [L]T,
};
}
test "function with return type type" {
if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest;
if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest;
var list: List(i32) = undefined;
var list2: List(i32) = undefined;
list.length = 10;
list2.length = 10;
try expect(list.prealloc_items.len == 8);
try expect(list2.prealloc_items.len == 8);
}
pub fn List(comptime T: type) type {
return SmallList(T, 8);
}
pub fn SmallList(comptime T: type, comptime STATIC_SIZE: usize) type {
return struct {
items: []T,
length: usize,
prealloc_items: [STATIC_SIZE]T,
};
}
test "const decls in struct" {
try expect(GenericDataThing(3).count_plus_one == 4);
}
fn GenericDataThing(comptime count: isize) type {
return struct {
const count_plus_one = count + 1;
};
}
test "use generic param in generic param" {
try expect(aGenericFn(i32, 3, 4) == 7);
}
fn aGenericFn(comptime T: type, comptime a: T, b: T) T {
return a + b;
}
test "generic fn with implicit cast" {
if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest;
if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest;
try expect(getFirstByte(u8, &[_]u8{13}) == 13);
try expect(getFirstByte(u16, &[_]u16{
0,
13,
}) == 0);
}
fn getByte(ptr: ?*const u8) u8 {
return ptr.?.*;
}
fn getFirstByte(comptime T: type, mem: []const T) u8 {
return getByte(@ptrCast(*const u8, &mem[0]));
}
test "generic fn keeps non-generic parameter types" {
if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest;
if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest;
const A = 128;
const S = struct {
fn f(comptime T: type, s: []T) !void {
try expect(A != @typeInfo(@TypeOf(s)).Pointer.alignment);
}
};
// The compiler monomorphizes `S.f` for `T=u8` on its first use, check that
// `x` type not affect `s` parameter type.
var x: [16]u8 align(A) = undefined;
try S.f(u8, &x);
}
test "array of generic fns" {
try expect(foos[0](true));
try expect(!foos[1](true));
}
const foos = [_]fn (anytype) bool{
foo1,
foo2,
};
fn foo1(arg: anytype) bool {
return arg;
}
fn foo2(arg: anytype) bool {
return !arg;
}
test "generic struct" {
if (builtin.zig_backend == .stage2_c) return error.SkipZigTest;
if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest;
var a1 = GenNode(i32){
.value = 13,
.next = null,
};
var b1 = GenNode(bool){
.value = true,
.next = null,
};
try expect(a1.value == 13);
try expect(a1.value == a1.getVal());
try expect(b1.getVal());
}
fn GenNode(comptime T: type) type {
return struct {
value: T,
next: ?*GenNode(T),
fn getVal(n: *const GenNode(T)) T {
return n.value;
}
};
}
test "function parameter is generic" {
const S = struct {
pub fn init(pointer: anytype, comptime fillFn: fn (ptr: *@TypeOf(pointer)) void) void {
_ = fillFn;
}
pub fn fill(self: *u32) void {
_ = self;
}
};
var rng: u32 = 2;
S.init(rng, S.fill);
} | test/behavior/generics.zig |
const std = @import("../std.zig");
const io = std.io;
const mem = std.mem;
const assert = std.debug.assert;
/// Automatically inserts indentation of written data by keeping
/// track of the current indentation level
pub fn AutoIndentingStream(comptime UnderlyingWriter: type) type {
return struct {
const Self = @This();
pub const Error = UnderlyingWriter.Error;
pub const Writer = io.Writer(*Self, Error, write);
underlying_writer: UnderlyingWriter,
indent_count: usize = 0,
indent_delta: usize,
current_line_empty: bool = true,
indent_one_shot_count: usize = 0, // automatically popped when applied
applied_indent: usize = 0, // the most recently applied indent
indent_next_line: usize = 0, // not used until the next line
pub fn writer(self: *Self) Writer {
return .{ .context = self };
}
pub fn write(self: *Self, bytes: []const u8) Error!usize {
if (bytes.len == 0)
return @as(usize, 0);
try self.applyIndent();
return self.writeNoIndent(bytes);
}
// Change the indent delta without changing the final indentation level
pub fn setIndentDelta(self: *Self, indent_delta: usize) void {
if (self.indent_delta == indent_delta) {
return;
} else if (self.indent_delta > indent_delta) {
assert(self.indent_delta % indent_delta == 0);
self.indent_count = self.indent_count * (self.indent_delta / indent_delta);
} else {
// assert that the current indentation (in spaces) in a multiple of the new delta
assert((self.indent_count * self.indent_delta) % indent_delta == 0);
self.indent_count = self.indent_count / (indent_delta / self.indent_delta);
}
self.indent_delta = indent_delta;
}
fn writeNoIndent(self: *Self, bytes: []const u8) Error!usize {
if (bytes.len == 0)
return @as(usize, 0);
try self.underlying_writer.writeAll(bytes);
if (bytes[bytes.len - 1] == '\n')
self.resetLine();
return bytes.len;
}
pub fn insertNewline(self: *Self) Error!void {
_ = try self.writeNoIndent("\n");
}
fn resetLine(self: *Self) void {
self.current_line_empty = true;
self.indent_next_line = 0;
}
/// Insert a newline unless the current line is blank
pub fn maybeInsertNewline(self: *Self) Error!void {
if (!self.current_line_empty)
try self.insertNewline();
}
/// Push default indentation
pub fn pushIndent(self: *Self) void {
// Doesn't actually write any indentation.
// Just primes the stream to be able to write the correct indentation if it needs to.
self.indent_count += 1;
}
/// Push an indent that is automatically popped after being applied
pub fn pushIndentOneShot(self: *Self) void {
self.indent_one_shot_count += 1;
self.pushIndent();
}
/// Turns all one-shot indents into regular indents
/// Returns number of indents that must now be manually popped
pub fn lockOneShotIndent(self: *Self) usize {
var locked_count = self.indent_one_shot_count;
self.indent_one_shot_count = 0;
return locked_count;
}
/// Push an indent that should not take effect until the next line
pub fn pushIndentNextLine(self: *Self) void {
self.indent_next_line += 1;
self.pushIndent();
}
pub fn popIndent(self: *Self) void {
assert(self.indent_count != 0);
self.indent_count -= 1;
if (self.indent_next_line > 0)
self.indent_next_line -= 1;
}
/// Writes ' ' bytes if the current line is empty
fn applyIndent(self: *Self) Error!void {
const current_indent = self.currentIndent();
if (self.current_line_empty and current_indent > 0) {
try self.underlying_writer.writeByteNTimes(' ', current_indent);
self.applied_indent = current_indent;
}
self.indent_count -= self.indent_one_shot_count;
self.indent_one_shot_count = 0;
self.current_line_empty = false;
}
/// Checks to see if the most recent indentation exceeds the currently pushed indents
pub fn isLineOverIndented(self: *Self) bool {
if (self.current_line_empty) return false;
return self.applied_indent > self.currentIndent();
}
fn currentIndent(self: *Self) usize {
var indent_current: usize = 0;
if (self.indent_count > 0) {
const indent_count = self.indent_count - self.indent_next_line;
indent_current = indent_count * self.indent_delta;
}
return indent_current;
}
};
}
pub fn autoIndentingStream(
indent_delta: usize,
underlying_writer: anytype,
) AutoIndentingStream(@TypeOf(underlying_writer)) {
return AutoIndentingStream(@TypeOf(underlying_writer)){
.underlying_writer = underlying_writer,
.indent_delta = indent_delta,
};
} | lib/std/io/auto_indenting_stream.zig |
const builtin = @import("builtin");
const std = @import("../index.zig");
const math = std.math;
const assert = std.debug.assert;
const assertError = std.debug.assertError;
// This implementation is based on that from the rust stlib
pub fn powi(comptime T: type, x: T, y: T) (error{Overflow, Underflow}!T) {
const info = @typeInfo(T);
comptime assert(@typeInfo(T) == builtin.TypeId.Int);
// powi(x, +-0) = 1 for any x
if (y == 0 or y == -0) {
return 0;
}
switch (x) {
// powi(0, y) = 1 for any y
0 => return 0,
// powi(1, y) = 1 for any y
1 => return 1,
else => {
// powi(x, y) = Overflow for for y >= @sizeOf(x) - 1 y > 0
// powi(x, y) = Underflow for for y > @sizeOf(x) - 1 y < 0
const bit_size = @sizeOf(T) * 8;
if (info.Int.is_signed) {
if (x == -1) {
// powi(-1, y) = -1 for for y an odd integer
// powi(-1, y) = 1 for for y an even integer
if (@mod(y, 2) == 0) {
return 1;
} else {
return -1;
}
}
if (x > 0 and y >= bit_size - 1) {
return error.Overflow;
} else if (x < 0 and y > bit_size - 1) {
return error.Underflow;
}
} else {
if (y >= bit_size) {
return error.Overflow;
}
}
var base = x;
var exp = y;
var acc: T = 1;
while (exp > 1) {
if (exp & 1 == 1) {
if (@mulWithOverflow(T, acc, base, &acc)) {
if (x > 0) {
return error.Overflow;
} else {
return error.Underflow;
}
}
}
exp >>= 1;
if (@mulWithOverflow(T, base, base, &base)) {
if (x > 0) {
return error.Overflow;
} else {
return error.Underflow;
}
}
}
if (exp == 1) {
if (@mulWithOverflow(T, acc, base, &acc)) {
if (x > 0) {
return error.Overflow;
} else {
return error.Underflow;
}
}
}
return acc;
}
}
}
test "math.powi" {
assertError(powi(i8, -66, 6), error.Underflow);
assertError(powi(i16, -13, 13), error.Underflow);
assertError(powi(i32, -32, 21), error.Underflow);
assertError(powi(i64, -24, 61), error.Underflow);
assertError(powi(i17, -15, 15), error.Underflow);
assertError(powi(i42, -6, 40), error.Underflow);
assert((try powi(i8, -5, 3)) == -125);
assert((try powi(i16, -16, 3)) == -4096);
assert((try powi(i32, -91, 3)) == -753571);
assert((try powi(i64, -36, 6)) == 2176782336);
assert((try powi(i17, -2, 15)) == -32768);
assert((try powi(i42, -5, 7)) == -78125);
assert((try powi(u8, 6, 2)) == 36);
assert((try powi(u16, 5, 4)) == 625);
assert((try powi(u32, 12, 6)) == 2985984);
assert((try powi(u64, 34, 2)) == 1156);
assert((try powi(u17, 16, 3)) == 4096);
assert((try powi(u42, 34, 6)) == 1544804416);
assertError(powi(i8, 120, 7), error.Overflow);
assertError(powi(i16, 73, 15), error.Overflow);
assertError(powi(i32, 23, 31), error.Overflow);
assertError(powi(i64, 68, 61), error.Overflow);
assertError(powi(i17, 15, 15), error.Overflow);
assertError(powi(i42, 121312, 41), error.Overflow);
assertError(powi(u8, 123, 7), error.Overflow);
assertError(powi(u16, 2313, 15), error.Overflow);
assertError(powi(u32, 8968, 31), error.Overflow);
assertError(powi(u64, 2342, 63), error.Overflow);
assertError(powi(u17, 2723, 16), error.Overflow);
assertError(powi(u42, 8234, 41), error.Overflow);
}
test "math.powi.special" {
assertError(powi(i8, -2, 8), error.Underflow);
assertError(powi(i16, -2, 16), error.Underflow);
assertError(powi(i32, -2, 32), error.Underflow);
assertError(powi(i64, -2, 64), error.Underflow);
assertError(powi(i17, -2, 17), error.Underflow);
assertError(powi(i42, -2, 42), error.Underflow);
assert((try powi(i8, -1, 3)) == -1);
assert((try powi(i16, -1, 2)) == 1);
assert((try powi(i32, -1, 16)) == 1);
assert((try powi(i64, -1, 6)) == 1);
assert((try powi(i17, -1, 15)) == -1);
assert((try powi(i42, -1, 7)) == -1);
assert((try powi(u8, 1, 2)) == 1);
assert((try powi(u16, 1, 4)) == 1);
assert((try powi(u32, 1, 6)) == 1);
assert((try powi(u64, 1, 2)) == 1);
assert((try powi(u17, 1, 3)) == 1);
assert((try powi(u42, 1, 6)) == 1);
assertError(powi(i8, 2, 7), error.Overflow);
assertError(powi(i16, 2, 15), error.Overflow);
assertError(powi(i32, 2, 31), error.Overflow);
assertError(powi(i64, 2, 63), error.Overflow);
assertError(powi(i17, 2, 16), error.Overflow);
assertError(powi(i42, 2, 41), error.Overflow);
assertError(powi(u8, 2, 8), error.Overflow);
assertError(powi(u16, 2, 16), error.Overflow);
assertError(powi(u32, 2, 32), error.Overflow);
assertError(powi(u64, 2, 64), error.Overflow);
assertError(powi(u17, 2, 17), error.Overflow);
assertError(powi(u42, 2, 42), error.Overflow);
} | std/math/powi.zig |
const std = @import("std");
const fs = std.fs;
const io = std.io;
const info = std.log.info;
const print = std.debug.print;
const fmt = std.fmt;
const utils = @import("utils.zig");
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const SEEBACK: usize = 25;
fn isSum(num: usize, parts: []usize) bool {
for (parts) |part1, i| {
for (parts) |part2| {
if (part1 == part2) {
continue;
}
if (part1 + part2 == num) {
return true;
}
}
}
return false;
}
const RollingSumFinder = struct {
allo: *std.mem.Allocator = undefined,
target: usize = undefined,
rolling_sum: usize = 0,
hist: []usize = undefined,
pub fn init(allo: *std.mem.Allocator, target: usize) RollingSumFinder {
return RollingSumFinder{
.allo = allo,
.target = target,
.hist = allo.alloc(usize, 0) catch unreachable,
};
}
pub fn deinit(self: *RollingSumFinder) void {
self.allo.free(self.hist);
}
pub fn appendNum(self: *RollingSumFinder, num: usize) bool {
if (self.hist.len <= self.hist.len) {
self.hist = self.allo.realloc(self.hist, self.hist.len + 1) catch unreachable;
}
self.rolling_sum += num;
self.hist[self.hist.len - 1] = num;
if (self.rolling_sum > self.target) {
while (self.rolling_sum > self.target) {
self.rolling_sum -= self.hist[0];
const new_hist = self.allo.dupe(usize, self.hist[1..self.hist.len]) catch unreachable;
self.allo.free(self.hist);
self.hist = new_hist;
}
}
if (self.rolling_sum == self.target) {
return true;
}
return false;
}
};
pub fn main() !void {
const begin = @divTrunc(std.time.nanoTimestamp(), 1000);
// setup
//
defer _ = gpa.deinit();
var allo = &gpa.allocator;
var lines: std.mem.TokenIterator = try utils.readInputLines(allo, "./input1");
defer allo.free(lines.buffer);
var nums = allo.alloc(usize, 0) catch unreachable;
defer allo.free(nums);
while (lines.next()) |line| {
nums = allo.realloc(nums, nums.len + 1) catch unreachable;
nums[nums.len - 1] = fmt.parseUnsigned(usize, line, 10) catch unreachable;
}
// business logic
//
// p1
//
var hist: [SEEBACK]usize = [_]usize{0} ** SEEBACK;
var p1_target: ?usize = null;
// find our invalid number
const target = for (nums) |num, i| {
if (i >= SEEBACK and !isSum(num, &hist)) {
break num;
}
hist[i % SEEBACK] = num;
} else {
info("p1 not found :(", .{});
return error.P1_NOT_FOUND;
};
info("p1: {}", .{p1_target});
// p2
//
var roller = RollingSumFinder.init(allo, target);
defer roller.deinit();
for (nums) |num| {
const p2_done = roller.appendNum(num);
if (p2_done) {
const min = std.mem.min(usize, roller.hist);
const max = std.mem.max(usize, roller.hist);
info("p2 done! {}", .{min + max});
break;
}
}
const delta = @divTrunc(std.time.nanoTimestamp(), 1000) - begin;
print("all done in {} microseconds\n", .{delta});
} | day_09/src/main.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const curl = @cImport({
@cInclude("curl/curl.h");
});
const Repo = struct {
user: []const u8 = undefined,
name: []const u8 = undefined,
url: []const u8 = undefined,
};
pub fn main() anyerror!void {
// var alloc_buf: [10_000_000]u8 = undefined;
// var fba = std.heap.FixedBufferAllocator.init(&alloc_buf);
// const alloc = fba.allocator();
// var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
// defer arena.deinit();
// const alloc = arena.allocator();
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const alloc = gpa.allocator();
const stdout = std.io.getStdOut().writer();
const h = curl.curl_url();
var arg_iter = std.process.args();
while (try arg_iter.next(alloc)) |url| {
const repo = parseUrl(alloc, h, url);
if (repo == null) {
//not sure why this prints \252\252\252...
//std.log.warn("can't parse: {s}", .{url});
continue;
} else {
std.log.debug("{s} {s}", .{ repo.?.user, repo.?.name });
try gitClone(stdout, alloc, repo.?);
}
}
}
test "basic test" {
try std.testing.expectEqual(10, 3 + 7);
}
fn makeRepo(url: []const u8, path: []const u8) Repo {
var it = std.mem.split(u8, path, "/");
_ = it.next().?; // emptiness before the slash
const user = it.next().?;
const repo = it.next().?;
// sourcehut uses tildes like unix homedirs, gotta strip that
return Repo{
.url = url,
.user = if (user[0] == '~') user[1..] else user,
.name = repo,
};
}
fn parseUrl(alloc: Allocator, h: ?*curl.struct_Curl_URL, url: [:0]const u8) ?*Repo {
var host: ?[*:0]u8 = null;
var path: ?[*:0]u8 = null;
var repo: Repo = Repo{};
var uc = curl.curl_url_set(h, curl.CURLUPART_URL, url, 0);
defer alloc.free(url);
if (uc == 0) {
_ = curl.curl_url_get(h, curl.CURLUPART_HOST, &host, 1);
_ = curl.curl_url_get(h, curl.CURLUPART_PATH, &path, 1);
repo = makeRepo(
url,
// the span() converts the slice to a []const u8
std.mem.span(path.?),
);
return &repo;
} else {
return null;
}
}
fn gitClone(stdout: std.io.Writer(
std.fs.File,
std.os.WriteError,
std.fs.File.write,
), alloc: Allocator, repo: *Repo) !void {
_ = repo;
const args = &.{
"git",
"clone",
repo.url,
};
const result = std.ChildProcess.exec(.{
.allocator = alloc,
.argv = args,
.cwd = "/tmp",
.env_map = null,
.max_output_bytes = 10_000_000,
}) catch |err| {
std.log.warn("The following command failed:\n", .{});
return err;
};
// Happened upon this at
// https://github.com/ziglang/zig/issues/8969#issue-909829436
defer {
alloc.free(result.stdout);
alloc.free(result.stderr);
}
try stdout.print("{s}\n", .{result.stdout});
} | src/main.zig |
const builtin = @import("builtin");
const Os = builtin.Os;
pub use switch(builtin.os) {
Os.linux => @import("linux.zig"),
Os.windows => @import("windows.zig"),
Os.macosx, Os.ios => @import("darwin.zig"),
else => empty_import,
};
const empty_import = @import("../empty.zig");
pub extern "c" fn abort() noreturn;
pub extern "c" fn exit(code: c_int) noreturn;
pub extern "c" fn isatty(fd: c_int) c_int;
pub extern "c" fn close(fd: c_int) c_int;
pub extern "c" fn fstat(fd: c_int, buf: &Stat) c_int;
pub extern "c" fn @"fstat$INODE64"(fd: c_int, buf: &Stat) c_int;
pub extern "c" fn lseek(fd: c_int, offset: isize, whence: c_int) isize;
pub extern "c" fn open(path: &const u8, oflag: c_int, ...) c_int;
pub extern "c" fn raise(sig: c_int) c_int;
pub extern "c" fn read(fd: c_int, buf: &c_void, nbyte: usize) isize;
pub extern "c" fn stat(noalias path: &const u8, noalias buf: &Stat) c_int;
pub extern "c" fn write(fd: c_int, buf: &const c_void, nbyte: usize) isize;
pub extern "c" fn mmap(addr: ?&c_void, len: usize, prot: c_int, flags: c_int,
fd: c_int, offset: isize) ?&c_void;
pub extern "c" fn munmap(addr: &c_void, len: usize) c_int;
pub extern "c" fn unlink(path: &const u8) c_int;
pub extern "c" fn getcwd(buf: &u8, size: usize) ?&u8;
pub extern "c" fn waitpid(pid: c_int, stat_loc: &c_int, options: c_int) c_int;
pub extern "c" fn fork() c_int;
pub extern "c" fn access(path: &const u8, mode: c_uint) c_int;
pub extern "c" fn pipe(fds: &c_int) c_int;
pub extern "c" fn mkdir(path: &const u8, mode: c_uint) c_int;
pub extern "c" fn symlink(existing: &const u8, new: &const u8) c_int;
pub extern "c" fn rename(old: &const u8, new: &const u8) c_int;
pub extern "c" fn chdir(path: &const u8) c_int;
pub extern "c" fn execve(path: &const u8, argv: &const ?&const u8,
envp: &const ?&const u8) c_int;
pub extern "c" fn dup(fd: c_int) c_int;
pub extern "c" fn dup2(old_fd: c_int, new_fd: c_int) c_int;
pub extern "c" fn readlink(noalias path: &const u8, noalias buf: &u8, bufsize: usize) isize;
pub extern "c" fn realpath(noalias file_name: &const u8, noalias resolved_name: &u8) ?&u8;
pub extern "c" fn sigprocmask(how: c_int, noalias set: &const sigset_t, noalias oset: ?&sigset_t) c_int;
pub extern "c" fn gettimeofday(tv: ?&timeval, tz: ?&timezone) c_int;
pub extern "c" fn sigaction(sig: c_int, noalias act: &const Sigaction, noalias oact: ?&Sigaction) c_int;
pub extern "c" fn nanosleep(rqtp: &const timespec, rmtp: ?×pec) c_int;
pub extern "c" fn setreuid(ruid: c_uint, euid: c_uint) c_int;
pub extern "c" fn setregid(rgid: c_uint, egid: c_uint) c_int;
pub extern "c" fn rmdir(path: &const u8) c_int;
pub extern "c" fn aligned_alloc(alignment: usize, size: usize) ?&c_void;
pub extern "c" fn malloc(usize) ?&c_void;
pub extern "c" fn realloc(&c_void, usize) ?&c_void;
pub extern "c" fn free(&c_void) void;
pub extern "c" fn posix_memalign(memptr: &&c_void, alignment: usize, size: usize) c_int; | std/c/index.zig |
const fmath = @import("index.zig");
pub fn tan(x: var) -> @typeOf(x) {
const T = @typeOf(x);
switch (T) {
f32 => @inlineCall(tan32, x),
f64 => @inlineCall(tan64, x),
else => @compileError("tan not implemented for " ++ @typeName(T)),
}
}
const Tp0 = -1.30936939181383777646E4;
const Tp1 = 1.15351664838587416140E6;
const Tp2 = -1.79565251976484877988E7;
const Tq1 = 1.36812963470692954678E4;
const Tq2 = -1.32089234440210967447E6;
const Tq3 = 2.50083801823357915839E7;
const Tq4 = -5.38695755929454629881E7;
// NOTE: This is taken from the go stdlib. The musl implementation is much more complex.
//
// This may have slight differences on some edge cases and may need to replaced if so.
fn tan32(x_: f32) -> f32 {
const pi4a = 7.85398125648498535156e-1;
const pi4b = 3.77489470793079817668E-8;
const pi4c = 2.69515142907905952645E-15;
const m4pi = 1.273239544735162542821171882678754627704620361328125;
var x = x_;
if (x == 0 or fmath.isNan(x)) {
return x;
}
if (fmath.isInf(x)) {
return fmath.nan(f32);
}
var sign = false;
if (x < 0) {
x = -x;
sign = true;
}
var y = fmath.floor(x * m4pi);
var j = i64(y);
if (j & 1 == 1) {
j += 1;
y += 1;
}
const z = ((x - y * pi4a) - y * pi4b) - y * pi4c;
const w = z * z;
var r = {
if (w > 1e-14) {
z + z * (w * ((Tp0 * w + Tp1) * w + Tp2) / ((((w + Tq1) * w + Tq2) * w + Tq3) * w + Tq4))
} else {
z
}
};
if (j & 2 == 2) {
r = -1 / r;
}
if (sign) {
r = -r;
}
r
}
fn tan64(x_: f64) -> f64 {
const pi4a = 7.85398125648498535156e-1;
const pi4b = 3.77489470793079817668E-8;
const pi4c = 2.69515142907905952645E-15;
const m4pi = 1.273239544735162542821171882678754627704620361328125;
var x = x_;
if (x == 0 or fmath.isNan(x)) {
return x;
}
if (fmath.isInf(x)) {
return fmath.nan(f64);
}
var sign = false;
if (x < 0) {
x = -x;
sign = true;
}
var y = fmath.floor(x * m4pi);
var j = i64(y);
if (j & 1 == 1) {
j += 1;
y += 1;
}
const z = ((x - y * pi4a) - y * pi4b) - y * pi4c;
const w = z * z;
var r = {
if (w > 1e-14) {
z + z * (w * ((Tp0 * w + Tp1) * w + Tp2) / ((((w + Tq1) * w + Tq2) * w + Tq3) * w + Tq4))
} else {
z
}
};
if (j & 2 == 2) {
r = -1 / r;
}
if (sign) {
r = -r;
}
r
}
test "tan" {
fmath.assert(tan(f32(0.0)) == tan32(0.0));
fmath.assert(tan(f64(0.0)) == tan64(0.0));
}
test "tan32" {
const epsilon = 0.000001;
fmath.assert(fmath.approxEq(f32, tan32(0.0), 0.0, epsilon));
fmath.assert(fmath.approxEq(f32, tan32(0.2), 0.202710, epsilon));
fmath.assert(fmath.approxEq(f32, tan32(0.8923), 1.240422, epsilon));
fmath.assert(fmath.approxEq(f32, tan32(1.5), 14.101420, epsilon));
fmath.assert(fmath.approxEq(f32, tan32(37.45), -0.254397, epsilon));
fmath.assert(fmath.approxEq(f32, tan32(89.123), 2.285852, epsilon));
}
test "tan64" {
const epsilon = 0.000001;
fmath.assert(fmath.approxEq(f64, tan64(0.0), 0.0, epsilon));
fmath.assert(fmath.approxEq(f64, tan64(0.2), 0.202710, epsilon));
fmath.assert(fmath.approxEq(f64, tan64(0.8923), 1.240422, epsilon));
fmath.assert(fmath.approxEq(f64, tan64(1.5), 14.101420, epsilon));
fmath.assert(fmath.approxEq(f64, tan64(37.45), -0.254397, epsilon));
fmath.assert(fmath.approxEq(f64, tan64(89.123), 2.2858376, epsilon));
} | src/tan.zig |
pub const GUID_DEVINTERFACE_SENSOR = Guid.initString("ba1bb692-9b7a-4833-9a1e-525ed134e7e2");
pub const SENSOR_EVENT_STATE_CHANGED = Guid.initString("bfd96016-6bd7-4560-ad34-f2f6607e8f81");
pub const SENSOR_EVENT_DATA_UPDATED = Guid.initString("2ed0f2a4-0087-41d3-87db-6773370b3c88");
pub const SENSOR_EVENT_PROPERTY_CHANGED = Guid.initString("2358f099-84c9-4d3d-90df-c2421e2b2045");
pub const SENSOR_EVENT_ACCELEROMETER_SHAKE = Guid.initString("825f5a94-0f48-4396-9ca0-6ecb5c99d915");
pub const SENSOR_EVENT_PARAMETER_COMMON_GUID = Guid.initString("64346e30-8728-4b34-bdf6-4f52442c5c28");
pub const SENSOR_ERROR_PARAMETER_COMMON_GUID = Guid.initString("77112bcd-fce1-4f43-b8b8-a88256adb4b3");
pub const SENSOR_PROPERTY_COMMON_GUID = Guid.initString("7f8383ec-d3ec-495c-a8cf-b8bbe85c2920");
pub const SENSOR_CATEGORY_ALL = Guid.initString("c317c286-c468-4288-9975-d4c4587c442c");
pub const SENSOR_CATEGORY_LOCATION = Guid.initString("bfa794e4-f964-4fdb-90f6-51056bfe4b44");
pub const SENSOR_CATEGORY_ENVIRONMENTAL = Guid.initString("323439aa-7f66-492b-ba0c-73e9aa0a65d5");
pub const SENSOR_CATEGORY_MOTION = Guid.initString("cd09daf1-3b2e-4c3d-b598-b5e5ff93fd46");
pub const SENSOR_CATEGORY_ORIENTATION = Guid.initString("9e6c04b6-96fe-4954-b726-68682a473f69");
pub const SENSOR_CATEGORY_MECHANICAL = Guid.initString("8d131d68-8ef7-4656-80b5-cccbd93791c5");
pub const SENSOR_CATEGORY_ELECTRICAL = Guid.initString("fb73fcd8-fc4a-483c-ac58-27b691c6beff");
pub const SENSOR_CATEGORY_BIOMETRIC = Guid.initString("ca19690f-a2c7-477d-a99e-99ec6e2b5648");
pub const SENSOR_CATEGORY_LIGHT = Guid.initString("17a665c0-9063-4216-b202-5c7a255e18ce");
pub const SENSOR_CATEGORY_SCANNER = Guid.initString("b000e77e-f5b5-420f-815d-0270a726f270");
pub const SENSOR_CATEGORY_OTHER = Guid.initString("2c90e7a9-f4c9-4fa2-af37-56d471fe5a3d");
pub const SENSOR_CATEGORY_UNSUPPORTED = Guid.initString("2beae7fa-19b0-48c5-a1f6-b5480dc206b0");
pub const SENSOR_TYPE_LOCATION_GPS = Guid.initString("ed4ca589-327a-4ff9-a560-91da4b48275e");
pub const SENSOR_TYPE_LOCATION_STATIC = Guid.initString("095f8184-0fa9-4445-8e6e-b70f320b6b4c");
pub const SENSOR_TYPE_LOCATION_LOOKUP = Guid.initString("3b2eae4a-72ce-436d-96d2-3c5b8570e987");
pub const SENSOR_TYPE_LOCATION_TRIANGULATION = Guid.initString("691c341a-5406-4fe1-942f-2246cbeb39e0");
pub const SENSOR_TYPE_LOCATION_OTHER = Guid.initString("9b2d0566-0368-4f71-b88d-533f132031de");
pub const SENSOR_TYPE_LOCATION_BROADCAST = Guid.initString("d26988cf-5162-4039-bb17-4c58b698e44a");
pub const SENSOR_TYPE_LOCATION_DEAD_RECKONING = Guid.initString("1a37d538-f28b-42da-9fce-a9d0a2a6d829");
pub const SENSOR_TYPE_ENVIRONMENTAL_TEMPERATURE = Guid.initString("04fd0ec4-d5da-45fa-95a9-5db38ee19306");
pub const SENSOR_TYPE_ENVIRONMENTAL_ATMOSPHERIC_PRESSURE = Guid.initString("0e903829-ff8a-4a93-97df-3dcbde402288");
pub const SENSOR_TYPE_ENVIRONMENTAL_HUMIDITY = Guid.initString("5c72bf67-bd7e-4257-990b-98a3ba3b400a");
pub const SENSOR_TYPE_ENVIRONMENTAL_WIND_SPEED = Guid.initString("dd50607b-a45f-42cd-8efd-ec61761c4226");
pub const SENSOR_TYPE_ENVIRONMENTAL_WIND_DIRECTION = Guid.initString("9ef57a35-9306-434d-af09-37fa5a9c00bd");
pub const SENSOR_TYPE_ACCELEROMETER_1D = Guid.initString("c04d2387-7340-4cc2-991e-3b18cb8ef2f4");
pub const SENSOR_TYPE_ACCELEROMETER_2D = Guid.initString("b2c517a8-f6b5-4ba6-a423-5df560b4cc07");
pub const SENSOR_TYPE_ACCELEROMETER_3D = Guid.initString("c2fb0f5f-e2d2-4c78-bcd0-352a9582819d");
pub const SENSOR_TYPE_MOTION_DETECTOR = Guid.initString("5c7c1a12-30a5-43b9-a4b2-cf09ec5b7be8");
pub const SENSOR_TYPE_GYROMETER_1D = Guid.initString("fa088734-f552-4584-8324-edfaf649652c");
pub const SENSOR_TYPE_GYROMETER_2D = Guid.initString("31ef4f83-919b-48bf-8de0-5d7a9d240556");
pub const SENSOR_TYPE_GYROMETER_3D = Guid.initString("09485f5a-759e-42c2-bd4b-a349b75c8643");
pub const SENSOR_TYPE_SPEEDOMETER = Guid.initString("6bd73c1f-0bb4-4310-81b2-dfc18a52bf94");
pub const SENSOR_TYPE_COMPASS_1D = Guid.initString("a415f6c5-cb50-49d0-8e62-a8270bd7a26c");
pub const SENSOR_TYPE_COMPASS_2D = Guid.initString("15655cc0-997a-4d30-84db-57caba3648bb");
pub const SENSOR_TYPE_COMPASS_3D = Guid.initString("76b5ce0d-17dd-414d-93a1-e127f40bdf6e");
pub const SENSOR_TYPE_INCLINOMETER_1D = Guid.initString("b96f98c5-7a75-4ba7-94e9-ac868c966dd8");
pub const SENSOR_TYPE_INCLINOMETER_2D = Guid.initString("ab140f6d-83eb-4264-b70b-b16a5b256a01");
pub const SENSOR_TYPE_INCLINOMETER_3D = Guid.initString("b84919fb-ea85-4976-8444-6f6f5c6d31db");
pub const SENSOR_TYPE_DISTANCE_1D = Guid.initString("5f14ab2f-1407-4306-a93f-b1dbabe4f9c0");
pub const SENSOR_TYPE_DISTANCE_2D = Guid.initString("5cf9a46c-a9a2-4e55-b6a1-a04aafa95a92");
pub const SENSOR_TYPE_DISTANCE_3D = Guid.initString("a20cae31-0e25-4772-9fe5-96608a1354b2");
pub const SENSOR_TYPE_AGGREGATED_QUADRANT_ORIENTATION = Guid.initString("9f81f1af-c4ab-4307-9904-c828bfb90829");
pub const SENSOR_TYPE_AGGREGATED_DEVICE_ORIENTATION = Guid.initString("cdb5d8f7-3cfd-41c8-8542-cce622cf5d6e");
pub const SENSOR_TYPE_AGGREGATED_SIMPLE_DEVICE_ORIENTATION = Guid.initString("86a19291-0482-402c-bf4c-addac52b1c39");
pub const SENSOR_TYPE_VOLTAGE = Guid.initString("c5484637-4fb7-4953-98b8-a56d8aa1fb1e");
pub const SENSOR_TYPE_CURRENT = Guid.initString("5adc9fce-15a0-4bbe-a1ad-2d38a9ae831c");
pub const SENSOR_TYPE_CAPACITANCE = Guid.initString("ca2ffb1c-2317-49c0-a0b4-b63ce63461a0");
pub const SENSOR_TYPE_RESISTANCE = Guid.initString("9993d2c8-c157-4a52-a7b5-195c76037231");
pub const SENSOR_TYPE_INDUCTANCE = Guid.initString("dc1d933f-c435-4c7d-a2fe-607192a524d3");
pub const SENSOR_TYPE_ELECTRICAL_POWER = Guid.initString("212f10f5-14ab-4376-9a43-a7794098c2fe");
pub const SENSOR_TYPE_POTENTIOMETER = Guid.initString("2b3681a9-cadc-45aa-a6ff-54957c8bb440");
pub const SENSOR_TYPE_FREQUENCY = Guid.initString("8cd2cbb6-73e6-4640-a709-72ae8fb60d7f");
pub const SENSOR_TYPE_BOOLEAN_SWITCH = Guid.initString("9c7e371f-1041-460b-8d5c-71e4752e350c");
pub const SENSOR_TYPE_MULTIVALUE_SWITCH = Guid.initString("b3ee4d76-37a4-4402-b25e-99c60a775fa1");
pub const SENSOR_TYPE_FORCE = Guid.initString("c2ab2b02-1a1c-4778-a81b-954a1788cc75");
pub const SENSOR_TYPE_SCALE = Guid.initString("c06dd92c-7feb-438e-9bf6-82207fff5bb8");
pub const SENSOR_TYPE_PRESSURE = Guid.initString("26d31f34-6352-41cf-b793-ea0713d53d77");
pub const SENSOR_TYPE_STRAIN = Guid.initString("c6d1ec0e-6803-4361-ad3d-85bcc58c6d29");
pub const SENSOR_TYPE_BOOLEAN_SWITCH_ARRAY = Guid.initString("545c8ba5-b143-4545-868f-ca7fd986b4f6");
pub const SENSOR_TYPE_HUMAN_PRESENCE = Guid.initString("c138c12b-ad52-451c-9375-87f518ff10c6");
pub const SENSOR_TYPE_HUMAN_PROXIMITY = Guid.initString("5220dae9-3179-4430-9f90-06266d2a34de");
pub const SENSOR_TYPE_TOUCH = Guid.initString("17db3018-06c4-4f7d-81af-9274b7599c27");
pub const SENSOR_TYPE_AMBIENT_LIGHT = Guid.initString("97f115c8-599a-4153-8894-d2d12899918a");
pub const SENSOR_TYPE_RFID_SCANNER = Guid.initString("44328ef5-02dd-4e8d-ad5d-9249832b2eca");
pub const SENSOR_TYPE_BARCODE_SCANNER = Guid.initString("990b3d8f-85bb-45ff-914d-998c04f372df");
pub const SENSOR_TYPE_CUSTOM = Guid.initString("e83af229-8640-4d18-a213-e22675ebb2c3");
pub const SENSOR_TYPE_UNKNOWN = Guid.initString("10ba83e3-ef4f-41ed-9885-a87d6435a8e1");
pub const SENSOR_DATA_TYPE_COMMON_GUID = Guid.initString("db5e0cf2-cf1f-4c18-b46c-d86011d62150");
pub const SENSOR_DATA_TYPE_LOCATION_GUID = Guid.initString("055c74d8-ca6f-47d6-95c6-1ed3637a0ff4");
pub const SENSOR_DATA_TYPE_ENVIRONMENTAL_GUID = Guid.initString("8b0aa2f1-2d57-42ee-8cc0-4d27622b46c4");
pub const SENSOR_DATA_TYPE_MOTION_GUID = Guid.initString("3f8a69a2-07c5-4e48-a965-cd797aab56d5");
pub const SENSOR_DATA_TYPE_ORIENTATION_GUID = Guid.initString("1637d8a2-4248-4275-865d-558de84aedfd");
pub const SENSOR_DATA_TYPE_GUID_MECHANICAL_GUID = Guid.initString("38564a7c-f2f2-49bb-9b2b-ba60f66a58df");
pub const SENSOR_DATA_TYPE_BIOMETRIC_GUID = Guid.initString("2299288a-6d9e-4b0b-b7ec-3528f89e40af");
pub const SENSOR_DATA_TYPE_LIGHT_GUID = Guid.initString("e4c77ce2-dcb7-46e9-8439-4fec548833a6");
pub const SENSOR_DATA_TYPE_SCANNER_GUID = Guid.initString("d7a59a3c-3421-44ab-8d3a-9de8ab6c4cae");
pub const SENSOR_DATA_TYPE_ELECTRICAL_GUID = Guid.initString("bbb246d1-e242-4780-a2d3-cded84f35842");
pub const SENSOR_DATA_TYPE_CUSTOM_GUID = Guid.initString("b14c764f-07cf-41e8-9d82-ebe3d0776a6f");
pub const SENSOR_PROPERTY_TEST_GUID = Guid.initString("e1e962f4-6e65-45f7-9c36-d487b7b1bd34");
pub const GNSS_CLEAR_ALL_ASSISTANCE_DATA = @as(u32, 1);
pub const GUID_SensorCategory_All = Guid.initString("c317c286-c468-4288-9975-d4c4587c442c");
pub const GUID_SensorCategory_Biometric = Guid.initString("ca19690f-a2c7-477d-a99e-99ec6e2b5648");
pub const GUID_SensorCategory_Electrical = Guid.initString("fb73fcd8-fc4a-483c-ac58-27b691c6beff");
pub const GUID_SensorCategory_Environmental = Guid.initString("323439aa-7f66-492b-ba0c-73e9aa0a65d5");
pub const GUID_SensorCategory_Light = Guid.initString("17a665c0-9063-4216-b202-5c7a255e18ce");
pub const GUID_SensorCategory_Location = Guid.initString("bfa794e4-f964-4fdb-90f6-51056bfe4b44");
pub const GUID_SensorCategory_Mechanical = Guid.initString("8d131d68-8ef7-4656-80b5-cccbd93791c5");
pub const GUID_SensorCategory_Motion = Guid.initString("cd09daf1-3b2e-4c3d-b598-b5e5ff93fd46");
pub const GUID_SensorCategory_Orientation = Guid.initString("9e6c04b6-96fe-4954-b726-68682a473f69");
pub const GUID_SensorCategory_Other = Guid.initString("2c90e7a9-f4c9-4fa2-af37-56d471fe5a3d");
pub const GUID_SensorCategory_PersonalActivity = Guid.initString("f1609081-1e12-412b-a14d-cbb0e95bd2e5");
pub const GUID_SensorCategory_Scanner = Guid.initString("b000e77e-f5b5-420f-815d-0270a726f270");
pub const GUID_SensorCategory_Unsupported = Guid.initString("2beae7fa-19b0-48c5-a1f6-b5480dc206b0");
pub const GUID_SensorType_Accelerometer3D = Guid.initString("c2fb0f5f-e2d2-4c78-bcd0-352a9582819d");
pub const GUID_SensorType_ActivityDetection = Guid.initString("9d9e0118-1807-4f2e-96e4-2ce57142e196");
pub const GUID_SensorType_AmbientLight = Guid.initString("97f115c8-599a-4153-8894-d2d12899918a");
pub const GUID_SensorType_Barometer = Guid.initString("0e903829-ff8a-4a93-97df-3dcbde402288");
pub const GUID_SensorType_Custom = Guid.initString("e83af229-8640-4d18-a213-e22675ebb2c3");
pub const GUID_SensorType_FloorElevation = Guid.initString("ade4987f-7ac4-4dfa-9722-0a027181c747");
pub const GUID_SensorType_GeomagneticOrientation = Guid.initString("e77195f8-2d1f-4823-971b-1c4467556c9d");
pub const GUID_SensorType_GravityVector = Guid.initString("03b52c73-bb76-463f-9524-38de76eb700b");
pub const GUID_SensorType_Gyrometer3D = Guid.initString("09485f5a-759e-42c2-bd4b-a349b75c8643");
pub const GUID_SensorType_Humidity = Guid.initString("5c72bf67-bd7e-4257-990b-98a3ba3b400a");
pub const GUID_SensorType_LinearAccelerometer = Guid.initString("038b0283-97b4-41c8-bc24-5ff1aa48fec7");
pub const GUID_SensorType_Magnetometer3D = Guid.initString("55e5effb-15c7-40df-8698-a84b7c863c53");
pub const GUID_SensorType_Orientation = Guid.initString("cdb5d8f7-3cfd-41c8-8542-cce622cf5d6e");
pub const GUID_SensorType_Pedometer = Guid.initString("b19f89af-e3eb-444b-8dea-202575a71599");
pub const GUID_SensorType_Proximity = Guid.initString("5220dae9-3179-4430-9f90-06266d2a34de");
pub const GUID_SensorType_RelativeOrientation = Guid.initString("40993b51-4706-44dc-98d5-c920c037ffab");
pub const GUID_SensorType_SimpleDeviceOrientation = Guid.initString("86a19291-0482-402c-bf4c-addac52b1c39");
pub const GUID_SensorType_Temperature = Guid.initString("04fd0ec4-d5da-45fa-95a9-5db38ee19306");
pub const GUID_SensorType_HingeAngle = Guid.initString("82358065-f4c4-4da1-b272-13c23332a207");
pub const SENSOR_PROPERTY_LIST_HEADER_SIZE = @as(u32, 8);
//--------------------------------------------------------------------------------
// Section: Types (36)
//--------------------------------------------------------------------------------
const CLSID_SensorManager_Value = @import("../zig.zig").Guid.initString("77a1c827-fcd2-4689-8915-9d613cc5fa3e");
pub const CLSID_SensorManager = &CLSID_SensorManager_Value;
const CLSID_SensorCollection_Value = @import("../zig.zig").Guid.initString("79c43adb-a429-469f-aa39-2f2b74b75937");
pub const CLSID_SensorCollection = &CLSID_SensorCollection_Value;
const CLSID_Sensor_Value = @import("../zig.zig").Guid.initString("e97ced00-523a-4133-bf6f-d3a2dae7f6ba");
pub const CLSID_Sensor = &CLSID_Sensor_Value;
const CLSID_SensorDataReport_Value = @import("../zig.zig").Guid.initString("4ea9d6ef-694b-4218-8816-ccda8da74bba");
pub const CLSID_SensorDataReport = &CLSID_SensorDataReport_Value;
pub const SensorState = enum(i32) {
MIN = 0,
// READY = 0, this enum value conflicts with MIN
NOT_AVAILABLE = 1,
NO_DATA = 2,
INITIALIZING = 3,
ACCESS_DENIED = 4,
ERROR = 5,
// MAX = 5, this enum value conflicts with ERROR
};
pub const SENSOR_STATE_MIN = SensorState.MIN;
pub const SENSOR_STATE_READY = SensorState.MIN;
pub const SENSOR_STATE_NOT_AVAILABLE = SensorState.NOT_AVAILABLE;
pub const SENSOR_STATE_NO_DATA = SensorState.NO_DATA;
pub const SENSOR_STATE_INITIALIZING = SensorState.INITIALIZING;
pub const SENSOR_STATE_ACCESS_DENIED = SensorState.ACCESS_DENIED;
pub const SENSOR_STATE_ERROR = SensorState.ERROR;
pub const SENSOR_STATE_MAX = SensorState.ERROR;
pub const SensorConnectionType = enum(i32) {
INTEGRATED = 0,
ATTACHED = 1,
EXTERNAL = 2,
};
pub const SENSOR_CONNECTION_TYPE_PC_INTEGRATED = SensorConnectionType.INTEGRATED;
pub const SENSOR_CONNECTION_TYPE_PC_ATTACHED = SensorConnectionType.ATTACHED;
pub const SENSOR_CONNECTION_TYPE_PC_EXTERNAL = SensorConnectionType.EXTERNAL;
pub const LOCATION_DESIRED_ACCURACY = enum(i32) {
DEFAULT = 0,
HIGH = 1,
};
pub const LOCATION_DESIRED_ACCURACY_DEFAULT = LOCATION_DESIRED_ACCURACY.DEFAULT;
pub const LOCATION_DESIRED_ACCURACY_HIGH = LOCATION_DESIRED_ACCURACY.HIGH;
pub const LOCATION_POSITION_SOURCE = enum(i32) {
CELLULAR = 0,
SATELLITE = 1,
WIFI = 2,
IPADDRESS = 3,
UNKNOWN = 4,
};
pub const LOCATION_POSITION_SOURCE_CELLULAR = LOCATION_POSITION_SOURCE.CELLULAR;
pub const LOCATION_POSITION_SOURCE_SATELLITE = LOCATION_POSITION_SOURCE.SATELLITE;
pub const LOCATION_POSITION_SOURCE_WIFI = LOCATION_POSITION_SOURCE.WIFI;
pub const LOCATION_POSITION_SOURCE_IPADDRESS = LOCATION_POSITION_SOURCE.IPADDRESS;
pub const LOCATION_POSITION_SOURCE_UNKNOWN = LOCATION_POSITION_SOURCE.UNKNOWN;
pub const SimpleDeviceOrientation = enum(i32) {
NOT_ROTATED = 0,
ROTATED_90 = 1,
ROTATED_180 = 2,
ROTATED_270 = 3,
ROTATED_FACE_UP = 4,
ROTATED_FACE_DOWN = 5,
};
pub const SIMPLE_DEVICE_ORIENTATION_NOT_ROTATED = SimpleDeviceOrientation.NOT_ROTATED;
pub const SIMPLE_DEVICE_ORIENTATION_ROTATED_90 = SimpleDeviceOrientation.ROTATED_90;
pub const SIMPLE_DEVICE_ORIENTATION_ROTATED_180 = SimpleDeviceOrientation.ROTATED_180;
pub const SIMPLE_DEVICE_ORIENTATION_ROTATED_270 = SimpleDeviceOrientation.ROTATED_270;
pub const SIMPLE_DEVICE_ORIENTATION_ROTATED_FACE_UP = SimpleDeviceOrientation.ROTATED_FACE_UP;
pub const SIMPLE_DEVICE_ORIENTATION_ROTATED_FACE_DOWN = SimpleDeviceOrientation.ROTATED_FACE_DOWN;
pub const MagnetometerAccuracy = enum(i32) {
UNKNOWN = 0,
UNRELIABLE = 1,
APPROXIMATE = 2,
HIGH = 3,
};
pub const MAGNETOMETER_ACCURACY_UNKNOWN = MagnetometerAccuracy.UNKNOWN;
pub const MAGNETOMETER_ACCURACY_UNRELIABLE = MagnetometerAccuracy.UNRELIABLE;
pub const MAGNETOMETER_ACCURACY_APPROXIMATE = MagnetometerAccuracy.APPROXIMATE;
pub const MAGNETOMETER_ACCURACY_HIGH = MagnetometerAccuracy.HIGH;
// TODO: this type is limited to platform 'windows6.1'
const IID_ISensorManager_Value = @import("../zig.zig").Guid.initString("bd77db67-45a8-42dc-8d00-6dcf15f8377a");
pub const IID_ISensorManager = &IID_ISensorManager_Value;
pub const ISensorManager = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetSensorsByCategory: fn(
self: *const ISensorManager,
sensorCategory: ?*Guid,
ppSensorsFound: ?*?*ISensorCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSensorsByType: fn(
self: *const ISensorManager,
sensorType: ?*Guid,
ppSensorsFound: ?*?*ISensorCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSensorByID: fn(
self: *const ISensorManager,
sensorID: ?*Guid,
ppSensor: ?*?*ISensor,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetEventSink: fn(
self: *const ISensorManager,
pEvents: ?*ISensorManagerEvents,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RequestPermissions: fn(
self: *const ISensorManager,
hParent: ?HWND,
pSensors: ?*ISensorCollection,
fModal: 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 ISensorManager_GetSensorsByCategory(self: *const T, sensorCategory: ?*Guid, ppSensorsFound: ?*?*ISensorCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const ISensorManager.VTable, self.vtable).GetSensorsByCategory(@ptrCast(*const ISensorManager, self), sensorCategory, ppSensorsFound);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISensorManager_GetSensorsByType(self: *const T, sensorType: ?*Guid, ppSensorsFound: ?*?*ISensorCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const ISensorManager.VTable, self.vtable).GetSensorsByType(@ptrCast(*const ISensorManager, self), sensorType, ppSensorsFound);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISensorManager_GetSensorByID(self: *const T, sensorID: ?*Guid, ppSensor: ?*?*ISensor) callconv(.Inline) HRESULT {
return @ptrCast(*const ISensorManager.VTable, self.vtable).GetSensorByID(@ptrCast(*const ISensorManager, self), sensorID, ppSensor);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISensorManager_SetEventSink(self: *const T, pEvents: ?*ISensorManagerEvents) callconv(.Inline) HRESULT {
return @ptrCast(*const ISensorManager.VTable, self.vtable).SetEventSink(@ptrCast(*const ISensorManager, self), pEvents);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISensorManager_RequestPermissions(self: *const T, hParent: ?HWND, pSensors: ?*ISensorCollection, fModal: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const ISensorManager.VTable, self.vtable).RequestPermissions(@ptrCast(*const ISensorManager, self), hParent, pSensors, fModal);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_ILocationPermissions_Value = @import("../zig.zig").Guid.initString("d5fb0a7f-e74e-44f5-8e02-4806863a274f");
pub const IID_ILocationPermissions = &IID_ILocationPermissions_Value;
pub const ILocationPermissions = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetGlobalLocationPermission: fn(
self: *const ILocationPermissions,
pfEnabled: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CheckLocationCapability: fn(
self: *const ILocationPermissions,
dwClientThreadId: 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 ILocationPermissions_GetGlobalLocationPermission(self: *const T, pfEnabled: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const ILocationPermissions.VTable, self.vtable).GetGlobalLocationPermission(@ptrCast(*const ILocationPermissions, self), pfEnabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ILocationPermissions_CheckLocationCapability(self: *const T, dwClientThreadId: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ILocationPermissions.VTable, self.vtable).CheckLocationCapability(@ptrCast(*const ILocationPermissions, self), dwClientThreadId);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_ISensorCollection_Value = @import("../zig.zig").Guid.initString("23571e11-e545-4dd8-a337-b89bf44b10df");
pub const IID_ISensorCollection = &IID_ISensorCollection_Value;
pub const ISensorCollection = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetAt: fn(
self: *const ISensorCollection,
ulIndex: u32,
ppSensor: ?*?*ISensor,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCount: fn(
self: *const ISensorCollection,
pCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Add: fn(
self: *const ISensorCollection,
pSensor: ?*ISensor,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Remove: fn(
self: *const ISensorCollection,
pSensor: ?*ISensor,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemoveByID: fn(
self: *const ISensorCollection,
sensorID: ?*Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Clear: fn(
self: *const ISensorCollection,
) 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 ISensorCollection_GetAt(self: *const T, ulIndex: u32, ppSensor: ?*?*ISensor) callconv(.Inline) HRESULT {
return @ptrCast(*const ISensorCollection.VTable, self.vtable).GetAt(@ptrCast(*const ISensorCollection, self), ulIndex, ppSensor);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISensorCollection_GetCount(self: *const T, pCount: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISensorCollection.VTable, self.vtable).GetCount(@ptrCast(*const ISensorCollection, self), pCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISensorCollection_Add(self: *const T, pSensor: ?*ISensor) callconv(.Inline) HRESULT {
return @ptrCast(*const ISensorCollection.VTable, self.vtable).Add(@ptrCast(*const ISensorCollection, self), pSensor);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISensorCollection_Remove(self: *const T, pSensor: ?*ISensor) callconv(.Inline) HRESULT {
return @ptrCast(*const ISensorCollection.VTable, self.vtable).Remove(@ptrCast(*const ISensorCollection, self), pSensor);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISensorCollection_RemoveByID(self: *const T, sensorID: ?*Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const ISensorCollection.VTable, self.vtable).RemoveByID(@ptrCast(*const ISensorCollection, self), sensorID);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISensorCollection_Clear(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ISensorCollection.VTable, self.vtable).Clear(@ptrCast(*const ISensorCollection, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_ISensor_Value = @import("../zig.zig").Guid.initString("5fa08f80-2657-458e-af75-46f73fa6ac5c");
pub const IID_ISensor = &IID_ISensor_Value;
pub const ISensor = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetID: fn(
self: *const ISensor,
pID: ?*Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCategory: fn(
self: *const ISensor,
pSensorCategory: ?*Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetType: fn(
self: *const ISensor,
pSensorType: ?*Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFriendlyName: fn(
self: *const ISensor,
pFriendlyName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetProperty: fn(
self: *const ISensor,
key: ?*const PROPERTYKEY,
pProperty: ?*PROPVARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetProperties: fn(
self: *const ISensor,
pKeys: ?*IPortableDeviceKeyCollection,
ppProperties: ?*?*IPortableDeviceValues,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSupportedDataFields: fn(
self: *const ISensor,
ppDataFields: ?*?*IPortableDeviceKeyCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetProperties: fn(
self: *const ISensor,
pProperties: ?*IPortableDeviceValues,
ppResults: ?*?*IPortableDeviceValues,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SupportsDataField: fn(
self: *const ISensor,
key: ?*const PROPERTYKEY,
pIsSupported: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetState: fn(
self: *const ISensor,
pState: ?*SensorState,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetData: fn(
self: *const ISensor,
ppDataReport: ?*?*ISensorDataReport,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SupportsEvent: fn(
self: *const ISensor,
eventGuid: ?*const Guid,
pIsSupported: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetEventInterest: fn(
self: *const ISensor,
ppValues: ?[*]?*Guid,
pCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetEventInterest: fn(
self: *const ISensor,
pValues: ?[*]Guid,
count: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetEventSink: fn(
self: *const ISensor,
pEvents: ?*ISensorEvents,
) 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 ISensor_GetID(self: *const T, pID: ?*Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const ISensor.VTable, self.vtable).GetID(@ptrCast(*const ISensor, self), pID);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISensor_GetCategory(self: *const T, pSensorCategory: ?*Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const ISensor.VTable, self.vtable).GetCategory(@ptrCast(*const ISensor, self), pSensorCategory);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISensor_GetType(self: *const T, pSensorType: ?*Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const ISensor.VTable, self.vtable).GetType(@ptrCast(*const ISensor, self), pSensorType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISensor_GetFriendlyName(self: *const T, pFriendlyName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ISensor.VTable, self.vtable).GetFriendlyName(@ptrCast(*const ISensor, self), pFriendlyName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISensor_GetProperty(self: *const T, key: ?*const PROPERTYKEY, pProperty: ?*PROPVARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const ISensor.VTable, self.vtable).GetProperty(@ptrCast(*const ISensor, self), key, pProperty);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISensor_GetProperties(self: *const T, pKeys: ?*IPortableDeviceKeyCollection, ppProperties: ?*?*IPortableDeviceValues) callconv(.Inline) HRESULT {
return @ptrCast(*const ISensor.VTable, self.vtable).GetProperties(@ptrCast(*const ISensor, self), pKeys, ppProperties);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISensor_GetSupportedDataFields(self: *const T, ppDataFields: ?*?*IPortableDeviceKeyCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const ISensor.VTable, self.vtable).GetSupportedDataFields(@ptrCast(*const ISensor, self), ppDataFields);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISensor_SetProperties(self: *const T, pProperties: ?*IPortableDeviceValues, ppResults: ?*?*IPortableDeviceValues) callconv(.Inline) HRESULT {
return @ptrCast(*const ISensor.VTable, self.vtable).SetProperties(@ptrCast(*const ISensor, self), pProperties, ppResults);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISensor_SupportsDataField(self: *const T, key: ?*const PROPERTYKEY, pIsSupported: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const ISensor.VTable, self.vtable).SupportsDataField(@ptrCast(*const ISensor, self), key, pIsSupported);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISensor_GetState(self: *const T, pState: ?*SensorState) callconv(.Inline) HRESULT {
return @ptrCast(*const ISensor.VTable, self.vtable).GetState(@ptrCast(*const ISensor, self), pState);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISensor_GetData(self: *const T, ppDataReport: ?*?*ISensorDataReport) callconv(.Inline) HRESULT {
return @ptrCast(*const ISensor.VTable, self.vtable).GetData(@ptrCast(*const ISensor, self), ppDataReport);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISensor_SupportsEvent(self: *const T, eventGuid: ?*const Guid, pIsSupported: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const ISensor.VTable, self.vtable).SupportsEvent(@ptrCast(*const ISensor, self), eventGuid, pIsSupported);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISensor_GetEventInterest(self: *const T, ppValues: ?[*]?*Guid, pCount: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISensor.VTable, self.vtable).GetEventInterest(@ptrCast(*const ISensor, self), ppValues, pCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISensor_SetEventInterest(self: *const T, pValues: ?[*]Guid, count: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISensor.VTable, self.vtable).SetEventInterest(@ptrCast(*const ISensor, self), pValues, count);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISensor_SetEventSink(self: *const T, pEvents: ?*ISensorEvents) callconv(.Inline) HRESULT {
return @ptrCast(*const ISensor.VTable, self.vtable).SetEventSink(@ptrCast(*const ISensor, self), pEvents);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_ISensorDataReport_Value = @import("../zig.zig").Guid.initString("0ab9df9b-c4b5-4796-8898-0470706a2e1d");
pub const IID_ISensorDataReport = &IID_ISensorDataReport_Value;
pub const ISensorDataReport = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetTimestamp: fn(
self: *const ISensorDataReport,
pTimeStamp: ?*SYSTEMTIME,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSensorValue: fn(
self: *const ISensorDataReport,
pKey: ?*const PROPERTYKEY,
pValue: ?*PROPVARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSensorValues: fn(
self: *const ISensorDataReport,
pKeys: ?*IPortableDeviceKeyCollection,
ppValues: ?*?*IPortableDeviceValues,
) 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 ISensorDataReport_GetTimestamp(self: *const T, pTimeStamp: ?*SYSTEMTIME) callconv(.Inline) HRESULT {
return @ptrCast(*const ISensorDataReport.VTable, self.vtable).GetTimestamp(@ptrCast(*const ISensorDataReport, self), pTimeStamp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISensorDataReport_GetSensorValue(self: *const T, pKey: ?*const PROPERTYKEY, pValue: ?*PROPVARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const ISensorDataReport.VTable, self.vtable).GetSensorValue(@ptrCast(*const ISensorDataReport, self), pKey, pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISensorDataReport_GetSensorValues(self: *const T, pKeys: ?*IPortableDeviceKeyCollection, ppValues: ?*?*IPortableDeviceValues) callconv(.Inline) HRESULT {
return @ptrCast(*const ISensorDataReport.VTable, self.vtable).GetSensorValues(@ptrCast(*const ISensorDataReport, self), pKeys, ppValues);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_ISensorManagerEvents_Value = @import("../zig.zig").Guid.initString("9b3b0b86-266a-4aad-b21f-fde5501001b7");
pub const IID_ISensorManagerEvents = &IID_ISensorManagerEvents_Value;
pub const ISensorManagerEvents = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
OnSensorEnter: fn(
self: *const ISensorManagerEvents,
pSensor: ?*ISensor,
state: SensorState,
) 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 ISensorManagerEvents_OnSensorEnter(self: *const T, pSensor: ?*ISensor, state: SensorState) callconv(.Inline) HRESULT {
return @ptrCast(*const ISensorManagerEvents.VTable, self.vtable).OnSensorEnter(@ptrCast(*const ISensorManagerEvents, self), pSensor, state);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_ISensorEvents_Value = @import("../zig.zig").Guid.initString("5d8dcc91-4641-47e7-b7c3-b74f48a6c391");
pub const IID_ISensorEvents = &IID_ISensorEvents_Value;
pub const ISensorEvents = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
OnStateChanged: fn(
self: *const ISensorEvents,
pSensor: ?*ISensor,
state: SensorState,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
OnDataUpdated: fn(
self: *const ISensorEvents,
pSensor: ?*ISensor,
pNewData: ?*ISensorDataReport,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
OnEvent: fn(
self: *const ISensorEvents,
pSensor: ?*ISensor,
eventID: ?*const Guid,
pEventData: ?*IPortableDeviceValues,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
OnLeave: fn(
self: *const ISensorEvents,
ID: ?*Guid,
) 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 ISensorEvents_OnStateChanged(self: *const T, pSensor: ?*ISensor, state: SensorState) callconv(.Inline) HRESULT {
return @ptrCast(*const ISensorEvents.VTable, self.vtable).OnStateChanged(@ptrCast(*const ISensorEvents, self), pSensor, state);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISensorEvents_OnDataUpdated(self: *const T, pSensor: ?*ISensor, pNewData: ?*ISensorDataReport) callconv(.Inline) HRESULT {
return @ptrCast(*const ISensorEvents.VTable, self.vtable).OnDataUpdated(@ptrCast(*const ISensorEvents, self), pSensor, pNewData);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISensorEvents_OnEvent(self: *const T, pSensor: ?*ISensor, eventID: ?*const Guid, pEventData: ?*IPortableDeviceValues) callconv(.Inline) HRESULT {
return @ptrCast(*const ISensorEvents.VTable, self.vtable).OnEvent(@ptrCast(*const ISensorEvents, self), pSensor, eventID, pEventData);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISensorEvents_OnLeave(self: *const T, ID: ?*Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const ISensorEvents.VTable, self.vtable).OnLeave(@ptrCast(*const ISensorEvents, self), ID);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const ACTIVITY_STATE_COUNT = enum(i32) {
t = 8,
};
pub const ActivityStateCount = ACTIVITY_STATE_COUNT.t;
pub const ACTIVITY_STATE = enum(i32) {
Unknown = 1,
Stationary = 2,
Fidgeting = 4,
Walking = 8,
Running = 16,
InVehicle = 32,
Biking = 64,
Idle = 128,
Max = 256,
Force_Dword = -1,
};
pub const ActivityState_Unknown = ACTIVITY_STATE.Unknown;
pub const ActivityState_Stationary = ACTIVITY_STATE.Stationary;
pub const ActivityState_Fidgeting = ACTIVITY_STATE.Fidgeting;
pub const ActivityState_Walking = ACTIVITY_STATE.Walking;
pub const ActivityState_Running = ACTIVITY_STATE.Running;
pub const ActivityState_InVehicle = ACTIVITY_STATE.InVehicle;
pub const ActivityState_Biking = ACTIVITY_STATE.Biking;
pub const ActivityState_Idle = ACTIVITY_STATE.Idle;
pub const ActivityState_Max = ACTIVITY_STATE.Max;
pub const ActivityState_Force_Dword = ACTIVITY_STATE.Force_Dword;
pub const ELEVATION_CHANGE_MODE = enum(i32) {
Unknown = 0,
Elevator = 1,
Stepping = 2,
Max = 3,
Force_Dword = -1,
};
pub const ElevationChangeMode_Unknown = ELEVATION_CHANGE_MODE.Unknown;
pub const ElevationChangeMode_Elevator = ELEVATION_CHANGE_MODE.Elevator;
pub const ElevationChangeMode_Stepping = ELEVATION_CHANGE_MODE.Stepping;
pub const ElevationChangeMode_Max = ELEVATION_CHANGE_MODE.Max;
pub const ElevationChangeMode_Force_Dword = ELEVATION_CHANGE_MODE.Force_Dword;
pub const MAGNETOMETER_ACCURACY = enum(i32) {
Unknown = 0,
Unreliable = 1,
Approximate = 2,
High = 3,
};
pub const MagnetometerAccuracy_Unknown = MAGNETOMETER_ACCURACY.Unknown;
pub const MagnetometerAccuracy_Unreliable = MAGNETOMETER_ACCURACY.Unreliable;
pub const MagnetometerAccuracy_Approximate = MAGNETOMETER_ACCURACY.Approximate;
pub const MagnetometerAccuracy_High = MAGNETOMETER_ACCURACY.High;
pub const PEDOMETER_STEP_TYPE_COUNT = enum(i32) {
t = 3,
};
pub const PedometerStepTypeCount = PEDOMETER_STEP_TYPE_COUNT.t;
pub const PEDOMETER_STEP_TYPE = enum(i32) {
Unknown = 1,
Walking = 2,
Running = 4,
Max = 8,
Force_Dword = -1,
};
pub const PedometerStepType_Unknown = PEDOMETER_STEP_TYPE.Unknown;
pub const PedometerStepType_Walking = PEDOMETER_STEP_TYPE.Walking;
pub const PedometerStepType_Running = PEDOMETER_STEP_TYPE.Running;
pub const PedometerStepType_Max = PEDOMETER_STEP_TYPE.Max;
pub const PedometerStepType_Force_Dword = PEDOMETER_STEP_TYPE.Force_Dword;
pub const PROXIMITY_TYPE = enum(i32) {
ObjectProximity = 0,
HumanProximity = 1,
Force_Dword = -1,
};
pub const ProximityType_ObjectProximity = PROXIMITY_TYPE.ObjectProximity;
pub const ProximityType_HumanProximity = PROXIMITY_TYPE.HumanProximity;
pub const ProximityType_Force_Dword = PROXIMITY_TYPE.Force_Dword;
pub const HUMAN_PRESENCE_DETECTION_TYPE_COUNT = enum(i32) {
t = 4,
};
pub const HumanPresenceDetectionTypeCount = HUMAN_PRESENCE_DETECTION_TYPE_COUNT.t;
pub const HUMAN_PRESENCE_DETECTION_TYPE = enum(i32) {
VendorDefinedNonBiometric = 1,
VendorDefinedBiometric = 2,
FacialBiometric = 4,
AudioBiometric = 8,
Force_Dword = -1,
};
pub const HumanPresenceDetectionType_VendorDefinedNonBiometric = HUMAN_PRESENCE_DETECTION_TYPE.VendorDefinedNonBiometric;
pub const HumanPresenceDetectionType_VendorDefinedBiometric = HUMAN_PRESENCE_DETECTION_TYPE.VendorDefinedBiometric;
pub const HumanPresenceDetectionType_FacialBiometric = HUMAN_PRESENCE_DETECTION_TYPE.FacialBiometric;
pub const HumanPresenceDetectionType_AudioBiometric = HUMAN_PRESENCE_DETECTION_TYPE.AudioBiometric;
pub const HumanPresenceDetectionType_Force_Dword = HUMAN_PRESENCE_DETECTION_TYPE.Force_Dword;
pub const SIMPLE_DEVICE_ORIENTATION = enum(i32) {
NotRotated = 0,
Rotated90DegreesCounterclockwise = 1,
Rotated180DegreesCounterclockwise = 2,
Rotated270DegreesCounterclockwise = 3,
Faceup = 4,
Facedown = 5,
};
pub const SimpleDeviceOrientation_NotRotated = SIMPLE_DEVICE_ORIENTATION.NotRotated;
pub const SimpleDeviceOrientation_Rotated90DegreesCounterclockwise = SIMPLE_DEVICE_ORIENTATION.Rotated90DegreesCounterclockwise;
pub const SimpleDeviceOrientation_Rotated180DegreesCounterclockwise = SIMPLE_DEVICE_ORIENTATION.Rotated180DegreesCounterclockwise;
pub const SimpleDeviceOrientation_Rotated270DegreesCounterclockwise = SIMPLE_DEVICE_ORIENTATION.Rotated270DegreesCounterclockwise;
pub const SimpleDeviceOrientation_Faceup = SIMPLE_DEVICE_ORIENTATION.Faceup;
pub const SimpleDeviceOrientation_Facedown = SIMPLE_DEVICE_ORIENTATION.Facedown;
pub const SENSOR_STATE = enum(i32) {
Initializing = 0,
Idle = 1,
Active = 2,
Error = 3,
};
pub const SensorState_Initializing = SENSOR_STATE.Initializing;
pub const SensorState_Idle = SENSOR_STATE.Idle;
pub const SensorState_Active = SENSOR_STATE.Active;
pub const SensorState_Error = SENSOR_STATE.Error;
pub const SENSOR_CONNECTION_TYPES = enum(i32) {
Integrated = 0,
Attached = 1,
External = 2,
};
pub const SensorConnectionType_Integrated = SENSOR_CONNECTION_TYPES.Integrated;
pub const SensorConnectionType_Attached = SENSOR_CONNECTION_TYPES.Attached;
pub const SensorConnectionType_External = SENSOR_CONNECTION_TYPES.External;
pub const SENSOR_VALUE_PAIR = extern struct {
Key: PROPERTYKEY,
Value: PROPVARIANT,
};
pub const SENSOR_COLLECTION_LIST = extern struct {
AllocatedSizeInBytes: u32,
Count: u32,
List: [1]SENSOR_VALUE_PAIR,
};
pub const SENSOR_PROPERTY_LIST = extern struct {
AllocatedSizeInBytes: u32,
Count: u32,
List: [1]PROPERTYKEY,
};
pub const VEC3D = extern struct {
X: f32,
Y: f32,
Z: f32,
};
pub const MATRIX3X3 = extern struct {
Anonymous: extern union {
Anonymous1: extern struct {
A11: f32,
A12: f32,
A13: f32,
A21: f32,
A22: f32,
A23: f32,
A31: f32,
A32: f32,
A33: f32,
},
Anonymous2: extern struct {
V1: VEC3D,
V2: VEC3D,
V3: VEC3D,
},
M: [9]f32,
},
};
pub const QUATERNION = extern struct {
X: f32,
Y: f32,
Z: f32,
W: f32,
};
pub const AXIS = enum(i32) {
X = 0,
Y = 1,
Z = 2,
MAX = 3,
};
pub const AXIS_X = AXIS.X;
pub const AXIS_Y = AXIS.Y;
pub const AXIS_Z = AXIS.Z;
pub const AXIS_MAX = AXIS.MAX;
//--------------------------------------------------------------------------------
// Section: Functions (40)
//--------------------------------------------------------------------------------
pub extern "SensorsUtilsV2" fn GetPerformanceTime(
TimeMs: ?*u32,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "SensorsUtilsV2" fn InitPropVariantFromFloat(
fltVal: f32,
ppropvar: ?*PROPVARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "SensorsUtilsV2" fn PropKeyFindKeyGetPropVariant(
pList: ?*const SENSOR_COLLECTION_LIST,
pKey: ?*const PROPERTYKEY,
TypeCheck: BOOLEAN,
pValue: ?*PROPVARIANT,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "SensorsUtilsV2" fn PropKeyFindKeySetPropVariant(
pList: ?*SENSOR_COLLECTION_LIST,
pKey: ?*const PROPERTYKEY,
TypeCheck: BOOLEAN,
pValue: ?*PROPVARIANT,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "SensorsUtilsV2" fn PropKeyFindKeyGetFileTime(
pList: ?*const SENSOR_COLLECTION_LIST,
pKey: ?*const PROPERTYKEY,
pRetValue: ?*FILETIME,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "SensorsUtilsV2" fn PropKeyFindKeyGetGuid(
pList: ?*const SENSOR_COLLECTION_LIST,
pKey: ?*const PROPERTYKEY,
pRetValue: ?*Guid,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "SensorsUtilsV2" fn PropKeyFindKeyGetBool(
pList: ?*const SENSOR_COLLECTION_LIST,
pKey: ?*const PROPERTYKEY,
pRetValue: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "SensorsUtilsV2" fn PropKeyFindKeyGetUlong(
pList: ?*const SENSOR_COLLECTION_LIST,
pKey: ?*const PROPERTYKEY,
pRetValue: ?*u32,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "SensorsUtilsV2" fn PropKeyFindKeyGetUshort(
pList: ?*const SENSOR_COLLECTION_LIST,
pKey: ?*const PROPERTYKEY,
pRetValue: ?*u16,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "SensorsUtilsV2" fn PropKeyFindKeyGetFloat(
pList: ?*const SENSOR_COLLECTION_LIST,
pKey: ?*const PROPERTYKEY,
pRetValue: ?*f32,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "SensorsUtilsV2" fn PropKeyFindKeyGetDouble(
pList: ?*const SENSOR_COLLECTION_LIST,
pKey: ?*const PROPERTYKEY,
pRetValue: ?*f64,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "SensorsUtilsV2" fn PropKeyFindKeyGetInt32(
pList: ?*const SENSOR_COLLECTION_LIST,
pKey: ?*const PROPERTYKEY,
pRetValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "SensorsUtilsV2" fn PropKeyFindKeyGetInt64(
pList: ?*const SENSOR_COLLECTION_LIST,
pKey: ?*const PROPERTYKEY,
pRetValue: ?*i64,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "SensorsUtilsV2" fn PropKeyFindKeyGetNthUlong(
pList: ?*const SENSOR_COLLECTION_LIST,
pKey: ?*const PROPERTYKEY,
Occurrence: u32,
pRetValue: ?*u32,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "SensorsUtilsV2" fn PropKeyFindKeyGetNthUshort(
pList: ?*const SENSOR_COLLECTION_LIST,
pKey: ?*const PROPERTYKEY,
Occurrence: u32,
pRetValue: ?*u16,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "SensorsUtilsV2" fn PropKeyFindKeyGetNthInt64(
pList: ?*const SENSOR_COLLECTION_LIST,
pKey: ?*const PROPERTYKEY,
Occurrence: u32,
pRetValue: ?*i64,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "SensorsUtilsV2" fn IsKeyPresentInPropertyList(
pList: ?*SENSOR_PROPERTY_LIST,
pKey: ?*const PROPERTYKEY,
) callconv(@import("std").os.windows.WINAPI) BOOLEAN;
pub extern "SensorsUtilsV2" fn IsKeyPresentInCollectionList(
pList: ?*SENSOR_COLLECTION_LIST,
pKey: ?*const PROPERTYKEY,
) callconv(@import("std").os.windows.WINAPI) BOOLEAN;
pub extern "SensorsUtilsV2" fn IsCollectionListSame(
ListA: ?*const SENSOR_COLLECTION_LIST,
ListB: ?*const SENSOR_COLLECTION_LIST,
) callconv(@import("std").os.windows.WINAPI) BOOLEAN;
pub extern "SensorsUtilsV2" fn PropVariantGetInformation(
PropVariantValue: ?*const PROPVARIANT,
PropVariantOffset: ?*u32,
PropVariantSize: ?*u32,
PropVariantPointer: ?*?*anyopaque,
RemappedType: ?*u32,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "SensorsUtilsV2" fn PropertiesListCopy(
Target: ?*SENSOR_PROPERTY_LIST,
Source: ?*const SENSOR_PROPERTY_LIST,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "SensorsUtilsV2" fn PropertiesListGetFillableCount(
BufferSizeBytes: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "SensorsUtilsV2" fn CollectionsListGetMarshalledSize(
Collection: ?*const SENSOR_COLLECTION_LIST,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "SensorsUtilsV2" fn CollectionsListCopyAndMarshall(
Target: ?*SENSOR_COLLECTION_LIST,
Source: ?*const SENSOR_COLLECTION_LIST,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "SensorsUtilsV2" fn CollectionsListMarshall(
Target: ?*SENSOR_COLLECTION_LIST,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "SensorsUtilsV2" fn CollectionsListGetMarshalledSizeWithoutSerialization(
Collection: ?*const SENSOR_COLLECTION_LIST,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "SensorsUtilsV2" fn CollectionsListUpdateMarshalledPointer(
Collection: ?*SENSOR_COLLECTION_LIST,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "SensorsUtilsV2" fn SerializationBufferAllocate(
SizeInBytes: u32,
pBuffer: ?*?*u8,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "SensorsUtilsV2" fn SerializationBufferFree(
Buffer: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "SensorsUtilsV2" fn CollectionsListGetSerializedSize(
Collection: ?*const SENSOR_COLLECTION_LIST,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "SensorsUtilsV2" fn CollectionsListSerializeToBuffer(
SourceCollection: ?*const SENSOR_COLLECTION_LIST,
TargetBufferSizeInBytes: u32,
// TODO: what to do with BytesParamIndex 1?
TargetBuffer: ?*u8,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "SensorsUtilsV2" fn CollectionsListAllocateBufferAndSerialize(
SourceCollection: ?*const SENSOR_COLLECTION_LIST,
pTargetBufferSizeInBytes: ?*u32,
pTargetBuffer: ?*?*u8,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "SensorsUtilsV2" fn CollectionsListDeserializeFromBuffer(
SourceBufferSizeInBytes: u32,
// TODO: what to do with BytesParamIndex 0?
SourceBuffer: ?*const u8,
TargetCollection: ?*SENSOR_COLLECTION_LIST,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "SensorsUtilsV2" fn SensorCollectionGetAt(
Index: u32,
pSensorsList: ?*SENSOR_COLLECTION_LIST,
pKey: ?*PROPERTYKEY,
pValue: ?*PROPVARIANT,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "SensorsUtilsV2" fn CollectionsListGetFillableCount(
BufferSizeBytes: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "SensorsUtilsV2" fn EvaluateActivityThresholds(
newSample: ?*SENSOR_COLLECTION_LIST,
oldSample: ?*SENSOR_COLLECTION_LIST,
thresholds: ?*SENSOR_COLLECTION_LIST,
) callconv(@import("std").os.windows.WINAPI) BOOLEAN;
pub extern "SensorsUtilsV2" fn CollectionsListSortSubscribedActivitiesByConfidence(
thresholds: ?*SENSOR_COLLECTION_LIST,
pCollection: ?*SENSOR_COLLECTION_LIST,
) callconv(@import("std").os.windows.WINAPI) NTSTATUS;
pub extern "SensorsUtilsV2" fn InitPropVariantFromCLSIDArray(
members: [*]Guid,
size: u32,
ppropvar: ?*PROPVARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "SensorsUtilsV2" fn IsSensorSubscribed(
subscriptionList: ?*SENSOR_COLLECTION_LIST,
currentType: Guid,
) callconv(@import("std").os.windows.WINAPI) BOOLEAN;
pub extern "SensorsUtilsV2" fn IsGUIDPresentInList(
guidArray: [*]const Guid,
arrayLength: u32,
guidElem: ?*const Guid,
) callconv(@import("std").os.windows.WINAPI) BOOLEAN;
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (0)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../zig.zig").unicode_mode) {
.ansi => struct {
},
.wide => struct {
},
.unspecified => if (@import("builtin").is_test) struct {
} else struct {
},
};
//--------------------------------------------------------------------------------
// Section: Imports (14)
//--------------------------------------------------------------------------------
const Guid = @import("../zig.zig").Guid;
const BOOL = @import("../foundation.zig").BOOL;
const BOOLEAN = @import("../foundation.zig").BOOLEAN;
const BSTR = @import("../foundation.zig").BSTR;
const FILETIME = @import("../foundation.zig").FILETIME;
const HRESULT = @import("../foundation.zig").HRESULT;
const HWND = @import("../foundation.zig").HWND;
const IPortableDeviceKeyCollection = @import("../devices/portable_devices.zig").IPortableDeviceKeyCollection;
const IPortableDeviceValues = @import("../devices/portable_devices.zig").IPortableDeviceValues;
const IUnknown = @import("../system/com.zig").IUnknown;
const NTSTATUS = @import("../foundation.zig").NTSTATUS;
const PROPERTYKEY = @import("../ui/shell/properties_system.zig").PROPERTYKEY;
const PROPVARIANT = @import("../system/com/structured_storage.zig").PROPVARIANT;
const SYSTEMTIME = @import("../foundation.zig").SYSTEMTIME;
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/devices/sensors.zig |
const root = @import("root");
const std = @import("std");
const testing = std.testing;
const assert = std.debug.assert;
pub usingnamespace @import("common.zig");
const nvic_priority_bits = if (@hasDecl(root, "nvic_priority_bits")) root.nvic_priority_bits else 4;
/// ARM DUI 0646C Table 4-17
const SCB_AIRCR_PRIGROUP_Pos: u32 = 8;
const SCB_AIRCR_PRIGROUP_Mask: u32 = 0x7 << SCB_AIRCR_PRIGROUP_Pos;
const SCB_AIRCR_VECTKEYSTAT_Pos: u32 = 16;
const SCB_AIRCR_VECTKEYSTAT_Mask: u32 = 0xffff << SCB_AIRCR_VECTKEYSTAT_Pos;
const SCB_AIRCR_VECTKEY: u32 = 0x5FA << SCB_AIRCR_VECTKEYSTAT_Pos;
const SCB_AIRCR_SYSRESETREQ_Pos: u32 = 2;
const SCB_AIRCR_SYSRESETREQ_Mask: u32 = 0x1 << SCB_AIRCR_SYSRESETREQ_Pos;
pub const FloatingPoint = struct {
/// ARM DDI 0403E.b Section B3.3.20
pub fn enable() void {
// Set CP10 and CP11 Full Access
SCB.CPACR |= @as(u32, 0xF) << 20;
}
test "Semantic Analyze" {
std.meta.refAllDecls(@This());
}
};
pub fn systemReset() noreturn {
dsb();
SCB.AIRCR = SCB_AIRCR_VECTKEY |
(SCB.AIRCR & SCB_AIRCR_PRIGROUP_Mask) |
SCB_AIRCR_SYSRESETREQ_Mask;
dsb();
while (true) {}
}
pub const Interrupts = struct {
// TODO: arch ref manual says irq_number can go up to 495
pub fn enable(irq_number: u8) void {
const irq_bit = @as(u32, 1) << @truncate(u5, irq_number);
NVIC.ISER[irq_number >> 5] = irq_bit;
}
pub fn getEnabled(irq_number: u8) bool {
const irq_bit = @as(u32, 1) << @truncate(u5, irq_number);
return if ((NVIC.ISER[irq_number >> 5] & irq_bit) == 0) false else true;
}
pub fn disable(irq_number: u8) void {
const irq_bit = @as(u32, 1) << @truncate(u5, irq_number);
NVIC.ICER[irq_number >> 5] = irq_bit;
dsb();
isb();
}
pub fn getPending(irq_number: u8) bool {
const irq_bit = @as(u32, 1) << @truncate(u5, irq_number);
return if ((NVIC.ISPR[irq_number >> 5] & irq_bit) == 0) false else true;
}
pub fn setPending(irq_number: u8) void {
const irq_bit = @as(u32, 1) << @truncate(u5, irq_number);
NVIC.ISPR[irq_number >> 5] = irq_bit;
}
pub fn clearPending(irq_number: u8) void {
const irq_bit = @as(u32, 1) << @truncate(u5, irq_number);
NVIC.ICPR[irq_number >> 5] = irq_bit;
}
pub fn getActive(irq_number: u8) bool {
const irq_bit = @as(u32, 1) << @truncate(u5, irq_number);
return if ((NVIC.IABR[irq_number >> 5] & irq_bit) == 0) false else true;
}
pub fn setPriority(irq_number: u8, priority: u8) void {
const prio_shift = 8 - nvic_priority_bits;
if (irq_number >= NVIC.IPR.len) return;
NVIC.IPR[irq_number] = priority << prio_shift;
}
pub fn getPriority(irq_number: u8, priority: u8) u8 {
const prio_shift = 8 - nvic_priority_bits;
assert(irq_number >= NVIC.IPR.len);
return (NVIC.IPR[irq_number] >> prio_shift);
}
test "Semantic Analyze" {
std.meta.refAllDecls(@This());
}
};
pub const SysTick = struct {
pub const CSR_COUNTFLAG_Pos = 16;
pub const CSR_COUNTFLAG_Mask = 1 << CSR_COUNTFLAG_Pos;
pub const CSR_CLKSOURCE_Pos = 2;
pub const CSR_CLKSOURCE_Mask = 1 << CSR_CLKSOURCE_Pos;
pub const CSR_TICKINT_Pos = 1;
pub const CSR_TICKINT_Mask = 1 << CSR_TICKINT_Pos;
pub const CSR_ENABLE_Mask = 1;
pub const LOAD_RELOAD_Mask = 0xFFFFFF;
pub const VAL_CURRENT_Mask = 0xFFFFFF;
pub const CALIB_NOREF_Pos = 31;
pub const CALIB_NOREF_Mask = 1 << CALIB_NOREF_Pos;
pub const CALIB_SKEW_Pos = 30;
pub const CALIB_SKEW_Mask = 1 << CALIB_SKEW_Pos;
pub const CALIB_TENMS_Mask = 0xFFFFFF;
pub const ClockSource = enum(u1) {
External,
Processor,
};
pub fn config(clock: ClockSource, interrupt: bool, enable: bool, reload_value: u24) void {
SYSTICK.RVR = reload_value;
Exceptions.SysTickHandler.setPriority((1 << nvic_priority_bits) - 1);
SYSTICK.CVR = 0;
var setting: u32 = 0;
if (clock == .Processor) setting |= CSR_CLKSOURCE_Mask;
if (interrupt) setting |= CSR_TICKINT_Mask;
if (enable) setting |= CSR_ENABLE_Mask;
SYSTICK.CSR = setting;
}
pub fn getTenMsCalibratedTicks() u24 {
return @truncate(u24, SYSTICK.CALIB);
}
test "Semantic Analyze" {
std.meta.refAllDecls(@This());
}
};
pub const PriorityBitsGrouping = enum(u3) {
GroupPriorityBits_7,
GroupPriorityBits_6,
GroupPriorityBits_5,
GroupPriorityBits_4,
GroupPriorityBits_3,
GroupPriorityBits_2,
GroupPriorityBits_1,
GroupPriorityBits_0,
const Self = @This();
pub fn set(priority_group: Self) void {
const iarcr = SCB.AIRCR & ~@as(u32, SCB_AIRCR_VECTKEYSTAT_Mask | SCB_AIRCR_PRIGROUP_Mask);
SCB.AIRCR = iarcr |
SCB_AIRCR_VECTKEY |
@as(u32, @enumToInt(priority_group)) << SCB_AIRCR_PRIGROUP_Pos;
}
pub fn get() Self {
return @intToEnum(PriorityBitsGrouping, @truncate(@TagType(PriorityBitsGrouping), SCB.AIRCR >> SCB_AIRCR_PRIGROUP_Pos));
}
test "Semantic Analyze" {
std.meta.refAllDecls(@This());
}
};
pub const Exceptions = enum(u4) {
MemManageHandler = 4,
BusHandler = 5,
UsageFaultHandler = 6,
SystemHandler7 = 7,
SystemHandler8 = 8,
SystemHandler9 = 9,
SystemHandler10 = 10,
SVCallHandler = 11,
DebugMonitorHandler = 12,
SystemHandler13 = 13,
PendSVHandler = 14,
SysTickHandler = 15,
const Self = @This();
pub fn setPriority(exception: Self, priority: u8) void {
const prio_shift = 8 - nvic_priority_bits;
const exception_number = @enumToInt(exception);
SCB.SHPR[exception_number - 4] = priority << prio_shift;
}
pub fn getPriority(exception: Self, priority: u8) u8 {
const prio_shift = 8 - nvic_priority_bits;
const exception_number = @enumToInt(exception);
return SCB.SHPR[exception_number - 4] >> prio_shift;
}
test "Semantic Analyze" {
std.meta.refAllDecls(@This());
}
};
pub const ICache = struct {
const SCB_CCR_IC_Mask: u32 = 1 << 17;
pub fn invalidate() void {
dsb();
isb();
CACHE_MAINTENANCE.ICIALLU = 0;
dsb();
isb();
}
pub fn enable() void {
invalidate();
SCB.CCR |= SCB_CCR_IC_Mask;
dsb();
isb();
}
pub fn disable() void {
dsb();
isb();
SCB.CCR &= ~(SCB_CCR_IC_Mask);
CACHE_MAINTENANCE.ICIALLU = 0;
dsb();
isb();
}
test "Semantic Analyze" {
std.meta.refAllDecls(@This());
}
};
pub const DCache = struct {
const Associativity = struct {
sets: u32,
ways: u32,
};
fn getAssociativity() Associativity {
const SCB_CCSIDR_NUMSETS_Pos = (13);
const SCB_CCSIDR_NUMSETS_Mask = (0x7FFF << SCB_CCSIDR_NUMSETS_Pos);
const SCB_CCSIDR_ASSOCIATIVITY_Pos = (3);
const SCB_CCSIDR_ASSOCIATIVITY_Mask = (0x3FF << SCB_CCSIDR_ASSOCIATIVITY_Pos);
const ccsidr = SCB.CCSIDR;
return .{
.sets = (ccsidr & SCB_CCSIDR_NUMSETS_Mask) >> SCB_CCSIDR_NUMSETS_Pos,
.ways = (ccsidr & SCB_CCSIDR_ASSOCIATIVITY_Mask) >> SCB_CCSIDR_ASSOCIATIVITY_Pos,
};
}
fn invalidateSetsAndWays() void {
const SCB_DCISW_WAY_Pos = (30);
const SCB_DCISW_WAY_Mask = (3 << SCB_DCISW_WAY_Pos);
const SCB_DCISW_SET_Pos = (5);
const SCB_DCISW_SET_Mask = (0x1FF << SCB_DCISW_SET_Pos);
var assoc = getAssociativity();
while (true) {
var ways_inner = assoc.ways;
while (true) {
CACHE_MAINTENANCE.DCISW = ((assoc.sets << SCB_DCISW_SET_Pos) & SCB_DCISW_SET_Mask) |
((ways_inner << SCB_DCISW_WAY_Pos) & SCB_DCISW_WAY_Mask);
if (ways_inner == 0) break;
ways_inner -= 1;
}
if (assoc.sets == 0) break;
assoc.sets -= 1;
}
}
fn cleanSetsAndWays() void {
const SCB_DCCSW_WAY_Pos = (30);
const SCB_DCCSW_WAY_Mask = (3 << SCB_DCCSW_WAY_Pos);
const SCB_DCCSW_SET_Pos = (5);
const SCB_DCCSW_SET_Mask = (0x1FF << SCB_DCCSW_SET_Pos);
var assoc = getAssociativity();
while (true) {
var ways_inner = assoc.ways;
while (true) {
CACHE_MAINTENANCE.DCCSW = ((assoc.sets << SCB_DCCSW_SET_Pos) & SCB_DCCSW_SET_Mask) |
((ways_inner << SCB_DCCSW_WAY_Pos) & SCB_DCCSW_WAY_Mask);
if (ways_inner == 0) break;
ways_inner -= 1;
}
if (assoc.sets == 0) break;
assoc.sets -= 1;
}
}
pub fn invalidate() void {
SCB.CSSELR = 0;
dsb();
invalidateSetsAndWays();
dsb();
isb();
}
pub fn enable() void {
const SCB_CCR_DC_Pos = 16;
const SCB_CCR_DC_Mask = (1 << SCB_CCR_DC_Pos);
SCB.CSSELR = 0;
dsb();
invalidateSetsAndWays();
dsb();
SCB.CCR |= SCB_CCR_DC_Mask;
dsb();
isb();
}
pub fn disable() void {
const SCB_CCR_DC_Pos = 16;
const SCB_CCR_DC_Mask: u32 = (1 << SCB_CCR_DC_Pos);
SCB.CSSELR = 0;
dsb();
SCB.CCR &= ~SCB_CCR_DC_Mask;
dsb();
invalidateSetsAndWays();
dsb();
isb();
}
pub fn clean() void {
SCB.CSSELR = 0;
dsb();
cleanSetsAndWays();
dsb();
isb();
}
pub fn invalidateByAddress(addr: *allowzero u32, len: i32) void {
const line_size = 32;
var data_size = len;
var data_addr = @ptrToInt(addr);
dsb();
while (data_size > 0) {
CACHE_MAINTENANCE.DCIMVAC = data_addr;
data_addr +%= line_size;
data_size -= line_size;
}
dsb();
isb();
}
pub fn cleanByAddress(addr: *allowzero u32, len: i32) void {
const line_size = 32;
var data_size = len;
var data_addr = @ptrToInt(addr);
dsb();
while (data_size > 0) {
CACHE_MAINTENANCE.DCCMVAC = data_addr;
data_addr +%= line_size;
data_size -= line_size;
}
dsb();
isb();
}
pub fn cleanInvalidateByAddress(addr: *allowzero u32, len: i32) void {
invalidateByAddress(addr, len);
}
test "Semantic Analyze" {
std.meta.refAllDecls(@This());
}
};
/// ARM DDI 0403E.b Section B3.2
/// Table B3-3
const SCS_BASE = 0xE000E000;
const SYSTICK_BASE = SCS_BASE + 0x010;
const NVIC_BASE = SCS_BASE + 0x100;
const SCB_BASE = SCS_BASE + 0xD00;
const MPU_BASE = SCS_BASE + 0xD90;
const DBC_BASE = SCS_BASE + 0xDF0;
const CACHE_MAINTENANCE_BASE = SCS_BASE + 0xF50;
const MCU_ID_BASE = SCS_BASE + 0xFD0;
/// ARM DDI 0403E.b Section B3.2
/// Table B3-6
const STIR_BASE = SCS_BASE + 0xF00;
/// ARM DDI 0403E.b Section B3.2
/// Table B3-5
const FPU_BASE = SCS_BASE + 0xF34;
/// ARM DDI 0403E.b Section C1.1
/// Table C1-1
const DEBUG_BASE = 0xE0000000;
const ITM_BASE = DEBUG_BASE + 0x0000;
const DWT_BASE = DEBUG_BASE + 0x1000;
const FPB_BASE = DEBUG_BASE + 0x2000;
const TPIU_BASE = DEBUG_BASE + 0x40000;
const ETM_BASE = DEBUG_BASE + 0x41000; // TODO
const ROM_TABLE_BASE = DEBUG_BASE + 0xFF000;
pub const SCS = @intToPtr(*align(4) volatile SCS_Regs, SCS_BASE);
pub const SYSTICK = @intToPtr(*align(4) volatile SYSTICK_Regs, SYSTICK_BASE);
pub const NVIC = @intToPtr(*align(4) volatile NVIC_Regs, NVIC_BASE);
pub const SCB = @intToPtr(*align(4) volatile SCB_Regs, SCB_BASE);
pub const MPU = @intToPtr(*align(4) volatile MPU_Regs, MPU_BASE);
pub const DBC = @intToPtr(*align(4) volatile DBC_Regs, DBC_BASE);
pub const CACHE_MAINTENANCE = @intToPtr(*align(4) volatile CACHE_MAINTENANCE_Regs, CACHE_MAINTENANCE_BASE);
pub const MCU_ID = @intToPtr(*align(4) volatile MCU_ID_Regs, MCU_ID_BASE);
pub const ITM = @intToPtr(*align(4) volatile ITM_Regs, ITM_BASE);
pub const DWT = @intToPtr(*align(4) volatile DWT_Regs, DWT_BASE);
pub const FPB = @intToPtr(*align(4) volatile FPB_Regs, FPB_BASE);
pub const TPIU = @intToPtr(*align(4) volatile TPIU_Regs, TPIU_BASE);
pub const FPU = @intToPtr(*align(4) volatile FPU_Regs, FPU_BASE);
/// ARM DDI 0403E.b Section B3.2
/// Table B3-4
/// and
/// ARM DDI 0403E.b Section B4.1
/// Table B4-1 For CPUID
pub const SCB_Regs = extern struct {
CPUID: u32,
ICSR: u32,
VTOR: u32,
AIRCR: u32,
SCR: u32,
CCR: u32,
SHPR: [12]u8,
SHCSR: u32,
CFSR: u32,
HFSR: u32,
DFSR: u32,
MMFAR: u32,
BFAR: u32,
AFSR: u32,
// CPUID
ID_PFR: [2]u32,
ID_DFR: u32,
ID_AFR: u32,
ID_MMFR: [4]u32,
ID_ISAR: [5]u32,
padding0: [1]u32, // ID_ISAR5 reserved
CLIDR: u32,
CTR: u32,
CCSIDR: u32,
CSSELR: u32,
// end CPUID
CPACR: u32,
padding1: [1]u32,
};
/// ARM DDI 0403E.b Section B3.2
/// Table B3-6
pub const SCS_Regs = extern struct {
padding0: [1]u32,
ICTR: u32,
ACTLR: u32,
padding1: [1]u32,
};
/// ARM DDI 0403E.b Section C1.11
/// Table C1-23
pub const FPB_Regs = extern struct {
CTRL: u32,
REMAP: u32,
COMP: [142]u32,
};
/// ARM DDI 0403E.b Section B3.3
/// Table B3-7
pub const SYSTICK_Regs = extern struct {
CSR: u32,
RVR: u32,
CVR: u32,
CALIB: u32,
padding0: [(0x100 - 0x20) / 4]u32,
};
/// ARM DDI 0403E.b Section B3.4
/// Table B3-8
pub const NVIC_Regs = extern struct {
ISER: [16]u32,
padding0: [16]u32,
ICER: [16]u32,
RSERVED1: [16]u32,
ISPR: [16]u32,
padding2: [16]u32,
ICPR: [16]u32,
padding3: [16]u32,
IABR: [16]u32,
padding4: [(0x400 - 0x340) / 4]u32,
IPR: [496]u8,
padding5: [STIR_BASE - 0xE000E5F0]u8,
STIR: u32,
};
/// ARM DDI 0403E.b Section C1.7.3
const ItmStimPort = packed union {
FIFOREADY: u1,
asByte: u8,
asHword: u16,
asWord: u32,
};
/// ARM DDI 0403E.b Section C1.7
/// Table C1-11
pub const ITM_Regs = extern struct {
ITM_STIM: [256]ItmStimPort,
padding0: [0xE00 - 0x400]u8,
ITM_TER: [8]u32,
padding1: [0xE40 - 0xE20]u8,
ITM_TPR: u32,
padding2: [60]u8,
ITM_TCR: u32,
};
/// ARM DDI 0403E.b Section C1.8
/// Table C1-21
const DwtComparatorControl = packed struct {
COMP: u32,
MASK: u32,
FUNCTION: u32,
padding0: u32,
};
/// ARM DDI 0403E.b Section C1.8.7
const DWT_CTRL_NUMCOMP_Pos = 28;
const DWT_CTRL_NUMCOMP_Width = 31 - 28 + 1;
const DWT_CTRL_NUMCOMP_Mask = bitmask(u32, DWT_CTRL_NUMCOMP_Width) << DWT_CTRL_NUMCOMP_Pos;
/// ARM DDI 0403E.b Section C1.8
/// Table C1-21
pub const DWT_Regs = extern struct {
CTRL: u32,
CYCCNT: u32,
CPICNT: u32,
EXCCNT: u32,
SLEEPCNT: u32,
LSUCNT: u32,
FOLDCNT: u32,
PCSR: u32,
COMP: [DWT_CTRL_NUMCOMP_Mask >> DWT_CTRL_NUMCOMP_Pos]DwtComparatorControl,
};
/// ARM DDI 0403E.b Section C1.10
/// Table C1-22
pub const TPIU_Regs = extern struct {
SSPSR: u32,
CSPSR: u32,
padding0: [0x10 - 0x08]u8,
ACPR: u32,
padding1: [0xF0 - 0x14]u8,
SPPR: u32,
padding2: [0xFC8 - 0xF4]u8,
TYPE: u32,
};
/// ARM DDI 0403E.b Section C1.6
/// Table C1-10
pub const DBC_Regs = extern struct {
DHCSR: u32,
DCRSR: u32,
DCRDR: u32,
DEMCR: u32,
padding0: [0xF00 - 0xE00]u8,
};
/// ARM DDI 0403E.b Section B3.5
/// Table B3-11
pub const MPU_Regs = extern struct {
TYPE: u32,
CTRL: u32,
RNR: u32,
RBAR: u32,
RASR: u32,
RBAR_A1: u32,
RASR_A1: u32,
RBAR_A2: u32,
RASR_A2: u32,
RBAR_A3: u32,
RASR_A3: u32,
padding0: [0xDF0 - 0xDBC]u8,
};
/// ARM DDI 0403E.b Section B3.2
/// Table B3-5
pub const FPU_Regs = extern struct {
FPCCR: u32,
FPCAR: u32,
FPDSCR: u32,
MVFR0: u32,
MVFR1: u32,
MVFR2: u32,
};
/// ARM DDI 0403E.b Section B2.2
/// Table B2-1
pub const CACHE_MAINTENANCE_Regs = extern struct {
ICIALLU: u32,
padding0: u32,
ICIMVAU: u32,
DCIMVAC: u32,
DCISW: u32,
DCCMVAU: u32,
DCCMVAC: u32,
DCCSW: u32,
DCCIMVAC: u32,
DCCISW: u32,
BPIALL: u32,
padding1: [2]u32,
};
/// ARM DDI 0403E.b Section B3.2
/// Table B3-6
pub const MCU_ID_Regs = extern struct {
PID4: u32,
PID5: u32,
PID6: u32,
PID7: u32,
PID0: u32,
PID1: u32,
PID2: u32,
PID3: u32,
CID0: u32,
CID1: u32,
CID2: u32,
CID3: u32,
};
test "Force compiler checks" {
std.meta.refAllDecls(@This());
}
test "Spot checking register locations" {
std.testing.expectEqual(@sizeOf(ItmStimPort), 0x4);
std.testing.expectEqual(@sizeOf(SCS_Regs), 0x10);
std.testing.expectEqual(@ptrToInt(&NVIC.STIR), STIR_BASE);
std.testing.expectEqual(@ptrToInt(&ITM.ITM_TPR), ITM_BASE + 0xE40);
std.testing.expectEqual(@byteOffsetOf(ITM_Regs, "ITM_TCR"), 0xE80);
std.testing.expectEqual(@byteOffsetOf(ITM_Regs, "padding0"), 0x400);
std.testing.expectEqual(@sizeOf(DWT_Regs), 0x020 + (16 * bitmask(comptime_int, DWT_CTRL_NUMCOMP_Width)));
std.testing.expectEqual(@byteOffsetOf(TPIU_Regs, "TYPE"), 0xFC8);
std.testing.expectEqual(@byteOffsetOf(FPU_Regs, "MVFR2"), 0xF48 - 0xF34);
} | v7m.zig |
usingnamespace @import("bits.zig");
const std = @import("std");
const builtin = std.builtin;
const assert = std.debug.assert;
const windows = @import("../windows.zig");
const unexpectedError = windows.unexpectedError;
const GetLastError = windows.kernel32.GetLastError;
const SetLastError = windows.kernel32.SetLastError;
fn selectSymbol(comptime function_static: anytype, function_dynamic: @TypeOf(function_static), comptime os: std.Target.Os.WindowsVersion) @TypeOf(function_static) {
comptime {
const sym_ok = std.Target.current.os.isAtLeast(.windows, os);
if (sym_ok == true) return function_static;
if (sym_ok == null) return function_dynamic;
if (sym_ok == false) @compileError("Target OS range does not support function, at least " ++ @tagName(os) ++ " is required");
}
}
// === Messages ===
pub const WNDPROC = fn (hwnd: HWND, uMsg: UINT, wParam: WPARAM, lParam: LPARAM) callconv(WINAPI) LRESULT;
pub const MSG = extern struct {
hWnd: ?HWND,
message: UINT,
wParam: WPARAM,
lParam: LPARAM,
time: DWORD,
pt: POINT,
lPrivate: DWORD,
};
// Compiled by the WINE team @ https://wiki.winehq.org/List_Of_Windows_Messages
pub const WM_NULL = 0x0000;
pub const WM_CREATE = 0x0001;
pub const WM_DESTROY = 0x0002;
pub const WM_MOVE = 0x0003;
pub const WM_SIZE = 0x0005;
pub const WM_ACTIVATE = 0x0006;
pub const WM_SETFOCUS = 0x0007;
pub const WM_KILLFOCUS = 0x0008;
pub const WM_ENABLE = 0x000A;
pub const WM_SETREDRAW = 0x000B;
pub const WM_SETTEXT = 0x000C;
pub const WM_GETTEXT = 0x000D;
pub const WM_GETTEXTLENGTH = 0x000E;
pub const WM_PAINT = 0x000F;
pub const WM_CLOSE = 0x0010;
pub const WM_QUERYENDSESSION = 0x0011;
pub const WM_QUIT = 0x0012;
pub const WM_QUERYOPEN = 0x0013;
pub const WM_ERASEBKGND = 0x0014;
pub const WM_SYSCOLORCHANGE = 0x0015;
pub const WM_ENDSESSION = 0x0016;
pub const WM_SHOWWINDOW = 0x0018;
pub const WM_CTLCOLOR = 0x0019;
pub const WM_WININICHANGE = 0x001A;
pub const WM_DEVMODECHANGE = 0x001B;
pub const WM_ACTIVATEAPP = 0x001C;
pub const WM_FONTCHANGE = 0x001D;
pub const WM_TIMECHANGE = 0x001E;
pub const WM_CANCELMODE = 0x001F;
pub const WM_SETCURSOR = 0x0020;
pub const WM_MOUSEACTIVATE = 0x0021;
pub const WM_CHILDACTIVATE = 0x0022;
pub const WM_QUEUESYNC = 0x0023;
pub const WM_GETMINMAXINFO = 0x0024;
pub const WM_PAINTICON = 0x0026;
pub const WM_ICONERASEBKGND = 0x0027;
pub const WM_NEXTDLGCTL = 0x0028;
pub const WM_SPOOLERSTATUS = 0x002A;
pub const WM_DRAWITEM = 0x002B;
pub const WM_MEASUREITEM = 0x002C;
pub const WM_DELETEITEM = 0x002D;
pub const WM_VKEYTOITEM = 0x002E;
pub const WM_CHARTOITEM = 0x002F;
pub const WM_SETFONT = 0x0030;
pub const WM_GETFONT = 0x0031;
pub const WM_SETHOTKEY = 0x0032;
pub const WM_GETHOTKEY = 0x0033;
pub const WM_QUERYDRAGICON = 0x0037;
pub const WM_COMPAREITEM = 0x0039;
pub const WM_GETOBJECT = 0x003D;
pub const WM_COMPACTING = 0x0041;
pub const WM_COMMNOTIFY = 0x0044;
pub const WM_WINDOWPOSCHANGING = 0x0046;
pub const WM_WINDOWPOSCHANGED = 0x0047;
pub const WM_POWER = 0x0048;
pub const WM_COPYGLOBALDATA = 0x0049;
pub const WM_COPYDATA = 0x004A;
pub const WM_CANCELJOURNAL = 0x004B;
pub const WM_NOTIFY = 0x004E;
pub const WM_INPUTLANGCHANGEREQUEST = 0x0050;
pub const WM_INPUTLANGCHANGE = 0x0051;
pub const WM_TCARD = 0x0052;
pub const WM_HELP = 0x0053;
pub const WM_USERCHANGED = 0x0054;
pub const WM_NOTIFYFORMAT = 0x0055;
pub const WM_CONTEXTMENU = 0x007B;
pub const WM_STYLECHANGING = 0x007C;
pub const WM_STYLECHANGED = 0x007D;
pub const WM_DISPLAYCHANGE = 0x007E;
pub const WM_GETICON = 0x007F;
pub const WM_SETICON = 0x0080;
pub const WM_NCCREATE = 0x0081;
pub const WM_NCDESTROY = 0x0082;
pub const WM_NCCALCSIZE = 0x0083;
pub const WM_NCHITTEST = 0x0084;
pub const WM_NCPAINT = 0x0085;
pub const WM_NCACTIVATE = 0x0086;
pub const WM_GETDLGCODE = 0x0087;
pub const WM_SYNCPAINT = 0x0088;
pub const WM_NCMOUSEMOVE = 0x00A0;
pub const WM_NCLBUTTONDOWN = 0x00A1;
pub const WM_NCLBUTTONUP = 0x00A2;
pub const WM_NCLBUTTONDBLCLK = 0x00A3;
pub const WM_NCRBUTTONDOWN = 0x00A4;
pub const WM_NCRBUTTONUP = 0x00A5;
pub const WM_NCRBUTTONDBLCLK = 0x00A6;
pub const WM_NCMBUTTONDOWN = 0x00A7;
pub const WM_NCMBUTTONUP = 0x00A8;
pub const WM_NCMBUTTONDBLCLK = 0x00A9;
pub const WM_NCXBUTTONDOWN = 0x00AB;
pub const WM_NCXBUTTONUP = 0x00AC;
pub const WM_NCXBUTTONDBLCLK = 0x00AD;
pub const EM_GETSEL = 0x00B0;
pub const EM_SETSEL = 0x00B1;
pub const EM_GETRECT = 0x00B2;
pub const EM_SETRECT = 0x00B3;
pub const EM_SETRECTNP = 0x00B4;
pub const EM_SCROLL = 0x00B5;
pub const EM_LINESCROLL = 0x00B6;
pub const EM_SCROLLCARET = 0x00B7;
pub const EM_GETMODIFY = 0x00B8;
pub const EM_SETMODIFY = 0x00B9;
pub const EM_GETLINECOUNT = 0x00BA;
pub const EM_LINEINDEX = 0x00BB;
pub const EM_SETHANDLE = 0x00BC;
pub const EM_GETHANDLE = 0x00BD;
pub const EM_GETTHUMB = 0x00BE;
pub const EM_LINELENGTH = 0x00C1;
pub const EM_REPLACESEL = 0x00C2;
pub const EM_SETFONT = 0x00C3;
pub const EM_GETLINE = 0x00C4;
pub const EM_LIMITTEXT = 0x00C5;
pub const EM_SETLIMITTEXT = 0x00C5;
pub const EM_CANUNDO = 0x00C6;
pub const EM_UNDO = 0x00C7;
pub const EM_FMTLINES = 0x00C8;
pub const EM_LINEFROMCHAR = 0x00C9;
pub const EM_SETWORDBREAK = 0x00CA;
pub const EM_SETTABSTOPS = 0x00CB;
pub const EM_SETPASSWORDCHAR = 0x00CC;
pub const EM_EMPTYUNDOBUFFER = 0x00CD;
pub const EM_GETFIRSTVISIBLELINE = 0x00CE;
pub const EM_SETREADONLY = 0x00CF;
pub const EM_SETWORDBREAKPROC = 0x00D0;
pub const EM_GETWORDBREAKPROC = 0x00D1;
pub const EM_GETPASSWORDCHAR = 0x00D2;
pub const EM_SETMARGINS = 0x00D3;
pub const EM_GETMARGINS = 0x00D4;
pub const EM_GETLIMITTEXT = 0x00D5;
pub const EM_POSFROMCHAR = 0x00D6;
pub const EM_CHARFROMPOS = 0x00D7;
pub const EM_SETIMESTATUS = 0x00D8;
pub const EM_GETIMESTATUS = 0x00D9;
pub const SBM_SETPOS = 0x00E0;
pub const SBM_GETPOS = 0x00E1;
pub const SBM_SETRANGE = 0x00E2;
pub const SBM_GETRANGE = 0x00E3;
pub const SBM_ENABLE_ARROWS = 0x00E4;
pub const SBM_SETRANGEREDRAW = 0x00E6;
pub const SBM_SETSCROLLINFO = 0x00E9;
pub const SBM_GETSCROLLINFO = 0x00EA;
pub const SBM_GETSCROLLBARINFO = 0x00EB;
pub const BM_GETCHECK = 0x00F0;
pub const BM_SETCHECK = 0x00F1;
pub const BM_GETSTATE = 0x00F2;
pub const BM_SETSTATE = 0x00F3;
pub const BM_SETSTYLE = 0x00F4;
pub const BM_CLICK = 0x00F5;
pub const BM_GETIMAGE = 0x00F6;
pub const BM_SETIMAGE = 0x00F7;
pub const BM_SETDONTCLICK = 0x00F8;
pub const WM_INPUT = 0x00FF;
pub const WM_KEYDOWN = 0x0100;
pub const WM_KEYUP = 0x0101;
pub const WM_CHAR = 0x0102;
pub const WM_DEADCHAR = 0x0103;
pub const WM_SYSKEYDOWN = 0x0104;
pub const WM_SYSKEYUP = 0x0105;
pub const WM_SYSCHAR = 0x0106;
pub const WM_SYSDEADCHAR = 0x0107;
pub const WM_UNICHAR = 0x0109;
pub const WM_WNT_CONVERTREQUESTEX = 0x0109;
pub const WM_CONVERTREQUEST = 0x010A;
pub const WM_CONVERTRESULT = 0x010B;
pub const WM_INTERIM = 0x010C;
pub const WM_IME_STARTCOMPOSITION = 0x010D;
pub const WM_IME_ENDCOMPOSITION = 0x010E;
pub const WM_IME_COMPOSITION = 0x010F;
pub const WM_INITDIALOG = 0x0110;
pub const WM_COMMAND = 0x0111;
pub const WM_SYSCOMMAND = 0x0112;
pub const WM_TIMER = 0x0113;
pub const WM_HSCROLL = 0x0114;
pub const WM_VSCROLL = 0x0115;
pub const WM_INITMENU = 0x0116;
pub const WM_INITMENUPOPUP = 0x0117;
pub const WM_SYSTIMER = 0x0118;
pub const WM_MENUSELECT = 0x011F;
pub const WM_MENUCHAR = 0x0120;
pub const WM_ENTERIDLE = 0x0121;
pub const WM_MENURBUTTONUP = 0x0122;
pub const WM_MENUDRAG = 0x0123;
pub const WM_MENUGETOBJECT = 0x0124;
pub const WM_UNINITMENUPOPUP = 0x0125;
pub const WM_MENUCOMMAND = 0x0126;
pub const WM_CHANGEUISTATE = 0x0127;
pub const WM_UPDATEUISTATE = 0x0128;
pub const WM_QUERYUISTATE = 0x0129;
pub const WM_CTLCOLORMSGBOX = 0x0132;
pub const WM_CTLCOLOREDIT = 0x0133;
pub const WM_CTLCOLORLISTBOX = 0x0134;
pub const WM_CTLCOLORBTN = 0x0135;
pub const WM_CTLCOLORDLG = 0x0136;
pub const WM_CTLCOLORSCROLLBAR = 0x0137;
pub const WM_CTLCOLORSTATIC = 0x0138;
pub const WM_MOUSEMOVE = 0x0200;
pub const WM_LBUTTONDOWN = 0x0201;
pub const WM_LBUTTONUP = 0x0202;
pub const WM_LBUTTONDBLCLK = 0x0203;
pub const WM_RBUTTONDOWN = 0x0204;
pub const WM_RBUTTONUP = 0x0205;
pub const WM_RBUTTONDBLCLK = 0x0206;
pub const WM_MBUTTONDOWN = 0x0207;
pub const WM_MBUTTONUP = 0x0208;
pub const WM_MBUTTONDBLCLK = 0x0209;
pub const WM_MOUSEWHEEL = 0x020A;
pub const WM_XBUTTONDOWN = 0x020B;
pub const WM_XBUTTONUP = 0x020C;
pub const WM_XBUTTONDBLCLK = 0x020D;
pub const WM_MOUSEHWHEEL = 0x020E;
pub const WM_PARENTNOTIFY = 0x0210;
pub const WM_ENTERMENULOOP = 0x0211;
pub const WM_EXITMENULOOP = 0x0212;
pub const WM_NEXTMENU = 0x0213;
pub const WM_SIZING = 0x0214;
pub const WM_CAPTURECHANGED = 0x0215;
pub const WM_MOVING = 0x0216;
pub const WM_POWERBROADCAST = 0x0218;
pub const WM_DEVICECHANGE = 0x0219;
pub const WM_MDICREATE = 0x0220;
pub const WM_MDIDESTROY = 0x0221;
pub const WM_MDIACTIVATE = 0x0222;
pub const WM_MDIRESTORE = 0x0223;
pub const WM_MDINEXT = 0x0224;
pub const WM_MDIMAXIMIZE = 0x0225;
pub const WM_MDITILE = 0x0226;
pub const WM_MDICASCADE = 0x0227;
pub const WM_MDIICONARRANGE = 0x0228;
pub const WM_MDIGETACTIVE = 0x0229;
pub const WM_MDISETMENU = 0x0230;
pub const WM_ENTERSIZEMOVE = 0x0231;
pub const WM_EXITSIZEMOVE = 0x0232;
pub const WM_DROPFILES = 0x0233;
pub const WM_MDIREFRESHMENU = 0x0234;
pub const WM_IME_REPORT = 0x0280;
pub const WM_IME_SETCONTEXT = 0x0281;
pub const WM_IME_NOTIFY = 0x0282;
pub const WM_IME_CONTROL = 0x0283;
pub const WM_IME_COMPOSITIONFULL = 0x0284;
pub const WM_IME_SELECT = 0x0285;
pub const WM_IME_CHAR = 0x0286;
pub const WM_IME_REQUEST = 0x0288;
pub const WM_IMEKEYDOWN = 0x0290;
pub const WM_IME_KEYDOWN = 0x0290;
pub const WM_IMEKEYUP = 0x0291;
pub const WM_IME_KEYUP = 0x0291;
pub const WM_NCMOUSEHOVER = 0x02A0;
pub const WM_MOUSEHOVER = 0x02A1;
pub const WM_NCMOUSELEAVE = 0x02A2;
pub const WM_MOUSELEAVE = 0x02A3;
pub const WM_CUT = 0x0300;
pub const WM_COPY = 0x0301;
pub const WM_PASTE = 0x0302;
pub const WM_CLEAR = 0x0303;
pub const WM_UNDO = 0x0304;
pub const WM_RENDERFORMAT = 0x0305;
pub const WM_RENDERALLFORMATS = 0x0306;
pub const WM_DESTROYCLIPBOARD = 0x0307;
pub const WM_DRAWCLIPBOARD = 0x0308;
pub const WM_PAINTCLIPBOARD = 0x0309;
pub const WM_VSCROLLCLIPBOARD = 0x030A;
pub const WM_SIZECLIPBOARD = 0x030B;
pub const WM_ASKCBFORMATNAME = 0x030C;
pub const WM_CHANGECBCHAIN = 0x030D;
pub const WM_HSCROLLCLIPBOARD = 0x030E;
pub const WM_QUERYNEWPALETTE = 0x030F;
pub const WM_PALETTEISCHANGING = 0x0310;
pub const WM_PALETTECHANGED = 0x0311;
pub const WM_HOTKEY = 0x0312;
pub const WM_PRINT = 0x0317;
pub const WM_PRINTCLIENT = 0x0318;
pub const WM_APPCOMMAND = 0x0319;
pub const WM_RCRESULT = 0x0381;
pub const WM_HOOKRCRESULT = 0x0382;
pub const WM_GLOBALRCCHANGE = 0x0383;
pub const WM_PENMISCINFO = 0x0383;
pub const WM_SKB = 0x0384;
pub const WM_HEDITCTL = 0x0385;
pub const WM_PENCTL = 0x0385;
pub const WM_PENMISC = 0x0386;
pub const WM_CTLINIT = 0x0387;
pub const WM_PENEVENT = 0x0388;
pub const WM_CARET_CREATE = 0x03E0;
pub const WM_CARET_DESTROY = 0x03E1;
pub const WM_CARET_BLINK = 0x03E2;
pub const WM_FDINPUT = 0x03F0;
pub const WM_FDOUTPUT = 0x03F1;
pub const WM_FDEXCEPT = 0x03F2;
pub const DDM_SETFMT = 0x0400;
pub const DM_GETDEFID = 0x0400;
pub const NIN_SELECT = 0x0400;
pub const TBM_GETPOS = 0x0400;
pub const WM_PSD_PAGESETUPDLG = 0x0400;
pub const WM_USER = 0x0400;
pub const CBEM_INSERTITEMA = 0x0401;
pub const DDM_DRAW = 0x0401;
pub const DM_SETDEFID = 0x0401;
pub const HKM_SETHOTKEY = 0x0401;
pub const PBM_SETRANGE = 0x0401;
pub const RB_INSERTBANDA = 0x0401;
pub const SB_SETTEXTA = 0x0401;
pub const TB_ENABLEBUTTON = 0x0401;
pub const TBM_GETRANGEMIN = 0x0401;
pub const TTM_ACTIVATE = 0x0401;
pub const WM_CHOOSEFONT_GETLOGFONT = 0x0401;
pub const WM_PSD_FULLPAGERECT = 0x0401;
pub const CBEM_SETIMAGELIST = 0x0402;
pub const DDM_CLOSE = 0x0402;
pub const DM_REPOSITION = 0x0402;
pub const HKM_GETHOTKEY = 0x0402;
pub const PBM_SETPOS = 0x0402;
pub const RB_DELETEBAND = 0x0402;
pub const SB_GETTEXTA = 0x0402;
pub const TB_CHECKBUTTON = 0x0402;
pub const TBM_GETRANGEMAX = 0x0402;
pub const WM_PSD_MINMARGINRECT = 0x0402;
pub const CBEM_GETIMAGELIST = 0x0403;
pub const DDM_BEGIN = 0x0403;
pub const HKM_SETRULES = 0x0403;
pub const PBM_DELTAPOS = 0x0403;
pub const RB_GETBARINFO = 0x0403;
pub const SB_GETTEXTLENGTHA = 0x0403;
pub const TBM_GETTIC = 0x0403;
pub const TB_PRESSBUTTON = 0x0403;
pub const TTM_SETDELAYTIME = 0x0403;
pub const WM_PSD_MARGINRECT = 0x0403;
pub const CBEM_GETITEMA = 0x0404;
pub const DDM_END = 0x0404;
pub const PBM_SETSTEP = 0x0404;
pub const RB_SETBARINFO = 0x0404;
pub const SB_SETPARTS = 0x0404;
pub const TB_HIDEBUTTON = 0x0404;
pub const TBM_SETTIC = 0x0404;
pub const TTM_ADDTOOLA = 0x0404;
pub const WM_PSD_GREEKTEXTRECT = 0x0404;
pub const CBEM_SETITEMA = 0x0405;
pub const PBM_STEPIT = 0x0405;
pub const TB_INDETERMINATE = 0x0405;
pub const TBM_SETPOS = 0x0405;
pub const TTM_DELTOOLA = 0x0405;
pub const WM_PSD_ENVSTAMPRECT = 0x0405;
pub const CBEM_GETCOMBOCONTROL = 0x0406;
pub const PBM_SETRANGE32 = 0x0406;
pub const RB_SETBANDINFOA = 0x0406;
pub const SB_GETPARTS = 0x0406;
pub const TB_MARKBUTTON = 0x0406;
pub const TBM_SETRANGE = 0x0406;
pub const TTM_NEWTOOLRECTA = 0x0406;
pub const WM_PSD_YAFULLPAGERECT = 0x0406;
pub const CBEM_GETEDITCONTROL = 0x0407;
pub const PBM_GETRANGE = 0x0407;
pub const RB_SETPARENT = 0x0407;
pub const SB_GETBORDERS = 0x0407;
pub const TBM_SETRANGEMIN = 0x0407;
pub const TTM_RELAYEVENT = 0x0407;
pub const CBEM_SETEXSTYLE = 0x0408;
pub const PBM_GETPOS = 0x0408;
pub const RB_HITTEST = 0x0408;
pub const SB_SETMINHEIGHT = 0x0408;
pub const TBM_SETRANGEMAX = 0x0408;
pub const TTM_GETTOOLINFOA = 0x0408;
pub const CBEM_GETEXSTYLE = 0x0409;
pub const CBEM_GETEXTENDEDSTYLE = 0x0409;
pub const PBM_SETBARCOLOR = 0x0409;
pub const RB_GETRECT = 0x0409;
pub const SB_SIMPLE = 0x0409;
pub const TB_ISBUTTONENABLED = 0x0409;
pub const TBM_CLEARTICS = 0x0409;
pub const TTM_SETTOOLINFOA = 0x0409;
pub const CBEM_HASEDITCHANGED = 0x040A;
pub const RB_INSERTBANDW = 0x040A;
pub const SB_GETRECT = 0x040A;
pub const TB_ISBUTTONCHECKED = 0x040A;
pub const TBM_SETSEL = 0x040A;
pub const TTM_HITTESTA = 0x040A;
pub const WIZ_QUERYNUMPAGES = 0x040A;
pub const CBEM_INSERTITEMW = 0x040B;
pub const RB_SETBANDINFOW = 0x040B;
pub const SB_SETTEXTW = 0x040B;
pub const TB_ISBUTTONPRESSED = 0x040B;
pub const TBM_SETSELSTART = 0x040B;
pub const TTM_GETTEXTA = 0x040B;
pub const WIZ_NEXT = 0x040B;
pub const CBEM_SETITEMW = 0x040C;
pub const RB_GETBANDCOUNT = 0x040C;
pub const SB_GETTEXTLENGTHW = 0x040C;
pub const TB_ISBUTTONHIDDEN = 0x040C;
pub const TBM_SETSELEND = 0x040C;
pub const TTM_UPDATETIPTEXTA = 0x040C;
pub const WIZ_PREV = 0x040C;
pub const CBEM_GETITEMW = 0x040D;
pub const RB_GETROWCOUNT = 0x040D;
pub const SB_GETTEXTW = 0x040D;
pub const TB_ISBUTTONINDETERMINATE = 0x040D;
pub const TTM_GETTOOLCOUNT = 0x040D;
pub const CBEM_SETEXTENDEDSTYLE = 0x040E;
pub const RB_GETROWHEIGHT = 0x040E;
pub const SB_ISSIMPLE = 0x040E;
pub const TB_ISBUTTONHIGHLIGHTED = 0x040E;
pub const TBM_GETPTICS = 0x040E;
pub const TTM_ENUMTOOLSA = 0x040E;
pub const SB_SETICON = 0x040F;
pub const TBM_GETTICPOS = 0x040F;
pub const TTM_GETCURRENTTOOLA = 0x040F;
pub const RB_IDTOINDEX = 0x0410;
pub const SB_SETTIPTEXTA = 0x0410;
pub const TBM_GETNUMTICS = 0x0410;
pub const TTM_WINDOWFROMPOINT = 0x0410;
pub const RB_GETTOOLTIPS = 0x0411;
pub const SB_SETTIPTEXTW = 0x0411;
pub const TBM_GETSELSTART = 0x0411;
pub const TB_SETSTATE = 0x0411;
pub const TTM_TRACKACTIVATE = 0x0411;
pub const RB_SETTOOLTIPS = 0x0412;
pub const SB_GETTIPTEXTA = 0x0412;
pub const TB_GETSTATE = 0x0412;
pub const TBM_GETSELEND = 0x0412;
pub const TTM_TRACKPOSITION = 0x0412;
pub const RB_SETBKCOLOR = 0x0413;
pub const SB_GETTIPTEXTW = 0x0413;
pub const TB_ADDBITMAP = 0x0413;
pub const TBM_CLEARSEL = 0x0413;
pub const TTM_SETTIPBKCOLOR = 0x0413;
pub const RB_GETBKCOLOR = 0x0414;
pub const SB_GETICON = 0x0414;
pub const TB_ADDBUTTONSA = 0x0414;
pub const TBM_SETTICFREQ = 0x0414;
pub const TTM_SETTIPTEXTCOLOR = 0x0414;
pub const RB_SETTEXTCOLOR = 0x0415;
pub const TB_INSERTBUTTONA = 0x0415;
pub const TBM_SETPAGESIZE = 0x0415;
pub const TTM_GETDELAYTIME = 0x0415;
pub const RB_GETTEXTCOLOR = 0x0416;
pub const TB_DELETEBUTTON = 0x0416;
pub const TBM_GETPAGESIZE = 0x0416;
pub const TTM_GETTIPBKCOLOR = 0x0416;
pub const RB_SIZETORECT = 0x0417;
pub const TB_GETBUTTON = 0x0417;
pub const TBM_SETLINESIZE = 0x0417;
pub const TTM_GETTIPTEXTCOLOR = 0x0417;
pub const RB_BEGINDRAG = 0x0418;
pub const TB_BUTTONCOUNT = 0x0418;
pub const TBM_GETLINESIZE = 0x0418;
pub const TTM_SETMAXTIPWIDTH = 0x0418;
pub const RB_ENDDRAG = 0x0419;
pub const TB_COMMANDTOINDEX = 0x0419;
pub const TBM_GETTHUMBRECT = 0x0419;
pub const TTM_GETMAXTIPWIDTH = 0x0419;
pub const RB_DRAGMOVE = 0x041A;
pub const TBM_GETCHANNELRECT = 0x041A;
pub const TB_SAVERESTOREA = 0x041A;
pub const TTM_SETMARGIN = 0x041A;
pub const RB_GETBARHEIGHT = 0x041B;
pub const TB_CUSTOMIZE = 0x041B;
pub const TBM_SETTHUMBLENGTH = 0x041B;
pub const TTM_GETMARGIN = 0x041B;
pub const RB_GETBANDINFOW = 0x041C;
pub const TB_ADDSTRINGA = 0x041C;
pub const TBM_GETTHUMBLENGTH = 0x041C;
pub const TTM_POP = 0x041C;
pub const RB_GETBANDINFOA = 0x041D;
pub const TB_GETITEMRECT = 0x041D;
pub const TBM_SETTOOLTIPS = 0x041D;
pub const TTM_UPDATE = 0x041D;
pub const RB_MINIMIZEBAND = 0x041E;
pub const TB_BUTTONSTRUCTSIZE = 0x041E;
pub const TBM_GETTOOLTIPS = 0x041E;
pub const TTM_GETBUBBLESIZE = 0x041E;
pub const RB_MAXIMIZEBAND = 0x041F;
pub const TBM_SETTIPSIDE = 0x041F;
pub const TB_SETBUTTONSIZE = 0x041F;
pub const TTM_ADJUSTRECT = 0x041F;
pub const TBM_SETBUDDY = 0x0420;
pub const TB_SETBITMAPSIZE = 0x0420;
pub const TTM_SETTITLEA = 0x0420;
pub const MSG_FTS_JUMP_VA = 0x0421;
pub const TB_AUTOSIZE = 0x0421;
pub const TBM_GETBUDDY = 0x0421;
pub const TTM_SETTITLEW = 0x0421;
pub const RB_GETBANDBORDERS = 0x0422;
pub const MSG_FTS_JUMP_QWORD = 0x0423;
pub const RB_SHOWBAND = 0x0423;
pub const TB_GETTOOLTIPS = 0x0423;
pub const MSG_REINDEX_REQUEST = 0x0424;
pub const TB_SETTOOLTIPS = 0x0424;
pub const MSG_FTS_WHERE_IS_IT = 0x0425;
pub const RB_SETPALETTE = 0x0425;
pub const TB_SETPARENT = 0x0425;
pub const RB_GETPALETTE = 0x0426;
pub const RB_MOVEBAND = 0x0427;
pub const TB_SETROWS = 0x0427;
pub const TB_GETROWS = 0x0428;
pub const TB_GETBITMAPFLAGS = 0x0429;
pub const TB_SETCMDID = 0x042A;
pub const RB_PUSHCHEVRON = 0x042B;
pub const TB_CHANGEBITMAP = 0x042B;
pub const TB_GETBITMAP = 0x042C;
pub const MSG_GET_DEFFONT = 0x042D;
pub const TB_GETBUTTONTEXTA = 0x042D;
pub const TB_REPLACEBITMAP = 0x042E;
pub const TB_SETINDENT = 0x042F;
pub const TB_SETIMAGELIST = 0x0430;
pub const TB_GETIMAGELIST = 0x0431;
pub const TB_LOADIMAGES = 0x0432;
pub const EM_CANPASTE = 0x0432;
pub const TTM_ADDTOOLW = 0x0432;
pub const EM_DISPLAYBAND = 0x0433;
pub const TB_GETRECT = 0x0433;
pub const TTM_DELTOOLW = 0x0433;
pub const EM_EXGETSEL = 0x0434;
pub const TB_SETHOTIMAGELIST = 0x0434;
pub const TTM_NEWTOOLRECTW = 0x0434;
pub const EM_EXLIMITTEXT = 0x0435;
pub const TB_GETHOTIMAGELIST = 0x0435;
pub const TTM_GETTOOLINFOW = 0x0435;
pub const EM_EXLINEFROMCHAR = 0x0436;
pub const TB_SETDISABLEDIMAGELIST = 0x0436;
pub const TTM_SETTOOLINFOW = 0x0436;
pub const EM_EXSETSEL = 0x0437;
pub const TB_GETDISABLEDIMAGELIST = 0x0437;
pub const TTM_HITTESTW = 0x0437;
pub const EM_FINDTEXT = 0x0438;
pub const TB_SETSTYLE = 0x0438;
pub const TTM_GETTEXTW = 0x0438;
pub const EM_FORMATRANGE = 0x0439;
pub const TB_GETSTYLE = 0x0439;
pub const TTM_UPDATETIPTEXTW = 0x0439;
pub const EM_GETCHARFORMAT = 0x043A;
pub const TB_GETBUTTONSIZE = 0x043A;
pub const TTM_ENUMTOOLSW = 0x043A;
pub const EM_GETEVENTMASK = 0x043B;
pub const TB_SETBUTTONWIDTH = 0x043B;
pub const TTM_GETCURRENTTOOLW = 0x043B;
pub const EM_GETOLEINTERFACE = 0x043C;
pub const TB_SETMAXTEXTROWS = 0x043C;
pub const EM_GETPARAFORMAT = 0x043D;
pub const TB_GETTEXTROWS = 0x043D;
pub const EM_GETSELTEXT = 0x043E;
pub const TB_GETOBJECT = 0x043E;
pub const EM_HIDESELECTION = 0x043F;
pub const TB_GETBUTTONINFOW = 0x043F;
pub const EM_PASTESPECIAL = 0x0440;
pub const TB_SETBUTTONINFOW = 0x0440;
pub const EM_REQUESTRESIZE = 0x0441;
pub const TB_GETBUTTONINFOA = 0x0441;
pub const EM_SELECTIONTYPE = 0x0442;
pub const TB_SETBUTTONINFOA = 0x0442;
pub const EM_SETBKGNDCOLOR = 0x0443;
pub const TB_INSERTBUTTONW = 0x0443;
pub const EM_SETCHARFORMAT = 0x0444;
pub const TB_ADDBUTTONSW = 0x0444;
pub const EM_SETEVENTMASK = 0x0445;
pub const TB_HITTEST = 0x0445;
pub const EM_SETOLECALLBACK = 0x0446;
pub const TB_SETDRAWTEXTFLAGS = 0x0446;
pub const EM_SETPARAFORMAT = 0x0447;
pub const TB_GETHOTITEM = 0x0447;
pub const EM_SETTARGETDEVICE = 0x0448;
pub const TB_SETHOTITEM = 0x0448;
pub const EM_STREAMIN = 0x0449;
pub const TB_SETANCHORHIGHLIGHT = 0x0449;
pub const EM_STREAMOUT = 0x044A;
pub const TB_GETANCHORHIGHLIGHT = 0x044A;
pub const EM_GETTEXTRANGE = 0x044B;
pub const TB_GETBUTTONTEXTW = 0x044B;
pub const EM_FINDWORDBREAK = 0x044C;
pub const TB_SAVERESTOREW = 0x044C;
pub const EM_SETOPTIONS = 0x044D;
pub const TB_ADDSTRINGW = 0x044D;
pub const EM_GETOPTIONS = 0x044E;
pub const TB_MAPACCELERATORA = 0x044E;
pub const EM_FINDTEXTEX = 0x044F;
pub const TB_GETINSERTMARK = 0x044F;
pub const EM_GETWORDBREAKPROCEX = 0x0450;
pub const TB_SETINSERTMARK = 0x0450;
pub const EM_SETWORDBREAKPROCEX = 0x0451;
pub const TB_INSERTMARKHITTEST = 0x0451;
pub const EM_SETUNDOLIMIT = 0x0452;
pub const TB_MOVEBUTTON = 0x0452;
pub const TB_GETMAXSIZE = 0x0453;
pub const EM_REDO = 0x0454;
pub const TB_SETEXTENDEDSTYLE = 0x0454;
pub const EM_CANREDO = 0x0455;
pub const TB_GETEXTENDEDSTYLE = 0x0455;
pub const EM_GETUNDONAME = 0x0456;
pub const TB_GETPADDING = 0x0456;
pub const EM_GETREDONAME = 0x0457;
pub const TB_SETPADDING = 0x0457;
pub const EM_STOPGROUPTYPING = 0x0458;
pub const TB_SETINSERTMARKCOLOR = 0x0458;
pub const EM_SETTEXTMODE = 0x0459;
pub const TB_GETINSERTMARKCOLOR = 0x0459;
pub const EM_GETTEXTMODE = 0x045A;
pub const TB_MAPACCELERATORW = 0x045A;
pub const EM_AUTOURLDETECT = 0x045B;
pub const TB_GETSTRINGW = 0x045B;
pub const EM_GETAUTOURLDETECT = 0x045C;
pub const TB_GETSTRINGA = 0x045C;
pub const EM_SETPALETTE = 0x045D;
pub const EM_GETTEXTEX = 0x045E;
pub const EM_GETTEXTLENGTHEX = 0x045F;
pub const EM_SHOWSCROLLBAR = 0x0460;
pub const EM_SETTEXTEX = 0x0461;
pub const TAPI_REPLY = 0x0463;
pub const ACM_OPENA = 0x0464;
pub const BFFM_SETSTATUSTEXTA = 0x0464;
pub const CDM_GETSPEC = 0x0464;
pub const EM_SETPUNCTUATION = 0x0464;
pub const IPM_CLEARADDRESS = 0x0464;
pub const WM_CAP_UNICODE_START = 0x0464;
pub const ACM_PLAY = 0x0465;
pub const BFFM_ENABLEOK = 0x0465;
pub const CDM_GETFILEPATH = 0x0465;
pub const EM_GETPUNCTUATION = 0x0465;
pub const IPM_SETADDRESS = 0x0465;
pub const PSM_SETCURSEL = 0x0465;
pub const UDM_SETRANGE = 0x0465;
pub const WM_CHOOSEFONT_SETLOGFONT = 0x0465;
pub const ACM_STOP = 0x0466;
pub const BFFM_SETSELECTIONA = 0x0466;
pub const CDM_GETFOLDERPATH = 0x0466;
pub const EM_SETWORDWRAPMODE = 0x0466;
pub const IPM_GETADDRESS = 0x0466;
pub const PSM_REMOVEPAGE = 0x0466;
pub const UDM_GETRANGE = 0x0466;
pub const WM_CAP_SET_CALLBACK_ERRORW = 0x0466;
pub const WM_CHOOSEFONT_SETFLAGS = 0x0466;
pub const ACM_OPENW = 0x0467;
pub const BFFM_SETSELECTIONW = 0x0467;
pub const CDM_GETFOLDERIDLIST = 0x0467;
pub const EM_GETWORDWRAPMODE = 0x0467;
pub const IPM_SETRANGE = 0x0467;
pub const PSM_ADDPAGE = 0x0467;
pub const UDM_SETPOS = 0x0467;
pub const WM_CAP_SET_CALLBACK_STATUSW = 0x0467;
pub const BFFM_SETSTATUSTEXTW = 0x0468;
pub const CDM_SETCONTROLTEXT = 0x0468;
pub const EM_SETIMECOLOR = 0x0468;
pub const IPM_SETFOCUS = 0x0468;
pub const PSM_CHANGED = 0x0468;
pub const UDM_GETPOS = 0x0468;
pub const CDM_HIDECONTROL = 0x0469;
pub const EM_GETIMECOLOR = 0x0469;
pub const IPM_ISBLANK = 0x0469;
pub const PSM_RESTARTWINDOWS = 0x0469;
pub const UDM_SETBUDDY = 0x0469;
pub const CDM_SETDEFEXT = 0x046A;
pub const EM_SETIMEOPTIONS = 0x046A;
pub const PSM_REBOOTSYSTEM = 0x046A;
pub const UDM_GETBUDDY = 0x046A;
pub const EM_GETIMEOPTIONS = 0x046B;
pub const PSM_CANCELTOCLOSE = 0x046B;
pub const UDM_SETACCEL = 0x046B;
pub const EM_CONVPOSITION = 0x046C;
pub const PSM_QUERYSIBLINGS = 0x046C;
pub const UDM_GETACCEL = 0x046C;
pub const MCIWNDM_GETZOOM = 0x046D;
pub const PSM_UNCHANGED = 0x046D;
pub const UDM_SETBASE = 0x046D;
pub const PSM_APPLY = 0x046E;
pub const UDM_GETBASE = 0x046E;
pub const PSM_SETTITLEA = 0x046F;
pub const UDM_SETRANGE32 = 0x046F;
pub const PSM_SETWIZBUTTONS = 0x0470;
pub const UDM_GETRANGE32 = 0x0470;
pub const WM_CAP_DRIVER_GET_NAMEW = 0x0470;
pub const PSM_PRESSBUTTON = 0x0471;
pub const UDM_SETPOS32 = 0x0471;
pub const WM_CAP_DRIVER_GET_VERSIONW = 0x0471;
pub const PSM_SETCURSELID = 0x0472;
pub const UDM_GETPOS32 = 0x0472;
pub const PSM_SETFINISHTEXTA = 0x0473;
pub const PSM_GETTABCONTROL = 0x0474;
pub const PSM_ISDIALOGMESSAGE = 0x0475;
pub const MCIWNDM_REALIZE = 0x0476;
pub const PSM_GETCURRENTPAGEHWND = 0x0476;
pub const MCIWNDM_SETTIMEFORMATA = 0x0477;
pub const PSM_INSERTPAGE = 0x0477;
pub const EM_SETLANGOPTIONS = 0x0478;
pub const MCIWNDM_GETTIMEFORMATA = 0x0478;
pub const PSM_SETTITLEW = 0x0478;
pub const WM_CAP_FILE_SET_CAPTURE_FILEW = 0x0478;
pub const EM_GETLANGOPTIONS = 0x0479;
pub const MCIWNDM_VALIDATEMEDIA = 0x0479;
pub const PSM_SETFINISHTEXTW = 0x0479;
pub const WM_CAP_FILE_GET_CAPTURE_FILEW = 0x0479;
pub const EM_GETIMECOMPMODE = 0x047A;
pub const EM_FINDTEXTW = 0x047B;
pub const MCIWNDM_PLAYTO = 0x047B;
pub const WM_CAP_FILE_SAVEASW = 0x047B;
pub const EM_FINDTEXTEXW = 0x047C;
pub const MCIWNDM_GETFILENAMEA = 0x047C;
pub const EM_RECONVERSION = 0x047D;
pub const MCIWNDM_GETDEVICEA = 0x047D;
pub const PSM_SETHEADERTITLEA = 0x047D;
pub const WM_CAP_FILE_SAVEDIBW = 0x047D;
pub const EM_SETIMEMODEBIAS = 0x047E;
pub const MCIWNDM_GETPALETTE = 0x047E;
pub const PSM_SETHEADERTITLEW = 0x047E;
pub const EM_GETIMEMODEBIAS = 0x047F;
pub const MCIWNDM_SETPALETTE = 0x047F;
pub const PSM_SETHEADERSUBTITLEA = 0x047F;
pub const MCIWNDM_GETERRORA = 0x0480;
pub const PSM_SETHEADERSUBTITLEW = 0x0480;
pub const PSM_HWNDTOINDEX = 0x0481;
pub const PSM_INDEXTOHWND = 0x0482;
pub const MCIWNDM_SETINACTIVETIMER = 0x0483;
pub const PSM_PAGETOINDEX = 0x0483;
pub const PSM_INDEXTOPAGE = 0x0484;
pub const DL_BEGINDRAG = 0x0485;
pub const MCIWNDM_GETINACTIVETIMER = 0x0485;
pub const PSM_IDTOINDEX = 0x0485;
pub const DL_DRAGGING = 0x0486;
pub const PSM_INDEXTOID = 0x0486;
pub const DL_DROPPED = 0x0487;
pub const PSM_GETRESULT = 0x0487;
pub const DL_CANCELDRAG = 0x0488;
pub const PSM_RECALCPAGESIZES = 0x0488;
pub const MCIWNDM_GET_SOURCE = 0x048C;
pub const MCIWNDM_PUT_SOURCE = 0x048D;
pub const MCIWNDM_GET_DEST = 0x048E;
pub const MCIWNDM_PUT_DEST = 0x048F;
pub const MCIWNDM_CAN_PLAY = 0x0490;
pub const MCIWNDM_CAN_WINDOW = 0x0491;
pub const MCIWNDM_CAN_RECORD = 0x0492;
pub const MCIWNDM_CAN_SAVE = 0x0493;
pub const MCIWNDM_CAN_EJECT = 0x0494;
pub const MCIWNDM_CAN_CONFIG = 0x0495;
pub const IE_GETINK = 0x0496;
pub const MCIWNDM_PALETTEKICK = 0x0496;
pub const IE_SETINK = 0x0497;
pub const IE_GETPENTIP = 0x0498;
pub const IE_SETPENTIP = 0x0499;
pub const IE_GETERASERTIP = 0x049A;
pub const IE_SETERASERTIP = 0x049B;
pub const IE_GETBKGND = 0x049C;
pub const IE_SETBKGND = 0x049D;
pub const IE_GETGRIDORIGIN = 0x049E;
pub const IE_SETGRIDORIGIN = 0x049F;
pub const IE_GETGRIDPEN = 0x04A0;
pub const IE_SETGRIDPEN = 0x04A1;
pub const IE_GETGRIDSIZE = 0x04A2;
pub const IE_SETGRIDSIZE = 0x04A3;
pub const IE_GETMODE = 0x04A4;
pub const IE_SETMODE = 0x04A5;
pub const IE_GETINKRECT = 0x04A6;
pub const WM_CAP_SET_MCI_DEVICEW = 0x04A6;
pub const WM_CAP_GET_MCI_DEVICEW = 0x04A7;
pub const WM_CAP_PAL_OPENW = 0x04B4;
pub const WM_CAP_PAL_SAVEW = 0x04B5;
pub const IE_GETAPPDATA = 0x04B8;
pub const IE_SETAPPDATA = 0x04B9;
pub const IE_GETDRAWOPTS = 0x04BA;
pub const IE_SETDRAWOPTS = 0x04BB;
pub const IE_GETFORMAT = 0x04BC;
pub const IE_SETFORMAT = 0x04BD;
pub const IE_GETINKINPUT = 0x04BE;
pub const IE_SETINKINPUT = 0x04BF;
pub const IE_GETNOTIFY = 0x04C0;
pub const IE_SETNOTIFY = 0x04C1;
pub const IE_GETRECOG = 0x04C2;
pub const IE_SETRECOG = 0x04C3;
pub const IE_GETSECURITY = 0x04C4;
pub const IE_SETSECURITY = 0x04C5;
pub const IE_GETSEL = 0x04C6;
pub const IE_SETSEL = 0x04C7;
pub const EM_SETBIDIOPTIONS = 0x04C8;
pub const IE_DOCOMMAND = 0x04C8;
pub const MCIWNDM_NOTIFYMODE = 0x04C8;
pub const EM_GETBIDIOPTIONS = 0x04C9;
pub const IE_GETCOMMAND = 0x04C9;
pub const EM_SETTYPOGRAPHYOPTIONS = 0x04CA;
pub const IE_GETCOUNT = 0x04CA;
pub const EM_GETTYPOGRAPHYOPTIONS = 0x04CB;
pub const IE_GETGESTURE = 0x04CB;
pub const MCIWNDM_NOTIFYMEDIA = 0x04CB;
pub const EM_SETEDITSTYLE = 0x04CC;
pub const IE_GETMENU = 0x04CC;
pub const EM_GETEDITSTYLE = 0x04CD;
pub const IE_GETPAINTDC = 0x04CD;
pub const MCIWNDM_NOTIFYERROR = 0x04CD;
pub const IE_GETPDEVENT = 0x04CE;
pub const IE_GETSELCOUNT = 0x04CF;
pub const IE_GETSELITEMS = 0x04D0;
pub const IE_GETSTYLE = 0x04D1;
pub const MCIWNDM_SETTIMEFORMATW = 0x04DB;
pub const EM_OUTLINE = 0x04DC;
pub const MCIWNDM_GETTIMEFORMATW = 0x04DC;
pub const EM_GETSCROLLPOS = 0x04DD;
pub const EM_SETSCROLLPOS = 0x04DE;
pub const EM_SETFONTSIZE = 0x04DF;
pub const EM_GETZOOM = 0x04E0;
pub const MCIWNDM_GETFILENAMEW = 0x04E0;
pub const EM_SETZOOM = 0x04E1;
pub const MCIWNDM_GETDEVICEW = 0x04E1;
pub const EM_GETVIEWKIND = 0x04E2;
pub const EM_SETVIEWKIND = 0x04E3;
pub const EM_GETPAGE = 0x04E4;
pub const MCIWNDM_GETERRORW = 0x04E4;
pub const EM_SETPAGE = 0x04E5;
pub const EM_GETHYPHENATEINFO = 0x04E6;
pub const EM_SETHYPHENATEINFO = 0x04E7;
pub const EM_GETPAGEROTATE = 0x04EB;
pub const EM_SETPAGEROTATE = 0x04EC;
pub const EM_GETCTFMODEBIAS = 0x04ED;
pub const EM_SETCTFMODEBIAS = 0x04EE;
pub const EM_GETCTFOPENSTATUS = 0x04F0;
pub const EM_SETCTFOPENSTATUS = 0x04F1;
pub const EM_GETIMECOMPTEXT = 0x04F2;
pub const EM_ISIME = 0x04F3;
pub const EM_GETIMEPROPERTY = 0x04F4;
pub const EM_GETQUERYRTFOBJ = 0x050D;
pub const EM_SETQUERYRTFOBJ = 0x050E;
pub const FM_GETFOCUS = 0x0600;
pub const FM_GETDRIVEINFOA = 0x0601;
pub const FM_GETSELCOUNT = 0x0602;
pub const FM_GETSELCOUNTLFN = 0x0603;
pub const FM_GETFILESELA = 0x0604;
pub const FM_GETFILESELLFNA = 0x0605;
pub const FM_REFRESH_WINDOWS = 0x0606;
pub const FM_RELOAD_EXTENSIONS = 0x0607;
pub const FM_GETDRIVEINFOW = 0x0611;
pub const FM_GETFILESELW = 0x0614;
pub const FM_GETFILESELLFNW = 0x0615;
pub const WLX_WM_SAS = 0x0659;
pub const SM_GETSELCOUNT = 0x07E8;
pub const UM_GETSELCOUNT = 0x07E8;
pub const WM_CPL_LAUNCH = 0x07E8;
pub const SM_GETSERVERSELA = 0x07E9;
pub const UM_GETUSERSELA = 0x07E9;
pub const WM_CPL_LAUNCHED = 0x07E9;
pub const SM_GETSERVERSELW = 0x07EA;
pub const UM_GETUSERSELW = 0x07EA;
pub const SM_GETCURFOCUSA = 0x07EB;
pub const UM_GETGROUPSELA = 0x07EB;
pub const SM_GETCURFOCUSW = 0x07EC;
pub const UM_GETGROUPSELW = 0x07EC;
pub const SM_GETOPTIONS = 0x07ED;
pub const UM_GETCURFOCUSA = 0x07ED;
pub const UM_GETCURFOCUSW = 0x07EE;
pub const UM_GETOPTIONS = 0x07EF;
pub const UM_GETOPTIONS2 = 0x07F0;
pub const LVM_GETBKCOLOR = 0x1000;
pub const LVM_SETBKCOLOR = 0x1001;
pub const LVM_GETIMAGELIST = 0x1002;
pub const LVM_SETIMAGELIST = 0x1003;
pub const LVM_GETITEMCOUNT = 0x1004;
pub const LVM_GETITEMA = 0x1005;
pub const LVM_SETITEMA = 0x1006;
pub const LVM_INSERTITEMA = 0x1007;
pub const LVM_DELETEITEM = 0x1008;
pub const LVM_DELETEALLITEMS = 0x1009;
pub const LVM_GETCALLBACKMASK = 0x100A;
pub const LVM_SETCALLBACKMASK = 0x100B;
pub const LVM_GETNEXTITEM = 0x100C;
pub const LVM_FINDITEMA = 0x100D;
pub const LVM_GETITEMRECT = 0x100E;
pub const LVM_SETITEMPOSITION = 0x100F;
pub const LVM_GETITEMPOSITION = 0x1010;
pub const LVM_GETSTRINGWIDTHA = 0x1011;
pub const LVM_HITTEST = 0x1012;
pub const LVM_ENSUREVISIBLE = 0x1013;
pub const LVM_SCROLL = 0x1014;
pub const LVM_REDRAWITEMS = 0x1015;
pub const LVM_ARRANGE = 0x1016;
pub const LVM_EDITLABELA = 0x1017;
pub const LVM_GETEDITCONTROL = 0x1018;
pub const LVM_GETCOLUMNA = 0x1019;
pub const LVM_SETCOLUMNA = 0x101A;
pub const LVM_INSERTCOLUMNA = 0x101B;
pub const LVM_DELETECOLUMN = 0x101C;
pub const LVM_GETCOLUMNWIDTH = 0x101D;
pub const LVM_SETCOLUMNWIDTH = 0x101E;
pub const LVM_GETHEADER = 0x101F;
pub const LVM_CREATEDRAGIMAGE = 0x1021;
pub const LVM_GETVIEWRECT = 0x1022;
pub const LVM_GETTEXTCOLOR = 0x1023;
pub const LVM_SETTEXTCOLOR = 0x1024;
pub const LVM_GETTEXTBKCOLOR = 0x1025;
pub const LVM_SETTEXTBKCOLOR = 0x1026;
pub const LVM_GETTOPINDEX = 0x1027;
pub const LVM_GETCOUNTPERPAGE = 0x1028;
pub const LVM_GETORIGIN = 0x1029;
pub const LVM_UPDATE = 0x102A;
pub const LVM_SETITEMSTATE = 0x102B;
pub const LVM_GETITEMSTATE = 0x102C;
pub const LVM_GETITEMTEXTA = 0x102D;
pub const LVM_SETITEMTEXTA = 0x102E;
pub const LVM_SETITEMCOUNT = 0x102F;
pub const LVM_SORTITEMS = 0x1030;
pub const LVM_SETITEMPOSITION32 = 0x1031;
pub const LVM_GETSELECTEDCOUNT = 0x1032;
pub const LVM_GETITEMSPACING = 0x1033;
pub const LVM_GETISEARCHSTRINGA = 0x1034;
pub const LVM_SETICONSPACING = 0x1035;
pub const LVM_SETEXTENDEDLISTVIEWSTYLE = 0x1036;
pub const LVM_GETEXTENDEDLISTVIEWSTYLE = 0x1037;
pub const LVM_GETSUBITEMRECT = 0x1038;
pub const LVM_SUBITEMHITTEST = 0x1039;
pub const LVM_SETCOLUMNORDERARRAY = 0x103A;
pub const LVM_GETCOLUMNORDERARRAY = 0x103B;
pub const LVM_SETHOTITEM = 0x103C;
pub const LVM_GETHOTITEM = 0x103D;
pub const LVM_SETHOTCURSOR = 0x103E;
pub const LVM_GETHOTCURSOR = 0x103F;
pub const LVM_APPROXIMATEVIEWRECT = 0x1040;
pub const LVM_SETWORKAREAS = 0x1041;
pub const LVM_GETSELECTIONMARK = 0x1042;
pub const LVM_SETSELECTIONMARK = 0x1043;
pub const LVM_SETBKIMAGEA = 0x1044;
pub const LVM_GETBKIMAGEA = 0x1045;
pub const LVM_GETWORKAREAS = 0x1046;
pub const LVM_SETHOVERTIME = 0x1047;
pub const LVM_GETHOVERTIME = 0x1048;
pub const LVM_GETNUMBEROFWORKAREAS = 0x1049;
pub const LVM_SETTOOLTIPS = 0x104A;
pub const LVM_GETITEMW = 0x104B;
pub const LVM_SETITEMW = 0x104C;
pub const LVM_INSERTITEMW = 0x104D;
pub const LVM_GETTOOLTIPS = 0x104E;
pub const LVM_FINDITEMW = 0x1053;
pub const LVM_GETSTRINGWIDTHW = 0x1057;
pub const LVM_GETCOLUMNW = 0x105F;
pub const LVM_SETCOLUMNW = 0x1060;
pub const LVM_INSERTCOLUMNW = 0x1061;
pub const LVM_GETITEMTEXTW = 0x1073;
pub const LVM_SETITEMTEXTW = 0x1074;
pub const LVM_GETISEARCHSTRINGW = 0x1075;
pub const LVM_EDITLABELW = 0x1076;
pub const LVM_GETBKIMAGEW = 0x108B;
pub const LVM_SETSELECTEDCOLUMN = 0x108C;
pub const LVM_SETTILEWIDTH = 0x108D;
pub const LVM_SETVIEW = 0x108E;
pub const LVM_GETVIEW = 0x108F;
pub const LVM_INSERTGROUP = 0x1091;
pub const LVM_SETGROUPINFO = 0x1093;
pub const LVM_GETGROUPINFO = 0x1095;
pub const LVM_REMOVEGROUP = 0x1096;
pub const LVM_MOVEGROUP = 0x1097;
pub const LVM_MOVEITEMTOGROUP = 0x109A;
pub const LVM_SETGROUPMETRICS = 0x109B;
pub const LVM_GETGROUPMETRICS = 0x109C;
pub const LVM_ENABLEGROUPVIEW = 0x109D;
pub const LVM_SORTGROUPS = 0x109E;
pub const LVM_INSERTGROUPSORTED = 0x109F;
pub const LVM_REMOVEALLGROUPS = 0x10A0;
pub const LVM_HASGROUP = 0x10A1;
pub const LVM_SETTILEVIEWINFO = 0x10A2;
pub const LVM_GETTILEVIEWINFO = 0x10A3;
pub const LVM_SETTILEINFO = 0x10A4;
pub const LVM_GETTILEINFO = 0x10A5;
pub const LVM_SETINSERTMARK = 0x10A6;
pub const LVM_GETINSERTMARK = 0x10A7;
pub const LVM_INSERTMARKHITTEST = 0x10A8;
pub const LVM_GETINSERTMARKRECT = 0x10A9;
pub const LVM_SETINSERTMARKCOLOR = 0x10AA;
pub const LVM_GETINSERTMARKCOLOR = 0x10AB;
pub const LVM_SETINFOTIP = 0x10AD;
pub const LVM_GETSELECTEDCOLUMN = 0x10AE;
pub const LVM_ISGROUPVIEWENABLED = 0x10AF;
pub const LVM_GETOUTLINECOLOR = 0x10B0;
pub const LVM_SETOUTLINECOLOR = 0x10B1;
pub const LVM_CANCELEDITLABEL = 0x10B3;
pub const LVM_MAPINDEXTOID = 0x10B4;
pub const LVM_MAPIDTOINDEX = 0x10B5;
pub const LVM_ISITEMVISIBLE = 0x10B6;
pub const OCM__BASE = 0x2000;
pub const LVM_SETUNICODEFORMAT = 0x2005;
pub const LVM_GETUNICODEFORMAT = 0x2006;
pub const OCM_CTLCOLOR = 0x2019;
pub const OCM_DRAWITEM = 0x202B;
pub const OCM_MEASUREITEM = 0x202C;
pub const OCM_DELETEITEM = 0x202D;
pub const OCM_VKEYTOITEM = 0x202E;
pub const OCM_CHARTOITEM = 0x202F;
pub const OCM_COMPAREITEM = 0x2039;
pub const OCM_NOTIFY = 0x204E;
pub const OCM_COMMAND = 0x2111;
pub const OCM_HSCROLL = 0x2114;
pub const OCM_VSCROLL = 0x2115;
pub const OCM_CTLCOLORMSGBOX = 0x2132;
pub const OCM_CTLCOLOREDIT = 0x2133;
pub const OCM_CTLCOLORLISTBOX = 0x2134;
pub const OCM_CTLCOLORBTN = 0x2135;
pub const OCM_CTLCOLORDLG = 0x2136;
pub const OCM_CTLCOLORSCROLLBAR = 0x2137;
pub const OCM_CTLCOLORSTATIC = 0x2138;
pub const OCM_PARENTNOTIFY = 0x2210;
pub const WM_APP = 0x8000;
pub const WM_RASDIALEVENT = 0xCCCD;
pub extern "user32" fn GetMessageA(lpMsg: *MSG, hWnd: ?HWND, wMsgFilterMin: UINT, wMsgFilterMax: UINT) callconv(WINAPI) BOOL;
pub fn getMessageA(lpMsg: *MSG, hWnd: ?HWND, wMsgFilterMin: u32, wMsgFilterMax: u32) !void {
const r = GetMessageA(lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax);
if (r == 0) return error.Quit;
if (r != -1) return;
switch (GetLastError()) {
.INVALID_WINDOW_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return windows.unexpectedError(err),
}
}
pub extern "user32" fn GetMessageW(lpMsg: *MSG, hWnd: ?HWND, wMsgFilterMin: UINT, wMsgFilterMax: UINT) callconv(WINAPI) BOOL;
pub var pfnGetMessageW: @TypeOf(GetMessageW) = undefined;
pub fn getMessageW(lpMsg: *MSG, hWnd: ?HWND, wMsgFilterMin: u32, wMsgFilterMax: u32) !void {
const function = selectSymbol(GetMessageW, pfnGetMessageW, .win2k);
const r = function(lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax);
if (r == 0) return error.Quit;
if (r != -1) return;
switch (GetLastError()) {
.INVALID_WINDOW_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return windows.unexpectedError(err),
}
}
pub const PM_NOREMOVE = 0x0000;
pub const PM_REMOVE = 0x0001;
pub const PM_NOYIELD = 0x0002;
pub extern "user32" fn PeekMessageA(lpMsg: *MSG, hWnd: ?HWND, wMsgFilterMin: UINT, wMsgFilterMax: UINT, wRemoveMsg: UINT) callconv(WINAPI) BOOL;
pub fn peekMessageA(lpMsg: *MSG, hWnd: ?HWND, wMsgFilterMin: u32, wMsgFilterMax: u32, wRemoveMsg: u32) !bool {
const r = PeekMessageA(lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax, wRemoveMsg);
if (r == 0) return false;
if (r != -1) return true;
switch (GetLastError()) {
.INVALID_WINDOW_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return windows.unexpectedError(err),
}
}
pub extern "user32" fn PeekMessageW(lpMsg: *MSG, hWnd: ?HWND, wMsgFilterMin: UINT, wMsgFilterMax: UINT, wRemoveMsg: UINT) callconv(WINAPI) BOOL;
pub var pfnPeekMessageW: @TypeOf(PeekMessageW) = undefined;
pub fn peekMessageW(lpMsg: *MSG, hWnd: ?HWND, wMsgFilterMin: u32, wMsgFilterMax: u32, wRemoveMsg: u32) !bool {
const function = selectSymbol(PeekMessageW, pfnPeekMessageW, .win2k);
const r = function(lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax, wRemoveMsg);
if (r == 0) return false;
if (r != -1) return true;
switch (GetLastError()) {
.INVALID_WINDOW_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return windows.unexpectedError(err),
}
}
pub extern "user32" fn TranslateMessage(lpMsg: *const MSG) callconv(WINAPI) BOOL;
pub fn translateMessage(lpMsg: *const MSG) bool {
return if (TranslateMessage(lpMsg) == 0) false else true;
}
pub extern "user32" fn DispatchMessageA(lpMsg: *const MSG) callconv(WINAPI) LRESULT;
pub fn dispatchMessageA(lpMsg: *const MSG) LRESULT {
return DispatchMessageA(lpMsg);
}
pub extern "user32" fn DispatchMessageW(lpMsg: *const MSG) callconv(WINAPI) LRESULT;
pub var pfnDispatchMessageW: @TypeOf(DispatchMessageW) = undefined;
pub fn dispatchMessageW(lpMsg: *const MSG) LRESULT {
const function = selectSymbol(DispatchMessageW, pfnDispatchMessageW, .win2k);
return function(lpMsg);
}
pub extern "user32" fn PostQuitMessage(nExitCode: i32) callconv(WINAPI) void;
pub fn postQuitMessage(nExitCode: i32) void {
PostQuitMessage(nExitCode);
}
pub extern "user32" fn DefWindowProcA(hWnd: HWND, Msg: UINT, wParam: WPARAM, lParam: LPARAM) callconv(WINAPI) LRESULT;
pub fn defWindowProcA(hWnd: HWND, Msg: UINT, wParam: WPARAM, lParam: LPARAM) LRESULT {
return DefWindowProcA(hWnd, Msg, wParam, lParam);
}
pub extern "user32" fn DefWindowProcW(hWnd: HWND, Msg: UINT, wParam: WPARAM, lParam: LPARAM) callconv(WINAPI) LRESULT;
pub var pfnDefWindowProcW: @TypeOf(DefWindowProcW) = undefined;
pub fn defWindowProcW(hWnd: HWND, Msg: UINT, wParam: WPARAM, lParam: LPARAM) LRESULT {
const function = selectSymbol(DefWindowProcW, pfnDefWindowProcW, .win2k);
return function(hWnd, Msg, wParam, lParam);
}
// === Windows ===
pub const CS_VREDRAW = 0x0001;
pub const CS_HREDRAW = 0x0002;
pub const CS_DBLCLKS = 0x0008;
pub const CS_OWNDC = 0x0020;
pub const CS_CLASSDC = 0x0040;
pub const CS_PARENTDC = 0x0080;
pub const CS_NOCLOSE = 0x0200;
pub const CS_SAVEBITS = 0x0800;
pub const CS_BYTEALIGNCLIENT = 0x1000;
pub const CS_BYTEALIGNWINDOW = 0x2000;
pub const CS_GLOBALCLASS = 0x4000;
pub const WNDCLASSEXA = extern struct {
cbSize: UINT = @sizeOf(WNDCLASSEXA),
style: UINT,
lpfnWndProc: WNDPROC,
cbClsExtra: i32 = 0,
cbWndExtra: i32 = 0,
hInstance: HINSTANCE,
hIcon: ?HICON,
hCursor: ?HCURSOR,
hbrBackground: ?HBRUSH,
lpszMenuName: ?[*:0]const u8,
lpszClassName: [*:0]const u8,
hIconSm: ?HICON,
};
pub const WNDCLASSEXW = extern struct {
cbSize: UINT = @sizeOf(WNDCLASSEXW),
style: UINT,
lpfnWndProc: WNDPROC,
cbClsExtra: i32 = 0,
cbWndExtra: i32 = 0,
hInstance: HINSTANCE,
hIcon: ?HICON,
hCursor: ?HCURSOR,
hbrBackground: ?HBRUSH,
lpszMenuName: ?[*:0]const u16,
lpszClassName: [*:0]const u16,
hIconSm: ?HICON,
};
pub extern "user32" fn RegisterClassExA(*const WNDCLASSEXA) callconv(WINAPI) ATOM;
pub fn registerClassExA(window_class: *const WNDCLASSEXA) !ATOM {
const atom = RegisterClassExA(window_class);
if (atom != 0) return atom;
switch (GetLastError()) {
.CLASS_ALREADY_EXISTS => return error.AlreadyExists,
.INVALID_PARAMETER => unreachable,
else => |err| return windows.unexpectedError(err),
}
}
pub extern "user32" fn RegisterClassExW(*const WNDCLASSEXW) callconv(WINAPI) ATOM;
pub var pfnRegisterClassExW: @TypeOf(RegisterClassExW) = undefined;
pub fn registerClassExW(window_class: *const WNDCLASSEXW) !ATOM {
const function = selectSymbol(RegisterClassExW, pfnRegisterClassExW, .win2k);
const atom = function(window_class);
if (atom != 0) return atom;
switch (GetLastError()) {
.CLASS_ALREADY_EXISTS => return error.AlreadyExists,
.CALL_NOT_IMPLEMENTED => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return windows.unexpectedError(err),
}
}
pub extern "user32" fn UnregisterClassA(lpClassName: [*:0]const u8, hInstance: HINSTANCE) callconv(WINAPI) BOOL;
pub fn unregisterClassA(lpClassName: [*:0]const u8, hInstance: HINSTANCE) !void {
if (UnregisterClassA(lpClassName, hInstance) == 0) {
switch (GetLastError()) {
.CLASS_DOES_NOT_EXIST => return error.ClassDoesNotExist,
else => |err| return windows.unexpectedError(err),
}
}
}
pub extern "user32" fn UnregisterClassW(lpClassName: [*:0]const u16, hInstance: HINSTANCE) callconv(WINAPI) BOOL;
pub var pfnUnregisterClassW: @TypeOf(UnregisterClassW) = undefined;
pub fn unregisterClassW(lpClassName: [*:0]const u16, hInstance: HINSTANCE) !void {
const function = selectSymbol(UnregisterClassW, pfnUnregisterClassW, .win2k);
if (function(lpClassName, hInstance) == 0) {
switch (GetLastError()) {
.CLASS_DOES_NOT_EXIST => return error.ClassDoesNotExist,
else => |err| return windows.unexpectedError(err),
}
}
}
pub const WS_OVERLAPPED = 0x00000000;
pub const WS_POPUP = 0x80000000;
pub const WS_CHILD = 0x40000000;
pub const WS_MINIMIZE = 0x20000000;
pub const WS_VISIBLE = 0x10000000;
pub const WS_DISABLED = 0x08000000;
pub const WS_CLIPSIBLINGS = 0x04000000;
pub const WS_CLIPCHILDREN = 0x02000000;
pub const WS_MAXIMIZE = 0x01000000;
pub const WS_CAPTION = WS_BORDER | WS_DLGFRAME;
pub const WS_BORDER = 0x00800000;
pub const WS_DLGFRAME = 0x00400000;
pub const WS_VSCROLL = 0x00200000;
pub const WS_HSCROLL = 0x00100000;
pub const WS_SYSMENU = 0x00080000;
pub const WS_THICKFRAME = 0x00040000;
pub const WS_GROUP = 0x00020000;
pub const WS_TABSTOP = 0x00010000;
pub const WS_MINIMIZEBOX = 0x00020000;
pub const WS_MAXIMIZEBOX = 0x00010000;
pub const WS_TILED = WS_OVERLAPPED;
pub const WS_ICONIC = WS_MINIMIZE;
pub const WS_SIZEBOX = WS_THICKFRAME;
pub const WS_TILEDWINDOW = WS_OVERLAPPEDWINDOW;
pub const WS_OVERLAPPEDWINDOW = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX;
pub const WS_POPUPWINDOW = WS_POPUP | WS_BORDER | WS_SYSMENU;
pub const WS_CHILDWINDOW = WS_CHILD;
pub const WS_EX_DLGMODALFRAME = 0x00000001;
pub const WS_EX_NOPARENTNOTIFY = 0x00000004;
pub const WS_EX_TOPMOST = 0x00000008;
pub const WS_EX_ACCEPTFILES = 0x00000010;
pub const WS_EX_TRANSPARENT = 0x00000020;
pub const WS_EX_MDICHILD = 0x00000040;
pub const WS_EX_TOOLWINDOW = 0x00000080;
pub const WS_EX_WINDOWEDGE = 0x00000100;
pub const WS_EX_CLIENTEDGE = 0x00000200;
pub const WS_EX_CONTEXTHELP = 0x00000400;
pub const WS_EX_RIGHT = 0x00001000;
pub const WS_EX_LEFT = 0x00000000;
pub const WS_EX_RTLREADING = 0x00002000;
pub const WS_EX_LTRREADING = 0x00000000;
pub const WS_EX_LEFTSCROLLBAR = 0x00004000;
pub const WS_EX_RIGHTSCROLLBAR = 0x00000000;
pub const WS_EX_CONTROLPARENT = 0x00010000;
pub const WS_EX_STATICEDGE = 0x00020000;
pub const WS_EX_APPWINDOW = 0x00040000;
pub const WS_EX_LAYERED = 0x00080000;
pub const WS_EX_OVERLAPPEDWINDOW = WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE;
pub const WS_EX_PALETTEWINDOW = WS_EX_WINDOWEDGE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST;
pub const CW_USEDEFAULT = @bitCast(i32, @as(u32, 0x80000000));
pub extern "user32" fn CreateWindowExA(dwExStyle: DWORD, lpClassName: [*:0]const u8, lpWindowName: [*:0]const u8, dwStyle: DWORD, X: i32, Y: i32, nWidth: i32, nHeight: i32, hWindParent: ?HWND, hMenu: ?HMENU, hInstance: HINSTANCE, lpParam: ?LPVOID) callconv(WINAPI) ?HWND;
pub fn createWindowExA(dwExStyle: u32, lpClassName: [*:0]const u8, lpWindowName: [*:0]const u8, dwStyle: u32, X: i32, Y: i32, nWidth: i32, nHeight: i32, hWindParent: ?HWND, hMenu: ?HMENU, hInstance: HINSTANCE, lpParam: ?*c_void) !HWND {
const window = CreateWindowExA(dwExStyle, lpClassName, lpWindowName, dwStyle, X, Y, nWidth, nHeight, hWindParent, hMenu, hInstance, lpParam);
if (window) |win| return win;
switch (GetLastError()) {
.CLASS_DOES_NOT_EXIST => return error.ClassDoesNotExist,
.INVALID_PARAMETER => unreachable,
else => |err| return windows.unexpectedError(err),
}
}
pub extern "user32" fn CreateWindowExW(dwExStyle: DWORD, lpClassName: [*:0]const u16, lpWindowName: [*:0]const u16, dwStyle: DWORD, X: i32, Y: i32, nWidth: i32, nHeight: i32, hWindParent: ?HWND, hMenu: ?HMENU, hInstance: HINSTANCE, lpParam: ?LPVOID) callconv(WINAPI) ?HWND;
pub var pfnCreateWindowExW: @TypeOf(CreateWindowExW) = undefined;
pub fn createWindowExW(dwExStyle: u32, lpClassName: [*:0]const u16, lpWindowName: [*:0]const u16, dwStyle: u32, X: i32, Y: i32, nWidth: i32, nHeight: i32, hWindParent: ?HWND, hMenu: ?HMENU, hInstance: HINSTANCE, lpParam: ?*c_void) !HWND {
const function = selectSymbol(CreateWindowExW, pfnCreateWindowExW, .win2k);
const window = function(dwExStyle, lpClassName, lpWindowName, dwStyle, X, Y, nWidth, nHeight, hWindParent, hMenu, hInstance, lpParam);
if (window) |win| return win;
switch (GetLastError()) {
.CLASS_DOES_NOT_EXIST => return error.ClassDoesNotExist,
.INVALID_PARAMETER => unreachable,
else => |err| return windows.unexpectedError(err),
}
}
pub extern "user32" fn DestroyWindow(hWnd: HWND) callconv(WINAPI) BOOL;
pub fn destroyWindow(hWnd: HWND) !void {
if (DestroyWindow(hWnd) == 0) {
switch (GetLastError()) {
.INVALID_WINDOW_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return windows.unexpectedError(err),
}
}
}
pub const SW_HIDE = 0;
pub const SW_SHOWNORMAL = 1;
pub const SW_NORMAL = 1;
pub const SW_SHOWMINIMIZED = 2;
pub const SW_SHOWMAXIMIZED = 3;
pub const SW_MAXIMIZE = 3;
pub const SW_SHOWNOACTIVATE = 4;
pub const SW_SHOW = 5;
pub const SW_MINIMIZE = 6;
pub const SW_SHOWMINNOACTIVE = 7;
pub const SW_SHOWNA = 8;
pub const SW_RESTORE = 9;
pub const SW_SHOWDEFAULT = 10;
pub const SW_FORCEMINIMIZE = 11;
pub const SW_MAX = 11;
pub extern "user32" fn ShowWindow(hWnd: HWND, nCmdShow: i32) callconv(WINAPI) BOOL;
pub fn showWindow(hWnd: HWND, nCmdShow: i32) bool {
return (ShowWindow(hWnd, nCmdShow) == TRUE);
}
pub extern "user32" fn UpdateWindow(hWnd: HWND) callconv(WINAPI) BOOL;
pub fn updateWindow(hWnd: HWND) !void {
if (ShowWindow(hWnd, nCmdShow) == 0) {
switch (GetLastError()) {
.INVALID_WINDOW_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return windows.unexpectedError(err),
}
}
}
pub extern "user32" fn AdjustWindowRectEx(lpRect: *RECT, dwStyle: DWORD, bMenu: BOOL, dwExStyle: DWORD) callconv(WINAPI) BOOL;
pub fn adjustWindowRectEx(lpRect: *RECT, dwStyle: u32, bMenu: bool, dwExStyle: u32) !void {
assert(dwStyle & WS_OVERLAPPED == 0);
if (AdjustWindowRectEx(lpRect, dwStyle, @boolToInt(bMenu), dwExStyle) == 0) {
switch (GetLastError()) {
.INVALID_PARAMETER => unreachable,
else => |err| return windows.unexpectedError(err),
}
}
}
pub const GWL_WNDPROC = -4;
pub const GWL_HINSTANCE = -6;
pub const GWL_HWNDPARENT = -8;
pub const GWL_STYLE = -16;
pub const GWL_EXSTYLE = -20;
pub const GWL_USERDATA = -21;
pub const GWL_ID = -12;
pub extern "user32" fn GetWindowLongA(hWnd: HWND, nIndex: i32) callconv(WINAPI) LONG;
pub fn getWindowLongA(hWnd: HWND, nIndex: i32) !i32 {
const value = GetWindowLongA(hWnd, nIndex);
if (value != 0) return value;
switch (GetLastError()) {
.SUCCESS => return 0,
.INVALID_WINDOW_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return windows.unexpectedError(err),
}
}
pub extern "user32" fn GetWindowLongW(hWnd: HWND, nIndex: i32) callconv(WINAPI) LONG;
pub var pfnGetWindowLongW: @TypeOf(GetWindowLongW) = undefined;
pub fn getWindowLongW(hWnd: HWND, nIndex: i32) !i32 {
const function = selectSymbol(GetWindowLongW, pfnGetWindowLongW, .win2k);
const value = function(hWnd, nIndex);
if (value != 0) return value;
switch (GetLastError()) {
.SUCCESS => return 0,
.INVALID_WINDOW_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return windows.unexpectedError(err),
}
}
pub extern "user32" fn GetWindowLongPtrA(hWnd: HWND, nIndex: i32) callconv(WINAPI) LONG_PTR;
pub fn getWindowLongPtrA(hWnd: HWND, nIndex: i32) !isize {
// "When compiling for 32-bit Windows, GetWindowLongPtr is defined as a call to the GetWindowLong function."
// https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getwindowlongptrw
if (@sizeOf(LONG_PTR) == 4) return getWindowLongA(hWnd, nIndex);
const value = GetWindowLongPtrA(hWnd, nIndex);
if (value != 0) return value;
switch (GetLastError()) {
.SUCCESS => return 0,
.INVALID_WINDOW_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return windows.unexpectedError(err),
}
}
pub extern "user32" fn GetWindowLongPtrW(hWnd: HWND, nIndex: i32) callconv(WINAPI) LONG_PTR;
pub var pfnGetWindowLongPtrW: @TypeOf(GetWindowLongPtrW) = undefined;
pub fn getWindowLongPtrW(hWnd: HWND, nIndex: i32) !isize {
if (@sizeOf(LONG_PTR) == 4) return getWindowLongW(hWnd, nIndex);
const function = selectSymbol(GetWindowLongPtrW, pfnGetWindowLongPtrW, .win2k);
const value = function(hWnd, nIndex);
if (value != 0) return value;
switch (GetLastError()) {
.SUCCESS => return 0,
.INVALID_WINDOW_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return windows.unexpectedError(err),
}
}
pub extern "user32" fn SetWindowLongA(hWnd: HWND, nIndex: i32, dwNewLong: LONG) callconv(WINAPI) LONG;
pub fn setWindowLongA(hWnd: HWND, nIndex: i32, dwNewLong: i32) !i32 {
// [...] you should clear the last error information by calling SetLastError with 0 before calling SetWindowLong.
// https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setwindowlonga
SetLastError(.SUCCESS);
const value = SetWindowLongA(hWnd, nIndex, dwNewLong);
if (value != 0) return value;
switch (GetLastError()) {
.SUCCESS => return 0,
.INVALID_WINDOW_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return windows.unexpectedError(err),
}
}
pub extern "user32" fn SetWindowLongW(hWnd: HWND, nIndex: i32, dwNewLong: LONG) callconv(WINAPI) LONG;
pub var pfnSetWindowLongW: @TypeOf(SetWindowLongW) = undefined;
pub fn setWindowLongW(hWnd: HWND, nIndex: i32, dwNewLong: i32) !i32 {
const function = selectSymbol(SetWindowLongW, pfnSetWindowLongW, .win2k);
SetLastError(.SUCCESS);
const value = function(hWnd, nIndex, dwNewLong);
if (value != 0) return value;
switch (GetLastError()) {
.SUCCESS => return 0,
.INVALID_WINDOW_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return windows.unexpectedError(err),
}
}
pub extern "user32" fn SetWindowLongPtrA(hWnd: HWND, nIndex: i32, dwNewLong: LONG_PTR) callconv(WINAPI) LONG_PTR;
pub fn setWindowLongPtrA(hWnd: HWND, nIndex: i32, dwNewLong: isize) !isize {
// "When compiling for 32-bit Windows, GetWindowLongPtr is defined as a call to the GetWindowLong function."
// https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getwindowlongptrw
if (@sizeOf(LONG_PTR) == 4) return setWindowLongA(hWnd, nIndex, dwNewLong);
SetLastError(.SUCCESS);
const value = SetWindowLongPtrA(hWnd, nIndex, dwNewLong);
if (value != 0) return value;
switch (GetLastError()) {
.SUCCESS => return 0,
.INVALID_WINDOW_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return windows.unexpectedError(err),
}
}
pub extern "user32" fn SetWindowLongPtrW(hWnd: HWND, nIndex: i32, dwNewLong: LONG_PTR) callconv(WINAPI) LONG_PTR;
pub var pfnSetWindowLongPtrW: @TypeOf(SetWindowLongPtrW) = undefined;
pub fn setWindowLongPtrW(hWnd: HWND, nIndex: i32, dwNewLong: isize) !isize {
if (@sizeOf(LONG_PTR) == 4) return setWindowLongW(hWnd, nIndex, dwNewLong);
const function = selectSymbol(SetWindowLongPtrW, pfnSetWindowLongPtrW, .win2k);
SetLastError(.SUCCESS);
const value = function(hWnd, nIndex, dwNewLong);
if (value != 0) return value;
switch (GetLastError()) {
.SUCCESS => return 0,
.INVALID_WINDOW_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return windows.unexpectedError(err),
}
}
pub extern "user32" fn GetDC(hWnd: ?HWND) callconv(WINAPI) ?HDC;
pub fn getDC(hWnd: ?HWND) !HDC {
const hdc = GetDC(hWnd);
if (hdc) |h| return h;
switch (GetLastError()) {
.INVALID_WINDOW_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return windows.unexpectedError(err),
}
}
pub extern "user32" fn ReleaseDC(hWnd: ?HWND, hDC: HDC) callconv(WINAPI) i32;
pub fn releaseDC(hWnd: ?HWND, hDC: HDC) bool {
return if (ReleaseDC(hWnd, hDC) == 1) true else false;
}
// === Modal dialogue boxes ===
pub const MB_OK = 0x00000000;
pub const MB_OKCANCEL = 0x00000001;
pub const MB_ABORTRETRYIGNORE = 0x00000002;
pub const MB_YESNOCANCEL = 0x00000003;
pub const MB_YESNO = 0x00000004;
pub const MB_RETRYCANCEL = 0x00000005;
pub const MB_CANCELTRYCONTINUE = 0x00000006;
pub const MB_ICONHAND = 0x00000010;
pub const MB_ICONQUESTION = 0x00000020;
pub const MB_ICONEXCLAMATION = 0x00000030;
pub const MB_ICONASTERISK = 0x00000040;
pub const MB_USERICON = 0x00000080;
pub const MB_ICONWARNING = MB_ICONEXCLAMATION;
pub const MB_ICONERROR = MB_ICONHAND;
pub const MB_ICONINFORMATION = MB_ICONASTERISK;
pub const MB_ICONSTOP = MB_ICONHAND;
pub const MB_DEFBUTTON1 = 0x00000000;
pub const MB_DEFBUTTON2 = 0x00000100;
pub const MB_DEFBUTTON3 = 0x00000200;
pub const MB_DEFBUTTON4 = 0x00000300;
pub const MB_APPLMODAL = 0x00000000;
pub const MB_SYSTEMMODAL = 0x00001000;
pub const MB_TASKMODAL = 0x00002000;
pub const MB_HELP = 0x00004000;
pub const MB_NOFOCUS = 0x00008000;
pub const MB_SETFOREGROUND = 0x00010000;
pub const MB_DEFAULT_DESKTOP_ONLY = 0x00020000;
pub const MB_TOPMOST = 0x00040000;
pub const MB_RIGHT = 0x00080000;
pub const MB_RTLREADING = 0x00100000;
pub const MB_TYPEMASK = 0x0000000F;
pub const MB_ICONMASK = 0x000000F0;
pub const MB_DEFMASK = 0x00000F00;
pub const MB_MODEMASK = 0x00003000;
pub const MB_MISCMASK = 0x0000C000;
pub const IDOK = 1;
pub const IDCANCEL = 2;
pub const IDABORT = 3;
pub const IDRETRY = 4;
pub const IDIGNORE = 5;
pub const IDYES = 6;
pub const IDNO = 7;
pub const IDCLOSE = 8;
pub const IDHELP = 9;
pub const IDTRYAGAIN = 10;
pub const IDCONTINUE = 11;
pub extern "user32" fn MessageBoxA(hWnd: ?HWND, lpText: [*:0]const u8, lpCaption: [*:0]const u8, uType: UINT) callconv(WINAPI) i32;
pub fn messageBoxA(hWnd: ?HWND, lpText: [*:0]const u8, lpCaption: [*:0]const u8, uType: u32) !i32 {
const value = MessageBoxA(hWnd, lpText, lpCaption, uType);
if (value != 0) return value;
switch (GetLastError()) {
.INVALID_WINDOW_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return windows.unexpectedError(err),
}
}
pub extern "user32" fn MessageBoxW(hWnd: ?HWND, lpText: [*:0]const u16, lpCaption: ?[*:0]const u16, uType: UINT) callconv(WINAPI) i32;
pub var pfnMessageBoxW: @TypeOf(MessageBoxW) = undefined;
pub fn messageBoxW(hWnd: ?HWND, lpText: [*:0]const u16, lpCaption: [*:0]const u16, uType: u32) !i32 {
const function = selectSymbol(MessageBoxW, pfnMessageBoxW, .win2k);
const value = function(hWnd, lpText, lpCaption, uType);
if (value != 0) return value;
switch (GetLastError()) {
.INVALID_WINDOW_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
else => |err| return windows.unexpectedError(err),
}
} | lib/std/os/windows/user32.zig |
const std = @import("std");
const os = @import("windows.zig");
const dcommon = @import("dcommon.zig");
const HRESULT = os.HRESULT;
const RESOURCE_STATES = @import("d3d12.zig").RESOURCE_STATES;
pub const CREATE_DEVICE_FLAG = packed struct {
SINGLETHREADED: bool = false,
DEBUG: bool = false,
SWITCH_TO_REF: bool = false,
PREVENT_INTERNAL_THREADING_OPTIMIZATIONS: bool = false,
RESERVED0: bool = false,
BGRA_SUPPORT: bool = false,
DEBUGGABLE: bool = false,
PREVENT_ALTERING_LAYER_SETTINGS_FROM_REGISTRY: bool = false,
DISABLE_GPU_TIMEOUT: bool = false,
padding: u24 = 0,
};
pub const IDevice = extern struct {
const Self = @This();
vtbl: *const extern struct {
// IUnknown
QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT,
AddRef: fn (*Self) callconv(.C) u32,
Release: fn (*Self) callconv(.C) u32,
// ID3D11Device
CreateBuffer: *c_void,
CreateTexture1D: *c_void,
CreateTexture2D: *c_void,
CreateTexture3D: *c_void,
CreateShaderResourceView: *c_void,
CreateUnorderedAccessView: *c_void,
CreateRenderTargetView: *c_void,
CreateDepthStencilView: *c_void,
CreateInputLayout: *c_void,
CreateVertexShader: *c_void,
CreateGeometryShader: *c_void,
CreateGeometryShaderWithStreamOutput: *c_void,
CreatePixelShader: *c_void,
CreateHullShader: *c_void,
CreateDomainShader: *c_void,
CreateComputeShader: *c_void,
CreateClassLinkage: *c_void,
CreateBlendState: *c_void,
CreateDepthStencilState: *c_void,
CreateRasterizerState: *c_void,
CreateSamplerState: *c_void,
CreateQuery: *c_void,
CreatePredicate: *c_void,
CreateCounter: *c_void,
CreateDeferredContext: *c_void,
OpenSharedResource: *c_void,
CheckFormatSupport: *c_void,
CheckMultisampleQualityLevels: *c_void,
CheckCounterInfo: *c_void,
CheckCounter: *c_void,
CheckFeatureSupport: *c_void,
GetPrivateData: *c_void,
SetPrivateData: *c_void,
SetPrivateDataInterface: *c_void,
GetFeatureLevel: *c_void,
GetCreationFlags: *c_void,
GetDeviceRemovedReason: *c_void,
GetImmediateContext: *c_void,
SetExceptionMode: *c_void,
GetExceptionMode: *c_void,
},
usingnamespace os.IUnknown.Methods(Self);
};
pub const IResource = extern struct {
const Self = @This();
vtbl: *const extern struct {
// IUnknown
QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT,
AddRef: fn (*Self) callconv(.C) u32,
Release: fn (*Self) callconv(.C) u32,
// ID3D11DeviceChild
GetDevice: *c_void,
GetPrivateData: *c_void,
SetPrivateData: *c_void,
SetPrivateDataInterface: *c_void,
// ID3D11Resource
GetType: *c_void,
SetEvictionPriority: *c_void,
GetEvictionPriority: *c_void,
},
usingnamespace os.IUnknown.Methods(Self);
};
pub const IDeviceContext = extern struct {
const Self = @This();
vtbl: *const extern struct {
// IUnknown
QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT,
AddRef: fn (*Self) callconv(.C) u32,
Release: fn (*Self) callconv(.C) u32,
// ID3D11DeviceChild
GetDevice: *c_void,
GetPrivateData: *c_void,
SetPrivateData: *c_void,
SetPrivateDataInterface: *c_void,
// ID3D11DeviceContext
VSSetConstantBuffers: *c_void,
PSSetShaderResources: *c_void,
PSSetShader: *c_void,
PSSetSamplers: *c_void,
VSSetShader: *c_void,
DrawIndexed: *c_void,
Draw: *c_void,
Map: *c_void,
Unmap: *c_void,
PSSetConstantBuffers: *c_void,
IASetInputLayout: *c_void,
IASetVertexBuffers: *c_void,
IASetIndexBuffer: *c_void,
DrawIndexedInstanced: *c_void,
DrawInstanced: *c_void,
GSSetConstantBuffers: *c_void,
GSSetShader: *c_void,
IASetPrimitiveTopology: *c_void,
VSSetShaderResources: *c_void,
VSSetSamplers: *c_void,
Begin: *c_void,
End: *c_void,
GetData: *c_void,
SetPredication: *c_void,
GSSetShaderResources: *c_void,
GSSetSamplers: *c_void,
OMSetRenderTargets: *c_void,
OMSetRenderTargetsAndUnorderedAccessViews: *c_void,
OMSetBlendState: *c_void,
OMSetDepthStencilState: *c_void,
SOSetTargets: *c_void,
DrawAuto: *c_void,
DrawIndexedInstancedIndirect: *c_void,
DrawInstancedIndirect: *c_void,
Dispatch: *c_void,
DispatchIndirect: *c_void,
RSSetState: *c_void,
RSSetViewports: *c_void,
RSSetScissorRects: *c_void,
CopySubresourceRegion: *c_void,
CopyResource: *c_void,
UpdateSubresource: *c_void,
CopyStructureCount: *c_void,
ClearRenderTargetView: *c_void,
ClearUnorderedAccessViewUint: *c_void,
ClearUnorderedAccessViewFloat: *c_void,
ClearDepthStencilView: *c_void,
GenerateMips: *c_void,
SetResourceMinLOD: *c_void,
GetResourceMinLOD: *c_void,
ResolveSubresource: *c_void,
ExecuteCommandList: *c_void,
HSSetShaderResources: *c_void,
HSSetShader: *c_void,
HSSetSamplers: *c_void,
HSSetConstantBuffers: *c_void,
DSSetShaderResources: *c_void,
DSSetShader: *c_void,
DSSetSamplers: *c_void,
DSSetConstantBuffers: *c_void,
CSSetShaderResources: *c_void,
CSSetUnorderedAccessViews: *c_void,
CSSetShader: *c_void,
CSSetSamplers: *c_void,
CSSetConstantBuffers: *c_void,
VSGetConstantBuffers: *c_void,
PSGetShaderResources: *c_void,
PSGetShader: *c_void,
PSGetSamplers: *c_void,
VSGetShader: *c_void,
PSGetConstantBuffers: *c_void,
IAGetInputLayout: *c_void,
IAGetVertexBuffers: *c_void,
IAGetIndexBuffer: *c_void,
GSGetConstantBuffers: *c_void,
GSGetShader: *c_void,
IAGetPrimitiveTopology: *c_void,
VSGetShaderResources: *c_void,
VSGetSamplers: *c_void,
GetPredication: *c_void,
GSGetShaderResources: *c_void,
GSGetSamplers: *c_void,
OMGetRenderTargets: *c_void,
OMGetRenderTargetsAndUnorderedAccessViews: *c_void,
OMGetBlendState: *c_void,
OMGetDepthStencilState: *c_void,
SOGetTargets: *c_void,
RSGetState: *c_void,
RSGetViewports: *c_void,
RSGetScissorRects: *c_void,
HSGetShaderResources: *c_void,
HSGetShader: *c_void,
HSGetSamplers: *c_void,
HSGetConstantBuffers: *c_void,
DSGetShaderResources: *c_void,
DSGetShader: *c_void,
DSGetSamplers: *c_void,
DSGetConstantBuffers: *c_void,
CSGetShaderResources: *c_void,
CSGetUnorderedAccessViews: *c_void,
CSGetShader: *c_void,
CSGetSamplers: *c_void,
CSGetConstantBuffers: *c_void,
ClearState: *c_void,
Flush: fn (*Self) callconv(.C) void,
GetType: *c_void,
GetContextFlags: *c_void,
FinishCommandList: *c_void,
},
usingnamespace os.IUnknown.Methods(Self);
usingnamespace IDeviceContext.Methods(Self);
fn Methods(comptime T: type) type {
return extern struct {
pub inline fn Flush(self: *T) void {
self.vtbl.Flush(self);
}
};
}
};
pub const RESOURCE_FLAGS_11ON12 = extern struct {
BindFlags: u32 = 0x20, // D3D11_BIND_RENDER_TARGET
MiscFlags: u32 = 0,
CPUAccessFlags: u32 = 0,
StructureByteStride: u32 = 0,
};
pub const I11On12Device = extern struct {
const Self = @This();
vtbl: *const extern struct {
// IUnknown
QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT,
AddRef: fn (*Self) callconv(.C) u32,
Release: fn (*Self) callconv(.C) u32,
// ID3D11On12Device
CreateWrappedResource: fn (
*Self,
*os.IUnknown,
*const RESOURCE_FLAGS_11ON12,
RESOURCE_STATES,
RESOURCE_STATES,
*const os.GUID,
**c_void,
) callconv(.C) HRESULT,
ReleaseWrappedResources: fn (*Self, [*]const *IResource, u32) callconv(.C) void,
AcquireWrappedResources: fn (*Self, [*]const *IResource, u32) callconv(.C) void,
},
usingnamespace os.IUnknown.Methods(Self);
usingnamespace I11On12Device.Methods(Self);
fn Methods(comptime T: type) type {
return extern struct {
pub inline fn CreateWrappedResource(
self: *T,
resource12: *os.IUnknown,
flags11: *const RESOURCE_FLAGS_11ON12,
in_state: RESOURCE_STATES,
out_state: RESOURCE_STATES,
guid: *const os.GUID,
resource11: **c_void,
) HRESULT {
return self.vtbl.CreateWrappedResource(
self,
resource12,
flags11,
in_state,
out_state,
guid,
resource11,
);
}
pub inline fn ReleaseWrappedResources(
self: *T,
resources: [*]const *IResource,
num_resources: u32,
) void {
self.vtbl.ReleaseWrappedResources(self, resources, num_resources);
}
pub inline fn AcquireWrappedResources(
self: *T,
resources: [*]const *IResource,
num_resources: u32,
) void {
self.vtbl.AcquireWrappedResources(self, resources, num_resources);
}
};
}
};
pub const IID_IResource = os.GUID{
.Data1 = 0xdc8e63f3,
.Data2 = 0xd12b,
.Data3 = 0x4952,
.Data4 = .{ 0xb4, 0x7b, 0x5e, 0x45, 0x02, 0x6a, 0x86, 0x2d },
};
pub const IID_I11On12Device = os.GUID{
.Data1 = 0x85611e73,
.Data2 = 0x70a9,
.Data3 = 0x490e,
.Data4 = .{ 0x96, 0x14, 0xa9, 0xe3, 0x02, 0x77, 0x79, 0x04 },
};
pub var Create11On12Device: fn (
*os.IUnknown,
CREATE_DEVICE_FLAG,
?[*]const dcommon.FEATURE_LEVEL,
u32,
[*]const *os.IUnknown,
u32,
u32,
?**IDevice,
?**IDeviceContext,
?*dcommon.FEATURE_LEVEL,
) callconv(.C) HRESULT = undefined;
pub fn init() void {
// TODO: Handle error.
var d3d11_dll = os.LoadLibraryA("d3d11.dll").?;
Create11On12Device = @ptrCast(
@TypeOf(Create11On12Device),
os.kernel32.GetProcAddress(d3d11_dll, "D3D11On12CreateDevice").?,
);
} | src/windows/d3d11.zig |
const builtin = @import("builtin");
const mem = @import("std").mem;
const assert = @import("std").debug.assert;
const crypto = @import("std").crypto;
const testing = @import("std").testing;
pub const Format = enum {
Bare,
Dashed,
Braced,
};
pub const Case = enum {
Lower,
Upper,
};
const GUIDBuilder = struct {
bytes: [16]u8,
first_nibble: ?u8 = null,
pointer: usize = 0,
const Self = @This();
pub inline fn init() Self {
return Self{ .bytes = undefined };
}
inline fn pushNibble(self: *Self, nib: u8) void {
assert(self.pointer < 16);
assert(nib <= 0xF);
if (self.first_nibble) |val| {
self.bytes[self.pointer] = val * 16 + nib;
self.pointer += 1;
self.first_nibble = null;
} else {
self.first_nibble = nib;
}
}
pub inline fn build(self: *const Self) GUID {
assert(self.pointer == 16);
return GUID.fromBytes(self.bytes);
}
inline fn parseUnbraced(comptime format: Format, string: []const u8) !GUID {
var builder = GUIDBuilder.init();
for (string) |c, i| {
switch (c) {
'A'...'F' => builder.pushNibble(c - 'A' + 10),
'a'...'f' => builder.pushNibble(c - 'a' + 10),
'0'...'9' => builder.pushNibble(c - '0'),
'-' => {
if (format == .Bare) {
return error.UnexpectedDash;
}
if (i != 8 and i != 13 and i != 18 and i != 23) {
return error.UnexpectedDash;
}
},
else => return error.UnexpectedCharacter,
}
}
return builder.build();
}
};
fn StringBuilder(comptime format: Format, comptime case: Case) type {
const len = switch (format) {
.Bare => 32,
.Dashed => 36,
.Braced => 38,
};
return struct {
string: []u8,
pointer: usize = 0,
const Self = @This();
pub fn init(buffer: []u8) !Self {
if (buffer.len < len) {
return error.BufferTooSmall;
}
var self = Self{ .string = buffer };
if (format == .Braced) {
self.string[0] = '{';
self.pointer += 1;
}
return self;
}
fn pushNibble(self: *Self, nib: u8) void {
const char = switch (nib) {
0...9 => '0' + nib,
0xA...0xF => if (case == Case.Lower) 'a' + nib - 10 else 'A' + nib - 10,
else => unreachable,
};
self.string[self.pointer] = char;
self.pointer += 1;
}
pub fn pushByte(self: *Self, byte: u8) void {
self.pushNibble((byte & 0xF0) >> 4);
self.pushNibble(byte & 0x0F);
const char: ?u8 = if (format == .Braced) switch (self.pointer) {
9, 14, 19, 24 => @as(u8, '-'),
len - 1 => @as(u8, '}'),
else => null,
} else if (format == .Dashed) switch (self.pointer) {
8, 13, 18, 23 => @as(u8, '-'),
else => null,
} else null;
if (char) |c| {
self.string[self.pointer] = c;
self.pointer += 1;
}
}
pub fn build(self: *const Self) []u8 {
assert(self.pointer == len);
return self.string;
}
};
}
/// A winapi-compatible GUID.
pub const GUID = packed struct {
Data1: u32,
Data2: u16,
Data3: u16,
Data4: [8]u8,
const Self = @This();
/// Does this GUID equal the other GUID?
pub inline fn eq(self: *const Self, other: *const Self) bool {
return mem.eql(u8, @ptrCast(*const [16]u8, self), @ptrCast(*const [16]u8, other));
}
/// Initialize a null GUID (all zeroes).
pub fn nil() Self {
return Self.from("00000000-0000-0000-0000-000000000000");
}
pub fn v4() !Self {
var bytes: [16]u8 = undefined;
try crypto.randomBytes(bytes[0..]);
return Self.fromBytes(bytes);
}
/// Initialize a GUID from a byte array.
pub fn fromBytes(bytes: [16]u8) Self {
return @bitCast(Self, bytes);
}
/// Get the GUID data as a byte array.
pub fn asBytes(self: *const Self) *const [16]u8 {
return @ptrCast(*const [16]u8, self);
}
/// Parse a GUID string at runtime.
/// It can be any of the three forms:
/// - Bare: 12345678ABCDEFEF90901234567890AB
/// - Dashed: 12345678-ABCD-EFEF-9090-1234567890AB
/// - Braced: {12345678-ABCD-EFEF-9090-1234567890AB}
pub fn parse(string: []const u8) !Self {
if (string.len == 38) return Self.parseBraced(string);
if (string.len == 36) return Self.parseDashed(string);
if (string.len == 32) return Self.parseBare(string);
return error.UnsupportedFormat;
}
/// Parse a braced GUID, of the form: "{12345678-ABCD-EFEF-9090-1234567890AB}"
pub fn parseBraced(string: []const u8) !Self {
if (string.len != 38) return error.IncorrectLength;
return Self.parseDashed(string[1..37]);
}
/// Parse a dashed GUID, of the form: "12345678-ABCD-EFEF-9090-1234567890AB"
pub fn parseDashed(string: []const u8) !Self {
if (string.len != 36) return error.IncorrectLength;
return GUIDBuilder.parseUnbraced(.Dashed, string);
}
/// Parse a bare GUID, of the form: "12345678ABCDEFEF90901234567890AB"
pub fn parseBare(string: []const u8) !Self {
if (string.len != 32) return error.IncorrectLength;
return GUIDBuilder.parseUnbraced(.Bare, string);
}
/// Create a GUID at compile time.
/// It can be any of the three forms:
/// - Bare: 12345678ABCDEFEF90901234567890AB
/// - Dashed: 12345678-ABCD-EFEF-9090-1234567890AB
/// - Braced: {12345678-ABCD-EFEF-9090-1234567890AB}
pub fn from(comptime string: []const u8) Self {
comptime var actual_string = string;
if (string.len == 38) {
actual_string = string[1..37];
}
const format = if (actual_string.len == 36) .Dashed else .Bare;
if (format == .Bare) {
assert(actual_string.len == 32);
}
return GUIDBuilder.parseUnbraced(format, actual_string) catch unreachable;
}
pub fn toString(self: *const Self, buffer: []u8, comptime format: Format, comptime case: Case) ![]u8 {
var builder = try StringBuilder(format, case).init(buffer);
for (self.asBytes()) |byte| {
builder.pushByte(byte);
}
return builder.build();
}
};
test "nil equals nil" {
testing.expect(GUID.nil().eq(&GUID.nil()));
}
test "compile time and runtime parsing" {
testing.expect(GUID.from("12345678-ABCD-EFEF-9090-1234567890AB").eq(&try GUID.parse("12345678-ABCD-EFEF-9090-1234567890AB")));
testing.expect(GUID.from("12345678-ABCD-EFEF-9090-1234567890AB").eq(&try GUID.parse("{12345678-ABCD-EFEF-9090-1234567890AB}")));
testing.expect(GUID.from("{12345678-ABCD-EFEF-9090-1234567890AB}").eq(&try GUID.parse("12345678ABCDEFEF90901234567890AB")));
testing.expect(GUID.from("12345678ABCDEFEF90901234567890AB").eq(&try GUID.parse("12345678-ABCD-EFEF-9090-1234567890AB")));
}
test "to string" {
var buffer = [_]u8{0} ** 38;
const guid = GUID.from("12345678-ABCD-EFEF-9090-1234567890AB");
var str = try guid.toString(buffer[0..], .Dashed, .Upper);
testing.expectEqualSlices(u8, "12345678-ABCD-EFEF-9090-1234567890AB", str[0..36]);
str = try guid.toString(buffer[0..], .Braced, .Lower);
testing.expectEqualSlices(u8, "{12345678-abcd-efef-9090-1234567890ab}", str);
}
test "parse error" {
testing.expectError(error.UnexpectedCharacter, GUID.parse("nothexad-ABCD-EFEF-9090-1234567890AB"));
testing.expectError(error.UnexpectedDash, GUID.parse("1234-678-ABCD-EFEF-9090-1234567890AB"));
} | src/guid.zig |
const std = @import("std");
const protobuf = @import("protobuf");
usingnamespace protobuf;
usingnamespace std;
const expected = @embedFile("encode_alltypes.output");
const SubMessage = struct {
substuff1: ArrayList(u8),
substuff2: ?i32,
substuff3: ?i32,
pub const _desc_table = [_]FieldDescriptor{
fd( 1, "substuff1" , .{.List = .FixedInt}),
fd( 2, "substuff2" , .{.Varint = .Simple}),
fd( 3, "substuff3" , .FixedInt),
};
pub fn encode(self: SubMessage, allocator: *mem.Allocator) ![]u8 {
return pb_encode(self, allocator);
}
pub fn deinit(self: SubMessage) void {
pb_deinit(self);
}
pub fn init(allocator: *mem.Allocator) SubMessage {
return pb_init(SubMessage, allocator);
}
};
const EmptyMessage = struct {
pub const _desc_table = [_]FieldDescriptor{};
pub fn encode(self: EmptyMessage, allocator: *mem.Allocator) ![]u8 {
return pb_encode(self, allocator);
}
pub fn deinit(self: EmptyMessage) void {
pb_deinit(self);
}
pub fn init(allocator: *mem.Allocator) EmptyMessage {
return pb_init(EmptyMessage, allocator);
}
};
const DemoEnum = enum(i32) {
HE_Zero = 0,
Negative = -2147483647,
Positive = 2147483647
};
const Limits = struct {
int32_min : ?i32,
int32_max : ?i32,
uint32_min : ?u32,
uint32_max : ?u32,
int64_min : ?i64,
int64_max : ?i64,
uint64_min : ?u64,
uint64_max : ?u64,
enum_min : ?HugeEnum,
enum_max : ?HugeEnum,
pub const _desc_table = [_]FieldDescriptor{
fd( 1, "int32_min" , .{.Varint = .Simple}),
fd( 2, "int32_max" , .{.Varint = .Simple}),
fd( 3, "uint32_min" , .{.Varint = .Simple}),
fd( 4, "uint32_max" , .{.Varint = .Simple}),
fd( 5, "int64_min" , .{.Varint = .Simple}),
fd( 6, "int64_max" , .{.Varint = .Simple}),
fd( 7, "uint64_min" , .{.Varint = .Simple}),
fd( 8, "uint64_max" , .{.Varint = .Simple}),
fd( 9, "enum_min" , .{.Varint = .Simple}),
fd( 10, "enum_max" , .{.Varint = .Simple}),
};
pub fn encode(self: Limits, allocator: *mem.Allocator) ![]u8 {
return pb_encode(self, allocator);
}
pub fn deinit(self: Limits) void {
pb_deinit(self);
}
pub fn init(allocator: *mem.Allocator) Limits {
return pb_init(Limits, allocator);
}
};
const MyEnum = enum(type) {
Zero = 0,
First = 1,
Second = 2,
Truth = 42,
};
const AllTypes = struct {
};
test "alltypes " {
//todo!
} | tests/alltypes.zig |
const std = @import("std");
const clap = @import("clap");
const xml = @import("xml.zig");
const svd = @import("svd.zig");
const Database = @import("Database.zig");
const ArenaAllocator = std.heap.ArenaAllocator;
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
pub const log_level: std.log.Level = .info;
const svd_schema = @embedFile("cmsis-svd.xsd");
const params = [_]clap.Param(clap.Help){
clap.parseParam("-h, --help Display this help and exit") catch unreachable,
clap.parseParam("-s, --schema <str> Explicitly set schema type, one of: svd, atdf, json") catch unreachable,
clap.parseParam("-o, --output_path <str> Write to a file") catch unreachable,
clap.parseParam("<str>...") catch unreachable,
};
pub fn main() !void {
mainImpl() catch |err| switch (err) {
error.Explained => std.process.exit(1),
else => return err,
};
}
const Schema = enum {
atdf,
dslite,
json,
svd,
xml,
};
fn mainImpl() anyerror!void {
defer xml.cleanupParser();
var gpa = std.heap.GeneralPurposeAllocator(.{
.stack_trace_frames = 20,
}){};
const allocator = gpa.allocator();
defer _ = gpa.deinit();
var arena = ArenaAllocator.init(allocator);
defer arena.deinit();
var diag = clap.Diagnostic{};
var res = clap.parse(clap.Help, ¶ms, clap.parsers.default, .{ .diagnostic = &diag }) catch |err| {
// Report useful error and exit
diag.report(std.io.getStdErr().writer(), err) catch {};
return error.Explained;
};
defer res.deinit();
if (res.args.help)
return clap.help(std.io.getStdErr().writer(), clap.Help, ¶ms);
var schema: ?Schema = if (res.args.schema) |schema_str|
if (std.meta.stringToEnum(Schema, schema_str)) |s| s else {
std.log.err("Unknown schema type: {s}, must be one of: svd, atdf, json", .{schema_str});
return error.Explained;
}
else
null;
var db = switch (res.positionals.len) {
0 => blk: {
if (schema == null) {
std.log.err("schema must be chosen when reading from stdin", .{});
return error.Explained;
}
if (schema.? == .json) {
return error.Todo;
}
var stdin = std.io.getStdIn().reader();
const doc: *xml.Doc = xml.readIo(readFn, null, &stdin, null, null, 0) orelse return error.ReadXmlFd;
defer xml.freeDoc(doc);
break :blk try parseXmlDatabase(allocator, doc, schema.?);
},
1 => blk: {
// if schema is null, then try to determine using file extension
if (schema == null) {
const ext = std.fs.path.extension(res.positionals[0]);
if (ext.len > 0) {
schema = std.meta.stringToEnum(Schema, ext[1..]) orelse {
std.log.err("unable to determine schema from file extension of '{s}'", .{res.positionals[0]});
return error.Explained;
};
}
}
// schema is guaranteed to be non-null from this point on
if (schema.? == .json) {
return error.Todo;
}
// all other schema types are xml based
const doc: *xml.Doc = xml.readFile(res.positionals[0].ptr, null, 0) orelse return error.ReadXmlFile;
defer xml.freeDoc(doc);
break :blk try parseXmlDatabase(allocator, doc, schema.?);
},
else => {
std.log.err("this program takes max one positional argument for now", .{});
return error.Explained;
},
};
defer db.deinit();
const writer = if (res.args.output_path) |output_path|
if (std.fs.path.isAbsolute(output_path)) writer: {
if (std.fs.path.dirname(output_path)) |dirname| {
_ = dirname;
// TODO: recursively create absolute path if it doesn't exist
}
break :writer (try std.fs.createFileAbsolute(output_path, .{})).writer();
} else writer: {
if (std.fs.path.dirname(output_path)) |dirname|
try std.fs.cwd().makePath(dirname);
break :writer (try std.fs.cwd().createFile(output_path, .{})).writer();
}
else
std.io.getStdOut().writer();
try db.toZig(writer);
}
fn readFn(ctx: ?*anyopaque, buffer: ?[*]u8, len: c_int) callconv(.C) c_int {
if (buffer == null)
return -1;
return if (ctx) |c| blk: {
const reader = @ptrCast(*std.fs.File.Reader, @alignCast(@alignOf(*std.fs.File.Reader), c));
const n = reader.read(buffer.?[0..@intCast(usize, len)]) catch return -1;
break :blk @intCast(c_int, n);
} else -1;
}
fn parseXmlDatabase(allocator: Allocator, doc: *xml.Doc, schema: Schema) !Database {
return switch (schema) {
.json => unreachable,
.atdf => try Database.initFromAtdf(allocator, doc),
.svd => try Database.initFromSvd(allocator, doc),
.dslite => return error.Todo,
.xml => determine_type: {
const root_element: *xml.Node = xml.docGetRootElement(doc) orelse return error.NoRoot;
if (xml.findValueForKey(root_element, "device") != null)
break :determine_type try Database.initFromSvd(allocator, doc)
else if (xml.findValueForKey(root_element, "avr-tools-device-file") != null)
break :determine_type try Database.initFromAtdf(allocator, doc)
else {
std.log.err("unable do detect register schema type", .{});
return error.Explained;
}
},
};
} | src/main.zig |
const std = @import("std");
const upaya = @import("upaya.zig");
usingnamespace upaya.sokol;
pub const Texture = extern struct {
img: upaya.sokol.sg_image = undefined,
width: i32 = 0,
height: i32 = 0,
pub const Filter = enum { linear, nearest };
pub const Wrap = enum { clamp, repeat };
pub fn initOffscreen(width: i32, height: i32, filter: Filter) Texture {
var img_desc = std.mem.zeroes(sg_image_desc);
img_desc.render_target = true;
img_desc.width = width;
img_desc.height = height;
img_desc.pixel_format = .SG_PIXELFORMAT_RGBA8;
img_desc.min_filter = if (filter == .linear) .SG_FILTER_LINEAR else .SG_FILTER_NEAREST;
img_desc.mag_filter = if (filter == .linear) .SG_FILTER_LINEAR else .SG_FILTER_NEAREST;
return .{ .width = width, .height = height, .img = sg_make_image(&img_desc) };
}
pub fn init(width: i32, height: i32, filter: Filter) Texture {
var img_desc = std.mem.zeroes(sg_image_desc);
img_desc.width = width;
img_desc.height = height;
img_desc.pixel_format = .SG_PIXELFORMAT_RGBA8;
img_desc.wrap_u = .SG_WRAP_CLAMP_TO_EDGE;
img_desc.wrap_v = .SG_WRAP_CLAMP_TO_EDGE;
img_desc.min_filter = if (filter == .linear) .SG_FILTER_LINEAR else .SG_FILTER_NEAREST;
img_desc.mag_filter = if (filter == .linear) .SG_FILTER_LINEAR else .SG_FILTER_NEAREST;
img_desc.content.subimage[0][0].size = width * height * 4 * @sizeOf(u8);
return .{ .width = width, .height = height, .img = sg_make_image(&img_desc) };
}
pub fn initTransparent(width: i32, height: i32) Texture {
var img = upaya.Image.init(@intCast(usize, width), @intCast(usize, height));
img.fillRect(.{ .width = width, .height = height }, upaya.math.Color.transparent);
return img.asTexture(.nearest);
}
pub fn initWithData(pixels: []u8, width: i32, height: i32, filter: Filter) Texture {
var img_desc = std.mem.zeroes(sg_image_desc);
img_desc.width = width;
img_desc.height = height;
img_desc.pixel_format = .SG_PIXELFORMAT_RGBA8;
img_desc.wrap_u = .SG_WRAP_CLAMP_TO_EDGE;
img_desc.wrap_v = .SG_WRAP_CLAMP_TO_EDGE;
img_desc.min_filter = if (filter == .linear) .SG_FILTER_LINEAR else .SG_FILTER_NEAREST;
img_desc.mag_filter = if (filter == .linear) .SG_FILTER_LINEAR else .SG_FILTER_NEAREST;
img_desc.data.subimage[0][0].ptr = pixels.ptr;
img_desc.data.subimage[0][0].size = @intCast(usize, width * height * 4 * @sizeOf(u8));
img_desc.label = "upaya-texture";
return .{ .width = width, .height = height, .img = sg_make_image(&img_desc) };
}
pub fn initWithColorData(pixels: []u32, width: i32, height: i32, filter: Filter, wrap: Wrap) Texture {
var img_desc = std.mem.zeroes(sg_image_desc);
img_desc.width = width;
img_desc.height = height;
img_desc.pixel_format = .SG_PIXELFORMAT_RGBA8;
img_desc.wrap_u = if (wrap == .clamp) .SG_WRAP_CLAMP_TO_EDGE else .SG_WRAP_REPEAT;
img_desc.wrap_v = if (wrap == .clamp) .SG_WRAP_CLAMP_TO_EDGE else .SG_WRAP_REPEAT;
img_desc.min_filter = if (filter == .linear) .SG_FILTER_LINEAR else .SG_FILTER_NEAREST;
img_desc.mag_filter = if (filter == .linear) .SG_FILTER_LINEAR else .SG_FILTER_NEAREST;
//img_desc.data.subimage[0][0].ptr = pixels.ptr;
//img_desc.data.subimage[0][0].size = @intCast(usize, width * height * @sizeOf(u32));
img_desc.label = "upaya-texture";
img_desc.usage = .SG_USAGE_DYNAMIC;
var img = sg_make_image(&img_desc);
var img_data: sg_image_data = std.mem.zeroes(sg_image_data);
img_data.subimage[0][0].ptr = pixels.ptr;
img_data.subimage[0][0].size = @intCast(usize, width * height * @sizeOf(u32));
sg_update_image(img, &img_data);
return .{ .width = width, .height = height, .img = img };
}
pub fn initFromFile(file: []const u8, filter: Filter) !Texture {
const image_contents = try upaya.fs.read(upaya.mem.tmp_allocator, file);
var w: c_int = undefined;
var h: c_int = undefined;
var channels: c_int = undefined;
const load_res = upaya.stb.stbi_load_from_memory(image_contents.ptr, @intCast(c_int, image_contents.len), &w, &h, &channels, 4);
if (load_res == null) return error.ImageLoadFailed;
defer upaya.stb.stbi_image_free(load_res);
return Texture.initWithData(load_res[0..@intCast(usize, w * h * channels)], w, h, filter);
}
pub fn initChecker(width: i32, height: i32, color1: upaya.math.Color, color2: upaya.math.Color) Texture {
var img = upaya.Image.init(@intCast(usize, width), @intCast(usize, height));
img.fillRect(.{ .width = width, .height = height }, color1);
var y: usize = 0;
while (y < img.h) : (y += 1) {
var row = img.pixels[y * img.w .. (y * img.w) + img.w];
for (row) |_, i| {
if (y % 2 == 0) {
if (i % 2 != 0) {
row[i] = color2.value;
}
} else {
if (i % 2 == 0) {
row[i] = color2.value;
}
}
}
}
return img.asTexture(.nearest);
}
pub fn deinit(self: Texture) void {
sg_destroy_image(self.img);
}
pub fn setData(self: Texture, pixels: []u8) void {
_ = self;
_ = pixels;
std.debug.panic("not implemented\n", .{});
// aya.gfx.device.setTextureData2D(self.tex, .color, 0, 0, self.width, self.height, 0, &data[0], @intCast(i32, data.len));
}
pub fn setColorData(self: Texture, pixels: []u32) void {
//std.debug.panic("not implemented\n", .{});
var data: sg_image_data = std.mem.zeroes(sg_image_data);
data.subimage[0][0].ptr = pixels.ptr;
data.subimage[0][0].size = @intCast(usize, self.width * self.height * @sizeOf(u32));
sg_update_image(self.img, &data);
}
pub fn imTextureID(self: Texture) upaya.imgui.ImTextureID {
return @intToPtr(*c_void, self.img.id);
}
/// returns true if the image was loaded successfully
pub fn getTextureSize(file: []const u8, w: *c_int, h: *c_int) bool {
const image_contents = upaya.fs.read(upaya.mem.tmp_allocator, file) catch unreachable;
var comp: c_int = undefined;
if (upaya.stb.stbi_info_from_memory(image_contents.ptr, @intCast(c_int, image_contents.len), w, h, &comp) == 1) {
return true;
}
return false;
}
}; | src/texture.zig |
pub const EVT_VARIANT_TYPE_MASK = @as(u32, 127);
pub const EVT_VARIANT_TYPE_ARRAY = @as(u32, 128);
pub const EVT_READ_ACCESS = @as(u32, 1);
pub const EVT_WRITE_ACCESS = @as(u32, 2);
pub const EVT_CLEAR_ACCESS = @as(u32, 4);
pub const EVT_ALL_ACCESS = @as(u32, 7);
//--------------------------------------------------------------------------------
// Section: Types (34)
//--------------------------------------------------------------------------------
pub const REPORT_EVENT_TYPE = enum(u16) {
SUCCESS = 0,
AUDIT_FAILURE = 16,
AUDIT_SUCCESS = 8,
ERROR_TYPE = 1,
INFORMATION_TYPE = 4,
WARNING_TYPE = 2,
};
pub const EVENTLOG_SUCCESS = REPORT_EVENT_TYPE.SUCCESS;
pub const EVENTLOG_AUDIT_FAILURE = REPORT_EVENT_TYPE.AUDIT_FAILURE;
pub const EVENTLOG_AUDIT_SUCCESS = REPORT_EVENT_TYPE.AUDIT_SUCCESS;
pub const EVENTLOG_ERROR_TYPE = REPORT_EVENT_TYPE.ERROR_TYPE;
pub const EVENTLOG_INFORMATION_TYPE = REPORT_EVENT_TYPE.INFORMATION_TYPE;
pub const EVENTLOG_WARNING_TYPE = REPORT_EVENT_TYPE.WARNING_TYPE;
pub const READ_EVENT_LOG_READ_FLAGS = enum(u32) {
EK_READ = 2,
QUENTIAL_READ = 1,
};
pub const EVENTLOG_SEEK_READ = READ_EVENT_LOG_READ_FLAGS.EK_READ;
pub const EVENTLOG_SEQUENTIAL_READ = READ_EVENT_LOG_READ_FLAGS.QUENTIAL_READ;
// TODO: this type has a FreeFunc 'CloseEventLog', what can Zig do with this information?
pub const EventLogHandle = isize;
// TODO: this type has a FreeFunc 'DeregisterEventSource', what can Zig do with this information?
pub const EventSourceHandle = isize;
pub const EVT_VARIANT_TYPE = enum(i32) {
Null = 0,
String = 1,
AnsiString = 2,
SByte = 3,
Byte = 4,
Int16 = 5,
UInt16 = 6,
Int32 = 7,
UInt32 = 8,
Int64 = 9,
UInt64 = 10,
Single = 11,
Double = 12,
Boolean = 13,
Binary = 14,
Guid = 15,
SizeT = 16,
FileTime = 17,
SysTime = 18,
Sid = 19,
HexInt32 = 20,
HexInt64 = 21,
EvtHandle = 32,
EvtXml = 35,
};
pub const EvtVarTypeNull = EVT_VARIANT_TYPE.Null;
pub const EvtVarTypeString = EVT_VARIANT_TYPE.String;
pub const EvtVarTypeAnsiString = EVT_VARIANT_TYPE.AnsiString;
pub const EvtVarTypeSByte = EVT_VARIANT_TYPE.SByte;
pub const EvtVarTypeByte = EVT_VARIANT_TYPE.Byte;
pub const EvtVarTypeInt16 = EVT_VARIANT_TYPE.Int16;
pub const EvtVarTypeUInt16 = EVT_VARIANT_TYPE.UInt16;
pub const EvtVarTypeInt32 = EVT_VARIANT_TYPE.Int32;
pub const EvtVarTypeUInt32 = EVT_VARIANT_TYPE.UInt32;
pub const EvtVarTypeInt64 = EVT_VARIANT_TYPE.Int64;
pub const EvtVarTypeUInt64 = EVT_VARIANT_TYPE.UInt64;
pub const EvtVarTypeSingle = EVT_VARIANT_TYPE.Single;
pub const EvtVarTypeDouble = EVT_VARIANT_TYPE.Double;
pub const EvtVarTypeBoolean = EVT_VARIANT_TYPE.Boolean;
pub const EvtVarTypeBinary = EVT_VARIANT_TYPE.Binary;
pub const EvtVarTypeGuid = EVT_VARIANT_TYPE.Guid;
pub const EvtVarTypeSizeT = EVT_VARIANT_TYPE.SizeT;
pub const EvtVarTypeFileTime = EVT_VARIANT_TYPE.FileTime;
pub const EvtVarTypeSysTime = EVT_VARIANT_TYPE.SysTime;
pub const EvtVarTypeSid = EVT_VARIANT_TYPE.Sid;
pub const EvtVarTypeHexInt32 = EVT_VARIANT_TYPE.HexInt32;
pub const EvtVarTypeHexInt64 = EVT_VARIANT_TYPE.HexInt64;
pub const EvtVarTypeEvtHandle = EVT_VARIANT_TYPE.EvtHandle;
pub const EvtVarTypeEvtXml = EVT_VARIANT_TYPE.EvtXml;
pub const EVT_VARIANT = extern struct {
Anonymous: extern union {
BooleanVal: BOOL,
SByteVal: i8,
Int16Val: i16,
Int32Val: i32,
Int64Val: i64,
ByteVal: u8,
UInt16Val: u16,
UInt32Val: u32,
UInt64Val: u64,
SingleVal: f32,
DoubleVal: f64,
FileTimeVal: u64,
SysTimeVal: ?*SYSTEMTIME,
GuidVal: ?*Guid,
StringVal: ?[*:0]const u16,
AnsiStringVal: ?[*:0]const u8,
BinaryVal: ?*u8,
SidVal: ?PSID,
SizeTVal: usize,
BooleanArr: ?*BOOL,
SByteArr: ?*i8,
Int16Arr: ?*i16,
Int32Arr: ?*i32,
Int64Arr: ?*i64,
ByteArr: ?*u8,
UInt16Arr: ?*u16,
UInt32Arr: ?*u32,
UInt64Arr: ?*u64,
SingleArr: ?*f32,
DoubleArr: ?*f64,
FileTimeArr: ?*FILETIME,
SysTimeArr: ?*SYSTEMTIME,
GuidArr: ?*Guid,
StringArr: ?*?PWSTR,
AnsiStringArr: ?*?PSTR,
SidArr: ?*?PSID,
SizeTArr: ?*usize,
EvtHandleVal: isize,
XmlVal: ?[*:0]const u16,
XmlValArr: ?*?PWSTR,
},
Count: u32,
Type: u32,
};
pub const EVT_LOGIN_CLASS = enum(i32) {
n = 1,
};
pub const EvtRpcLogin = EVT_LOGIN_CLASS.n;
pub const EVT_RPC_LOGIN_FLAGS = enum(i32) {
Default = 0,
Negotiate = 1,
Kerberos = 2,
NTLM = 3,
};
pub const EvtRpcLoginAuthDefault = EVT_RPC_LOGIN_FLAGS.Default;
pub const EvtRpcLoginAuthNegotiate = EVT_RPC_LOGIN_FLAGS.Negotiate;
pub const EvtRpcLoginAuthKerberos = EVT_RPC_LOGIN_FLAGS.Kerberos;
pub const EvtRpcLoginAuthNTLM = EVT_RPC_LOGIN_FLAGS.NTLM;
pub const EVT_RPC_LOGIN = extern struct {
Server: ?PWSTR,
User: ?PWSTR,
Domain: ?PWSTR,
Password: <PASSWORD>,
Flags: u32,
};
pub const EVT_QUERY_FLAGS = enum(i32) {
ChannelPath = 1,
FilePath = 2,
ForwardDirection = 256,
ReverseDirection = 512,
TolerateQueryErrors = 4096,
};
pub const EvtQueryChannelPath = EVT_QUERY_FLAGS.ChannelPath;
pub const EvtQueryFilePath = EVT_QUERY_FLAGS.FilePath;
pub const EvtQueryForwardDirection = EVT_QUERY_FLAGS.ForwardDirection;
pub const EvtQueryReverseDirection = EVT_QUERY_FLAGS.ReverseDirection;
pub const EvtQueryTolerateQueryErrors = EVT_QUERY_FLAGS.TolerateQueryErrors;
pub const EVT_SEEK_FLAGS = enum(i32) {
RelativeToFirst = 1,
RelativeToLast = 2,
RelativeToCurrent = 3,
RelativeToBookmark = 4,
OriginMask = 7,
Strict = 65536,
};
pub const EvtSeekRelativeToFirst = EVT_SEEK_FLAGS.RelativeToFirst;
pub const EvtSeekRelativeToLast = EVT_SEEK_FLAGS.RelativeToLast;
pub const EvtSeekRelativeToCurrent = EVT_SEEK_FLAGS.RelativeToCurrent;
pub const EvtSeekRelativeToBookmark = EVT_SEEK_FLAGS.RelativeToBookmark;
pub const EvtSeekOriginMask = EVT_SEEK_FLAGS.OriginMask;
pub const EvtSeekStrict = EVT_SEEK_FLAGS.Strict;
pub const EVT_SUBSCRIBE_FLAGS = enum(i32) {
ToFutureEvents = 1,
StartAtOldestRecord = 2,
StartAfterBookmark = 3,
// OriginMask = 3, this enum value conflicts with StartAfterBookmark
TolerateQueryErrors = 4096,
Strict = 65536,
};
pub const EvtSubscribeToFutureEvents = EVT_SUBSCRIBE_FLAGS.ToFutureEvents;
pub const EvtSubscribeStartAtOldestRecord = EVT_SUBSCRIBE_FLAGS.StartAtOldestRecord;
pub const EvtSubscribeStartAfterBookmark = EVT_SUBSCRIBE_FLAGS.StartAfterBookmark;
pub const EvtSubscribeOriginMask = EVT_SUBSCRIBE_FLAGS.StartAfterBookmark;
pub const EvtSubscribeTolerateQueryErrors = EVT_SUBSCRIBE_FLAGS.TolerateQueryErrors;
pub const EvtSubscribeStrict = EVT_SUBSCRIBE_FLAGS.Strict;
pub const EVT_SUBSCRIBE_NOTIFY_ACTION = enum(i32) {
Error = 0,
Deliver = 1,
};
pub const EvtSubscribeActionError = EVT_SUBSCRIBE_NOTIFY_ACTION.Error;
pub const EvtSubscribeActionDeliver = EVT_SUBSCRIBE_NOTIFY_ACTION.Deliver;
pub const EVT_SUBSCRIBE_CALLBACK = fn(
Action: EVT_SUBSCRIBE_NOTIFY_ACTION,
UserContext: ?*anyopaque,
Event: isize,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const EVT_SYSTEM_PROPERTY_ID = enum(i32) {
ProviderName = 0,
ProviderGuid = 1,
EventID = 2,
Qualifiers = 3,
Level = 4,
Task = 5,
Opcode = 6,
Keywords = 7,
TimeCreated = 8,
EventRecordId = 9,
ActivityID = 10,
RelatedActivityID = 11,
ProcessID = 12,
ThreadID = 13,
Channel = 14,
Computer = 15,
UserID = 16,
Version = 17,
PropertyIdEND = 18,
};
pub const EvtSystemProviderName = EVT_SYSTEM_PROPERTY_ID.ProviderName;
pub const EvtSystemProviderGuid = EVT_SYSTEM_PROPERTY_ID.ProviderGuid;
pub const EvtSystemEventID = EVT_SYSTEM_PROPERTY_ID.EventID;
pub const EvtSystemQualifiers = EVT_SYSTEM_PROPERTY_ID.Qualifiers;
pub const EvtSystemLevel = EVT_SYSTEM_PROPERTY_ID.Level;
pub const EvtSystemTask = EVT_SYSTEM_PROPERTY_ID.Task;
pub const EvtSystemOpcode = EVT_SYSTEM_PROPERTY_ID.Opcode;
pub const EvtSystemKeywords = EVT_SYSTEM_PROPERTY_ID.Keywords;
pub const EvtSystemTimeCreated = EVT_SYSTEM_PROPERTY_ID.TimeCreated;
pub const EvtSystemEventRecordId = EVT_SYSTEM_PROPERTY_ID.EventRecordId;
pub const EvtSystemActivityID = EVT_SYSTEM_PROPERTY_ID.ActivityID;
pub const EvtSystemRelatedActivityID = EVT_SYSTEM_PROPERTY_ID.RelatedActivityID;
pub const EvtSystemProcessID = EVT_SYSTEM_PROPERTY_ID.ProcessID;
pub const EvtSystemThreadID = EVT_SYSTEM_PROPERTY_ID.ThreadID;
pub const EvtSystemChannel = EVT_SYSTEM_PROPERTY_ID.Channel;
pub const EvtSystemComputer = EVT_SYSTEM_PROPERTY_ID.Computer;
pub const EvtSystemUserID = EVT_SYSTEM_PROPERTY_ID.UserID;
pub const EvtSystemVersion = EVT_SYSTEM_PROPERTY_ID.Version;
pub const EvtSystemPropertyIdEND = EVT_SYSTEM_PROPERTY_ID.PropertyIdEND;
pub const EVT_RENDER_CONTEXT_FLAGS = enum(i32) {
Values = 0,
System = 1,
User = 2,
};
pub const EvtRenderContextValues = EVT_RENDER_CONTEXT_FLAGS.Values;
pub const EvtRenderContextSystem = EVT_RENDER_CONTEXT_FLAGS.System;
pub const EvtRenderContextUser = EVT_RENDER_CONTEXT_FLAGS.User;
pub const EVT_RENDER_FLAGS = enum(i32) {
EventValues = 0,
EventXml = 1,
Bookmark = 2,
};
pub const EvtRenderEventValues = EVT_RENDER_FLAGS.EventValues;
pub const EvtRenderEventXml = EVT_RENDER_FLAGS.EventXml;
pub const EvtRenderBookmark = EVT_RENDER_FLAGS.Bookmark;
pub const EVT_FORMAT_MESSAGE_FLAGS = enum(i32) {
Event = 1,
Level = 2,
Task = 3,
Opcode = 4,
Keyword = 5,
Channel = 6,
Provider = 7,
Id = 8,
Xml = 9,
};
pub const EvtFormatMessageEvent = EVT_FORMAT_MESSAGE_FLAGS.Event;
pub const EvtFormatMessageLevel = EVT_FORMAT_MESSAGE_FLAGS.Level;
pub const EvtFormatMessageTask = EVT_FORMAT_MESSAGE_FLAGS.Task;
pub const EvtFormatMessageOpcode = EVT_FORMAT_MESSAGE_FLAGS.Opcode;
pub const EvtFormatMessageKeyword = EVT_FORMAT_MESSAGE_FLAGS.Keyword;
pub const EvtFormatMessageChannel = EVT_FORMAT_MESSAGE_FLAGS.Channel;
pub const EvtFormatMessageProvider = EVT_FORMAT_MESSAGE_FLAGS.Provider;
pub const EvtFormatMessageId = EVT_FORMAT_MESSAGE_FLAGS.Id;
pub const EvtFormatMessageXml = EVT_FORMAT_MESSAGE_FLAGS.Xml;
pub const EVT_OPEN_LOG_FLAGS = enum(i32) {
ChannelPath = 1,
FilePath = 2,
};
pub const EvtOpenChannelPath = EVT_OPEN_LOG_FLAGS.ChannelPath;
pub const EvtOpenFilePath = EVT_OPEN_LOG_FLAGS.FilePath;
pub const EVT_LOG_PROPERTY_ID = enum(i32) {
CreationTime = 0,
LastAccessTime = 1,
LastWriteTime = 2,
FileSize = 3,
Attributes = 4,
NumberOfLogRecords = 5,
OldestRecordNumber = 6,
Full = 7,
};
pub const EvtLogCreationTime = EVT_LOG_PROPERTY_ID.CreationTime;
pub const EvtLogLastAccessTime = EVT_LOG_PROPERTY_ID.LastAccessTime;
pub const EvtLogLastWriteTime = EVT_LOG_PROPERTY_ID.LastWriteTime;
pub const EvtLogFileSize = EVT_LOG_PROPERTY_ID.FileSize;
pub const EvtLogAttributes = EVT_LOG_PROPERTY_ID.Attributes;
pub const EvtLogNumberOfLogRecords = EVT_LOG_PROPERTY_ID.NumberOfLogRecords;
pub const EvtLogOldestRecordNumber = EVT_LOG_PROPERTY_ID.OldestRecordNumber;
pub const EvtLogFull = EVT_LOG_PROPERTY_ID.Full;
pub const EVT_EXPORTLOG_FLAGS = enum(i32) {
ChannelPath = 1,
FilePath = 2,
TolerateQueryErrors = 4096,
Overwrite = 8192,
};
pub const EvtExportLogChannelPath = EVT_EXPORTLOG_FLAGS.ChannelPath;
pub const EvtExportLogFilePath = EVT_EXPORTLOG_FLAGS.FilePath;
pub const EvtExportLogTolerateQueryErrors = EVT_EXPORTLOG_FLAGS.TolerateQueryErrors;
pub const EvtExportLogOverwrite = EVT_EXPORTLOG_FLAGS.Overwrite;
pub const EVT_CHANNEL_CONFIG_PROPERTY_ID = enum(i32) {
ConfigEnabled = 0,
ConfigIsolation = 1,
ConfigType = 2,
ConfigOwningPublisher = 3,
ConfigClassicEventlog = 4,
ConfigAccess = 5,
LoggingConfigRetention = 6,
LoggingConfigAutoBackup = 7,
LoggingConfigMaxSize = 8,
LoggingConfigLogFilePath = 9,
PublishingConfigLevel = 10,
PublishingConfigKeywords = 11,
PublishingConfigControlGuid = 12,
PublishingConfigBufferSize = 13,
PublishingConfigMinBuffers = 14,
PublishingConfigMaxBuffers = 15,
PublishingConfigLatency = 16,
PublishingConfigClockType = 17,
PublishingConfigSidType = 18,
PublisherList = 19,
PublishingConfigFileMax = 20,
ConfigPropertyIdEND = 21,
};
pub const EvtChannelConfigEnabled = EVT_CHANNEL_CONFIG_PROPERTY_ID.ConfigEnabled;
pub const EvtChannelConfigIsolation = EVT_CHANNEL_CONFIG_PROPERTY_ID.ConfigIsolation;
pub const EvtChannelConfigType = EVT_CHANNEL_CONFIG_PROPERTY_ID.ConfigType;
pub const EvtChannelConfigOwningPublisher = EVT_CHANNEL_CONFIG_PROPERTY_ID.ConfigOwningPublisher;
pub const EvtChannelConfigClassicEventlog = EVT_CHANNEL_CONFIG_PROPERTY_ID.ConfigClassicEventlog;
pub const EvtChannelConfigAccess = EVT_CHANNEL_CONFIG_PROPERTY_ID.ConfigAccess;
pub const EvtChannelLoggingConfigRetention = EVT_CHANNEL_CONFIG_PROPERTY_ID.LoggingConfigRetention;
pub const EvtChannelLoggingConfigAutoBackup = EVT_CHANNEL_CONFIG_PROPERTY_ID.LoggingConfigAutoBackup;
pub const EvtChannelLoggingConfigMaxSize = EVT_CHANNEL_CONFIG_PROPERTY_ID.LoggingConfigMaxSize;
pub const EvtChannelLoggingConfigLogFilePath = EVT_CHANNEL_CONFIG_PROPERTY_ID.LoggingConfigLogFilePath;
pub const EvtChannelPublishingConfigLevel = EVT_CHANNEL_CONFIG_PROPERTY_ID.PublishingConfigLevel;
pub const EvtChannelPublishingConfigKeywords = EVT_CHANNEL_CONFIG_PROPERTY_ID.PublishingConfigKeywords;
pub const EvtChannelPublishingConfigControlGuid = EVT_CHANNEL_CONFIG_PROPERTY_ID.PublishingConfigControlGuid;
pub const EvtChannelPublishingConfigBufferSize = EVT_CHANNEL_CONFIG_PROPERTY_ID.PublishingConfigBufferSize;
pub const EvtChannelPublishingConfigMinBuffers = EVT_CHANNEL_CONFIG_PROPERTY_ID.PublishingConfigMinBuffers;
pub const EvtChannelPublishingConfigMaxBuffers = EVT_CHANNEL_CONFIG_PROPERTY_ID.PublishingConfigMaxBuffers;
pub const EvtChannelPublishingConfigLatency = EVT_CHANNEL_CONFIG_PROPERTY_ID.PublishingConfigLatency;
pub const EvtChannelPublishingConfigClockType = EVT_CHANNEL_CONFIG_PROPERTY_ID.PublishingConfigClockType;
pub const EvtChannelPublishingConfigSidType = EVT_CHANNEL_CONFIG_PROPERTY_ID.PublishingConfigSidType;
pub const EvtChannelPublisherList = EVT_CHANNEL_CONFIG_PROPERTY_ID.PublisherList;
pub const EvtChannelPublishingConfigFileMax = EVT_CHANNEL_CONFIG_PROPERTY_ID.PublishingConfigFileMax;
pub const EvtChannelConfigPropertyIdEND = EVT_CHANNEL_CONFIG_PROPERTY_ID.ConfigPropertyIdEND;
pub const EVT_CHANNEL_TYPE = enum(i32) {
Admin = 0,
Operational = 1,
Analytic = 2,
Debug = 3,
};
pub const EvtChannelTypeAdmin = EVT_CHANNEL_TYPE.Admin;
pub const EvtChannelTypeOperational = EVT_CHANNEL_TYPE.Operational;
pub const EvtChannelTypeAnalytic = EVT_CHANNEL_TYPE.Analytic;
pub const EvtChannelTypeDebug = EVT_CHANNEL_TYPE.Debug;
pub const EVT_CHANNEL_ISOLATION_TYPE = enum(i32) {
Application = 0,
System = 1,
Custom = 2,
};
pub const EvtChannelIsolationTypeApplication = EVT_CHANNEL_ISOLATION_TYPE.Application;
pub const EvtChannelIsolationTypeSystem = EVT_CHANNEL_ISOLATION_TYPE.System;
pub const EvtChannelIsolationTypeCustom = EVT_CHANNEL_ISOLATION_TYPE.Custom;
pub const EVT_CHANNEL_CLOCK_TYPE = enum(i32) {
SystemTime = 0,
QPC = 1,
};
pub const EvtChannelClockTypeSystemTime = EVT_CHANNEL_CLOCK_TYPE.SystemTime;
pub const EvtChannelClockTypeQPC = EVT_CHANNEL_CLOCK_TYPE.QPC;
pub const EVT_CHANNEL_SID_TYPE = enum(i32) {
None = 0,
Publishing = 1,
};
pub const EvtChannelSidTypeNone = EVT_CHANNEL_SID_TYPE.None;
pub const EvtChannelSidTypePublishing = EVT_CHANNEL_SID_TYPE.Publishing;
pub const EVT_CHANNEL_REFERENCE_FLAGS = enum(i32) {
d = 1,
};
pub const EvtChannelReferenceImported = EVT_CHANNEL_REFERENCE_FLAGS.d;
pub const EVT_PUBLISHER_METADATA_PROPERTY_ID = enum(i32) {
PublisherGuid = 0,
ResourceFilePath = 1,
ParameterFilePath = 2,
MessageFilePath = 3,
HelpLink = 4,
PublisherMessageID = 5,
ChannelReferences = 6,
ChannelReferencePath = 7,
ChannelReferenceIndex = 8,
ChannelReferenceID = 9,
ChannelReferenceFlags = 10,
ChannelReferenceMessageID = 11,
Levels = 12,
LevelName = 13,
LevelValue = 14,
LevelMessageID = 15,
Tasks = 16,
TaskName = 17,
TaskEventGuid = 18,
TaskValue = 19,
TaskMessageID = 20,
Opcodes = 21,
OpcodeName = 22,
OpcodeValue = 23,
OpcodeMessageID = 24,
Keywords = 25,
KeywordName = 26,
KeywordValue = 27,
KeywordMessageID = 28,
PropertyIdEND = 29,
};
pub const EvtPublisherMetadataPublisherGuid = EVT_PUBLISHER_METADATA_PROPERTY_ID.PublisherGuid;
pub const EvtPublisherMetadataResourceFilePath = EVT_PUBLISHER_METADATA_PROPERTY_ID.ResourceFilePath;
pub const EvtPublisherMetadataParameterFilePath = EVT_PUBLISHER_METADATA_PROPERTY_ID.ParameterFilePath;
pub const EvtPublisherMetadataMessageFilePath = EVT_PUBLISHER_METADATA_PROPERTY_ID.MessageFilePath;
pub const EvtPublisherMetadataHelpLink = EVT_PUBLISHER_METADATA_PROPERTY_ID.HelpLink;
pub const EvtPublisherMetadataPublisherMessageID = EVT_PUBLISHER_METADATA_PROPERTY_ID.PublisherMessageID;
pub const EvtPublisherMetadataChannelReferences = EVT_PUBLISHER_METADATA_PROPERTY_ID.ChannelReferences;
pub const EvtPublisherMetadataChannelReferencePath = EVT_PUBLISHER_METADATA_PROPERTY_ID.ChannelReferencePath;
pub const EvtPublisherMetadataChannelReferenceIndex = EVT_PUBLISHER_METADATA_PROPERTY_ID.ChannelReferenceIndex;
pub const EvtPublisherMetadataChannelReferenceID = EVT_PUBLISHER_METADATA_PROPERTY_ID.ChannelReferenceID;
pub const EvtPublisherMetadataChannelReferenceFlags = EVT_PUBLISHER_METADATA_PROPERTY_ID.ChannelReferenceFlags;
pub const EvtPublisherMetadataChannelReferenceMessageID = EVT_PUBLISHER_METADATA_PROPERTY_ID.ChannelReferenceMessageID;
pub const EvtPublisherMetadataLevels = EVT_PUBLISHER_METADATA_PROPERTY_ID.Levels;
pub const EvtPublisherMetadataLevelName = EVT_PUBLISHER_METADATA_PROPERTY_ID.LevelName;
pub const EvtPublisherMetadataLevelValue = EVT_PUBLISHER_METADATA_PROPERTY_ID.LevelValue;
pub const EvtPublisherMetadataLevelMessageID = EVT_PUBLISHER_METADATA_PROPERTY_ID.LevelMessageID;
pub const EvtPublisherMetadataTasks = EVT_PUBLISHER_METADATA_PROPERTY_ID.Tasks;
pub const EvtPublisherMetadataTaskName = EVT_PUBLISHER_METADATA_PROPERTY_ID.TaskName;
pub const EvtPublisherMetadataTaskEventGuid = EVT_PUBLISHER_METADATA_PROPERTY_ID.TaskEventGuid;
pub const EvtPublisherMetadataTaskValue = EVT_PUBLISHER_METADATA_PROPERTY_ID.TaskValue;
pub const EvtPublisherMetadataTaskMessageID = EVT_PUBLISHER_METADATA_PROPERTY_ID.TaskMessageID;
pub const EvtPublisherMetadataOpcodes = EVT_PUBLISHER_METADATA_PROPERTY_ID.Opcodes;
pub const EvtPublisherMetadataOpcodeName = EVT_PUBLISHER_METADATA_PROPERTY_ID.OpcodeName;
pub const EvtPublisherMetadataOpcodeValue = EVT_PUBLISHER_METADATA_PROPERTY_ID.OpcodeValue;
pub const EvtPublisherMetadataOpcodeMessageID = EVT_PUBLISHER_METADATA_PROPERTY_ID.OpcodeMessageID;
pub const EvtPublisherMetadataKeywords = EVT_PUBLISHER_METADATA_PROPERTY_ID.Keywords;
pub const EvtPublisherMetadataKeywordName = EVT_PUBLISHER_METADATA_PROPERTY_ID.KeywordName;
pub const EvtPublisherMetadataKeywordValue = EVT_PUBLISHER_METADATA_PROPERTY_ID.KeywordValue;
pub const EvtPublisherMetadataKeywordMessageID = EVT_PUBLISHER_METADATA_PROPERTY_ID.KeywordMessageID;
pub const EvtPublisherMetadataPropertyIdEND = EVT_PUBLISHER_METADATA_PROPERTY_ID.PropertyIdEND;
pub const EVT_EVENT_METADATA_PROPERTY_ID = enum(i32) {
entMetadataEventID = 0,
entMetadataEventVersion = 1,
entMetadataEventChannel = 2,
entMetadataEventLevel = 3,
entMetadataEventOpcode = 4,
entMetadataEventTask = 5,
entMetadataEventKeyword = 6,
entMetadataEventMessageID = 7,
entMetadataEventTemplate = 8,
tEventMetadataPropertyIdEND = 9,
};
pub const EventMetadataEventID = EVT_EVENT_METADATA_PROPERTY_ID.entMetadataEventID;
pub const EventMetadataEventVersion = EVT_EVENT_METADATA_PROPERTY_ID.entMetadataEventVersion;
pub const EventMetadataEventChannel = EVT_EVENT_METADATA_PROPERTY_ID.entMetadataEventChannel;
pub const EventMetadataEventLevel = EVT_EVENT_METADATA_PROPERTY_ID.entMetadataEventLevel;
pub const EventMetadataEventOpcode = EVT_EVENT_METADATA_PROPERTY_ID.entMetadataEventOpcode;
pub const EventMetadataEventTask = EVT_EVENT_METADATA_PROPERTY_ID.entMetadataEventTask;
pub const EventMetadataEventKeyword = EVT_EVENT_METADATA_PROPERTY_ID.entMetadataEventKeyword;
pub const EventMetadataEventMessageID = EVT_EVENT_METADATA_PROPERTY_ID.entMetadataEventMessageID;
pub const EventMetadataEventTemplate = EVT_EVENT_METADATA_PROPERTY_ID.entMetadataEventTemplate;
pub const EvtEventMetadataPropertyIdEND = EVT_EVENT_METADATA_PROPERTY_ID.tEventMetadataPropertyIdEND;
pub const EVT_QUERY_PROPERTY_ID = enum(i32) {
Names = 0,
Statuses = 1,
PropertyIdEND = 2,
};
pub const EvtQueryNames = EVT_QUERY_PROPERTY_ID.Names;
pub const EvtQueryStatuses = EVT_QUERY_PROPERTY_ID.Statuses;
pub const EvtQueryPropertyIdEND = EVT_QUERY_PROPERTY_ID.PropertyIdEND;
pub const EVT_EVENT_PROPERTY_ID = enum(i32) {
QueryIDs = 0,
Path = 1,
PropertyIdEND = 2,
};
pub const EvtEventQueryIDs = EVT_EVENT_PROPERTY_ID.QueryIDs;
pub const EvtEventPath = EVT_EVENT_PROPERTY_ID.Path;
pub const EvtEventPropertyIdEND = EVT_EVENT_PROPERTY_ID.PropertyIdEND;
pub const EVENTLOGRECORD = extern struct {
Length: u32,
Reserved: u32,
RecordNumber: u32,
TimeGenerated: u32,
TimeWritten: u32,
EventID: u32,
EventType: REPORT_EVENT_TYPE,
NumStrings: u16,
EventCategory: u16,
ReservedFlags: u16,
ClosingRecordNumber: u32,
StringOffset: u32,
UserSidLength: u32,
UserSidOffset: u32,
DataLength: u32,
DataOffset: u32,
};
pub const EVENTSFORLOGFILE = extern struct {
ulSize: u32,
szLogicalLogFile: [256]u16,
ulNumRecords: u32,
pEventLogRecords: [1]EVENTLOGRECORD,
};
pub const EVENTLOG_FULL_INFORMATION = extern struct {
dwFull: u32,
};
//--------------------------------------------------------------------------------
// Section: Functions (55)
//--------------------------------------------------------------------------------
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "wevtapi" fn EvtOpenSession(
LoginClass: EVT_LOGIN_CLASS,
Login: ?*anyopaque,
Timeout: u32,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) isize;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "wevtapi" fn EvtClose(
Object: isize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "wevtapi" fn EvtCancel(
Object: isize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "wevtapi" fn EvtGetExtendedStatus(
BufferSize: u32,
Buffer: ?[*:0]u16,
BufferUsed: ?*u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "wevtapi" fn EvtQuery(
Session: isize,
Path: ?[*:0]const u16,
Query: ?[*:0]const u16,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) isize;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "wevtapi" fn EvtNext(
ResultSet: isize,
EventsSize: u32,
Events: [*]isize,
Timeout: u32,
Flags: u32,
Returned: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "wevtapi" fn EvtSeek(
ResultSet: isize,
Position: i64,
Bookmark: isize,
Timeout: u32,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "wevtapi" fn EvtSubscribe(
Session: isize,
SignalEvent: ?HANDLE,
ChannelPath: ?[*:0]const u16,
Query: ?[*:0]const u16,
Bookmark: isize,
Context: ?*anyopaque,
Callback: ?EVT_SUBSCRIBE_CALLBACK,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) isize;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "wevtapi" fn EvtCreateRenderContext(
ValuePathsCount: u32,
ValuePaths: ?[*]?PWSTR,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) isize;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "wevtapi" fn EvtRender(
Context: isize,
Fragment: isize,
Flags: u32,
BufferSize: u32,
// TODO: what to do with BytesParamIndex 3?
Buffer: ?*anyopaque,
BufferUsed: ?*u32,
PropertyCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "wevtapi" fn EvtFormatMessage(
PublisherMetadata: isize,
Event: isize,
MessageId: u32,
ValueCount: u32,
Values: ?[*]EVT_VARIANT,
Flags: u32,
BufferSize: u32,
Buffer: ?[*:0]u16,
BufferUsed: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "wevtapi" fn EvtOpenLog(
Session: isize,
Path: ?[*:0]const u16,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) isize;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "wevtapi" fn EvtGetLogInfo(
Log: isize,
PropertyId: EVT_LOG_PROPERTY_ID,
PropertyValueBufferSize: u32,
// TODO: what to do with BytesParamIndex 2?
PropertyValueBuffer: ?*EVT_VARIANT,
PropertyValueBufferUsed: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "wevtapi" fn EvtClearLog(
Session: isize,
ChannelPath: ?[*:0]const u16,
TargetFilePath: ?[*:0]const u16,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "wevtapi" fn EvtExportLog(
Session: isize,
Path: ?[*:0]const u16,
Query: ?[*:0]const u16,
TargetFilePath: ?[*:0]const u16,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "wevtapi" fn EvtArchiveExportedLog(
Session: isize,
LogFilePath: ?[*:0]const u16,
Locale: u32,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "wevtapi" fn EvtOpenChannelEnum(
Session: isize,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) isize;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "wevtapi" fn EvtNextChannelPath(
ChannelEnum: isize,
ChannelPathBufferSize: u32,
ChannelPathBuffer: ?[*:0]u16,
ChannelPathBufferUsed: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "wevtapi" fn EvtOpenChannelConfig(
Session: isize,
ChannelPath: ?[*:0]const u16,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) isize;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "wevtapi" fn EvtSaveChannelConfig(
ChannelConfig: isize,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "wevtapi" fn EvtSetChannelConfigProperty(
ChannelConfig: isize,
PropertyId: EVT_CHANNEL_CONFIG_PROPERTY_ID,
Flags: u32,
PropertyValue: ?*EVT_VARIANT,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "wevtapi" fn EvtGetChannelConfigProperty(
ChannelConfig: isize,
PropertyId: EVT_CHANNEL_CONFIG_PROPERTY_ID,
Flags: u32,
PropertyValueBufferSize: u32,
// TODO: what to do with BytesParamIndex 3?
PropertyValueBuffer: ?*EVT_VARIANT,
PropertyValueBufferUsed: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "wevtapi" fn EvtOpenPublisherEnum(
Session: isize,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) isize;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "wevtapi" fn EvtNextPublisherId(
PublisherEnum: isize,
PublisherIdBufferSize: u32,
PublisherIdBuffer: ?[*:0]u16,
PublisherIdBufferUsed: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "wevtapi" fn EvtOpenPublisherMetadata(
Session: isize,
PublisherId: ?[*:0]const u16,
LogFilePath: ?[*:0]const u16,
Locale: u32,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) isize;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "wevtapi" fn EvtGetPublisherMetadataProperty(
PublisherMetadata: isize,
PropertyId: EVT_PUBLISHER_METADATA_PROPERTY_ID,
Flags: u32,
PublisherMetadataPropertyBufferSize: u32,
// TODO: what to do with BytesParamIndex 3?
PublisherMetadataPropertyBuffer: ?*EVT_VARIANT,
PublisherMetadataPropertyBufferUsed: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "wevtapi" fn EvtOpenEventMetadataEnum(
PublisherMetadata: isize,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) isize;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "wevtapi" fn EvtNextEventMetadata(
EventMetadataEnum: isize,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) isize;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "wevtapi" fn EvtGetEventMetadataProperty(
EventMetadata: isize,
PropertyId: EVT_EVENT_METADATA_PROPERTY_ID,
Flags: u32,
EventMetadataPropertyBufferSize: u32,
// TODO: what to do with BytesParamIndex 3?
EventMetadataPropertyBuffer: ?*EVT_VARIANT,
EventMetadataPropertyBufferUsed: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "wevtapi" fn EvtGetObjectArraySize(
ObjectArray: isize,
ObjectArraySize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "wevtapi" fn EvtGetObjectArrayProperty(
ObjectArray: isize,
PropertyId: u32,
ArrayIndex: u32,
Flags: u32,
PropertyValueBufferSize: u32,
// TODO: what to do with BytesParamIndex 4?
PropertyValueBuffer: ?*EVT_VARIANT,
PropertyValueBufferUsed: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "wevtapi" fn EvtGetQueryInfo(
QueryOrSubscription: isize,
PropertyId: EVT_QUERY_PROPERTY_ID,
PropertyValueBufferSize: u32,
// TODO: what to do with BytesParamIndex 2?
PropertyValueBuffer: ?*EVT_VARIANT,
PropertyValueBufferUsed: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "wevtapi" fn EvtCreateBookmark(
BookmarkXml: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) isize;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "wevtapi" fn EvtUpdateBookmark(
Bookmark: isize,
Event: isize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "wevtapi" fn EvtGetEventInfo(
Event: isize,
PropertyId: EVT_EVENT_PROPERTY_ID,
PropertyValueBufferSize: u32,
// TODO: what to do with BytesParamIndex 2?
PropertyValueBuffer: ?*EVT_VARIANT,
PropertyValueBufferUsed: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ADVAPI32" fn ClearEventLogA(
hEventLog: ?HANDLE,
lpBackupFileName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ADVAPI32" fn ClearEventLogW(
hEventLog: ?HANDLE,
lpBackupFileName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ADVAPI32" fn BackupEventLogA(
hEventLog: ?HANDLE,
lpBackupFileName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ADVAPI32" fn BackupEventLogW(
hEventLog: ?HANDLE,
lpBackupFileName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ADVAPI32" fn CloseEventLog(
hEventLog: EventLogHandle,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ADVAPI32" fn DeregisterEventSource(
hEventLog: EventSourceHandle,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ADVAPI32" fn NotifyChangeEventLog(
hEventLog: ?HANDLE,
hEvent: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ADVAPI32" fn GetNumberOfEventLogRecords(
hEventLog: ?HANDLE,
NumberOfRecords: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ADVAPI32" fn GetOldestEventLogRecord(
hEventLog: ?HANDLE,
OldestRecord: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ADVAPI32" fn OpenEventLogA(
lpUNCServerName: ?[*:0]const u8,
lpSourceName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) EventLogHandle;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ADVAPI32" fn OpenEventLogW(
lpUNCServerName: ?[*:0]const u16,
lpSourceName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) EventLogHandle;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ADVAPI32" fn RegisterEventSourceA(
lpUNCServerName: ?[*:0]const u8,
lpSourceName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) EventSourceHandle;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ADVAPI32" fn RegisterEventSourceW(
lpUNCServerName: ?[*:0]const u16,
lpSourceName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) EventSourceHandle;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ADVAPI32" fn OpenBackupEventLogA(
lpUNCServerName: ?[*:0]const u8,
lpFileName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) EventLogHandle;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ADVAPI32" fn OpenBackupEventLogW(
lpUNCServerName: ?[*:0]const u16,
lpFileName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) EventLogHandle;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ADVAPI32" fn ReadEventLogA(
hEventLog: ?HANDLE,
dwReadFlags: READ_EVENT_LOG_READ_FLAGS,
dwRecordOffset: u32,
// TODO: what to do with BytesParamIndex 4?
lpBuffer: ?*anyopaque,
nNumberOfBytesToRead: u32,
pnBytesRead: ?*u32,
pnMinNumberOfBytesNeeded: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ADVAPI32" fn ReadEventLogW(
hEventLog: ?HANDLE,
dwReadFlags: READ_EVENT_LOG_READ_FLAGS,
dwRecordOffset: u32,
// TODO: what to do with BytesParamIndex 4?
lpBuffer: ?*anyopaque,
nNumberOfBytesToRead: u32,
pnBytesRead: ?*u32,
pnMinNumberOfBytesNeeded: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ADVAPI32" fn ReportEventA(
hEventLog: ?HANDLE,
wType: REPORT_EVENT_TYPE,
wCategory: u16,
dwEventID: u32,
lpUserSid: ?PSID,
wNumStrings: u16,
dwDataSize: u32,
lpStrings: ?[*]?PSTR,
// TODO: what to do with BytesParamIndex 6?
lpRawData: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ADVAPI32" fn ReportEventW(
hEventLog: ?HANDLE,
wType: REPORT_EVENT_TYPE,
wCategory: u16,
dwEventID: u32,
lpUserSid: ?PSID,
wNumStrings: u16,
dwDataSize: u32,
lpStrings: ?[*]?PWSTR,
// TODO: what to do with BytesParamIndex 6?
lpRawData: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "ADVAPI32" fn GetEventLogInformation(
hEventLog: ?HANDLE,
dwInfoLevel: u32,
// TODO: what to do with BytesParamIndex 3?
lpBuffer: ?*anyopaque,
cbBufSize: u32,
pcbBytesNeeded: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (7)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../zig.zig").unicode_mode) {
.ansi => struct {
pub const ClearEventLog = thismodule.ClearEventLogA;
pub const BackupEventLog = thismodule.BackupEventLogA;
pub const OpenEventLog = thismodule.OpenEventLogA;
pub const RegisterEventSource = thismodule.RegisterEventSourceA;
pub const OpenBackupEventLog = thismodule.OpenBackupEventLogA;
pub const ReadEventLog = thismodule.ReadEventLogA;
pub const ReportEvent = thismodule.ReportEventA;
},
.wide => struct {
pub const ClearEventLog = thismodule.ClearEventLogW;
pub const BackupEventLog = thismodule.BackupEventLogW;
pub const OpenEventLog = thismodule.OpenEventLogW;
pub const RegisterEventSource = thismodule.RegisterEventSourceW;
pub const OpenBackupEventLog = thismodule.OpenBackupEventLogW;
pub const ReadEventLog = thismodule.ReadEventLogW;
pub const ReportEvent = thismodule.ReportEventW;
},
.unspecified => if (@import("builtin").is_test) struct {
pub const ClearEventLog = *opaque{};
pub const BackupEventLog = *opaque{};
pub const OpenEventLog = *opaque{};
pub const RegisterEventSource = *opaque{};
pub const OpenBackupEventLog = *opaque{};
pub const ReadEventLog = *opaque{};
pub const ReportEvent = *opaque{};
} else struct {
pub const ClearEventLog = @compileError("'ClearEventLog' requires that UNICODE be set to true or false in the root module");
pub const BackupEventLog = @compileError("'BackupEventLog' requires that UNICODE be set to true or false in the root module");
pub const OpenEventLog = @compileError("'OpenEventLog' requires that UNICODE be set to true or false in the root module");
pub const RegisterEventSource = @compileError("'RegisterEventSource' requires that UNICODE be set to true or false in the root module");
pub const OpenBackupEventLog = @compileError("'OpenBackupEventLog' requires that UNICODE be set to true or false in the root module");
pub const ReadEventLog = @compileError("'ReadEventLog' requires that UNICODE be set to true or false in the root module");
pub const ReportEvent = @compileError("'ReportEvent' requires that UNICODE be set to true or false in the root module");
},
};
//--------------------------------------------------------------------------------
// Section: Imports (8)
//--------------------------------------------------------------------------------
const Guid = @import("../zig.zig").Guid;
const BOOL = @import("../foundation.zig").BOOL;
const FILETIME = @import("../foundation.zig").FILETIME;
const HANDLE = @import("../foundation.zig").HANDLE;
const PSID = @import("../foundation.zig").PSID;
const PSTR = @import("../foundation.zig").PSTR;
const PWSTR = @import("../foundation.zig").PWSTR;
const SYSTEMTIME = @import("../foundation.zig").SYSTEMTIME;
test {
// The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476
if (@hasDecl(@This(), "EVT_SUBSCRIBE_CALLBACK")) { _ = EVT_SUBSCRIBE_CALLBACK; }
@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/event_log.zig |
// DO NOT MODIFY. This is not actually a source file; it is a textual representation of generated code.
// Use only for debugging purposes.
// Auto-generated constructor
// Access: public
Method <init> : V
(
// (no arguments)
) {
ALOAD 0
// Method descriptor: ()V
INVOKESPECIAL java/lang/Object#<init>
RETURN
}
// Access: public
Method deploy : V
(
arg 1 = Lio/quarkus/runtime/StartupContext;
) {
** label1
LDC (Integer) 23
ANEWARRAY java/lang/Object
ASTORE 2
ALOAD 0
ALOAD 1
ALOAD 2
// Method descriptor: (Lio/quarkus/runtime/StartupContext;[Ljava/lang/Object;)V
INVOKEVIRTUAL io/quarkus/deployment/steps/HibernateOrmProcessor$build8#deploy_0
RETURN
** label2
}
// Access: public
Method deploy_0 : V
(
arg 1 = Lio/quarkus/runtime/StartupContext;,
arg 2 = [Ljava/lang/Object;
) {
** label1
NEW io/quarkus/hibernate/orm/runtime/HibernateOrmRecorder
DUP
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/hibernate/orm/runtime/HibernateOrmRecorder#<init>
ASTORE 3
ALOAD 2
LDC (Integer) 0
ALOAD 3
AASTORE
ALOAD 2
LDC (Integer) 0
AALOAD
ASTORE 4
ALOAD 4
CHECKCAST io/quarkus/hibernate/orm/runtime/HibernateOrmRecorder
// Method descriptor: ()V
INVOKEVIRTUAL io/quarkus/hibernate/orm/runtime/HibernateOrmRecorder#callHibernateFeatureInit
ALOAD 4
CHECKCAST io/quarkus/hibernate/orm/runtime/HibernateOrmRecorder
LDC (String) "io.openshift.booster.database.Fruit"
// Method descriptor: (Ljava/lang/String;)V
INVOKEVIRTUAL io/quarkus/hibernate/orm/runtime/HibernateOrmRecorder#addEntity
ALOAD 4
CHECKCAST io/quarkus/hibernate/orm/runtime/HibernateOrmRecorder
LDC (String) "com.pursuitbank.models.Company"
// Method descriptor: (Ljava/lang/String;)V
INVOKEVIRTUAL io/quarkus/hibernate/orm/runtime/HibernateOrmRecorder#addEntity
ALOAD 4
CHECKCAST io/quarkus/hibernate/orm/runtime/HibernateOrmRecorder
LDC (String) "com.pursuitbank.models.Customer"
// Method descriptor: (Ljava/lang/String;)V
INVOKEVIRTUAL io/quarkus/hibernate/orm/runtime/HibernateOrmRecorder#addEntity
ALOAD 4
CHECKCAST io/quarkus/hibernate/orm/runtime/HibernateOrmRecorder
LDC (String) "com.pursuitbank.models.Offer"
// Method descriptor: (Ljava/lang/String;)V
INVOKEVIRTUAL io/quarkus/hibernate/orm/runtime/HibernateOrmRecorder#addEntity
ALOAD 4
CHECKCAST io/quarkus/hibernate/orm/runtime/HibernateOrmRecorder
LDC (String) "com.pursuitbank.models.Location"
// Method descriptor: (Ljava/lang/String;)V
INVOKEVIRTUAL io/quarkus/hibernate/orm/runtime/HibernateOrmRecorder#addEntity
ALOAD 4
CHECKCAST io/quarkus/hibernate/orm/runtime/HibernateOrmRecorder
// Method descriptor: ()V
INVOKEVIRTUAL io/quarkus/hibernate/orm/runtime/HibernateOrmRecorder#enlistPersistenceUnit
NEW java/util/ArrayList
DUP
// Method descriptor: ()V
INVOKESPECIAL java/util/ArrayList#<init>
ASTORE 5
ALOAD 2
LDC (Integer) 3
ALOAD 5
AASTORE
NEW org/hibernate/jpa/boot/internal/ParsedPersistenceXmlDescriptor
DUP
ACONST_NULL
// Method descriptor: (Ljava/net/URL;)V
INVOKESPECIAL org/hibernate/jpa/boot/internal/ParsedPersistenceXmlDescriptor#<init>
ASTORE 6
ALOAD 2
LDC (Integer) 1
ALOAD 6
AASTORE
ALOAD 2
LDC (Integer) 1
AALOAD
ASTORE 7
LDC (Boolean) false
// Method descriptor: (Z)Ljava/lang/Boolean;
INVOKESTATIC java/lang/Boolean#valueOf
ASTORE 8
ALOAD 7
CHECKCAST org/hibernate/jpa/boot/internal/ParsedPersistenceXmlDescriptor
ALOAD 8
CHECKCAST java/lang/Boolean
// Method descriptor: ()Z
INVOKEVIRTUAL java/lang/Boolean#booleanValue
// Method descriptor: (Z)V
INVOKEVIRTUAL org/hibernate/jpa/boot/internal/ParsedPersistenceXmlDescriptor#setExcludeUnlistedClasses
LDC (String) "JTA"
// Method descriptor: (Ljava/lang/String;)Ljavax/persistence/spi/PersistenceUnitTransactionType;
INVOKESTATIC javax/persistence/spi/PersistenceUnitTransactionType#valueOf
ASTORE 9
ALOAD 7
CHECKCAST org/hibernate/jpa/boot/internal/ParsedPersistenceXmlDescriptor
ALOAD 9
// Method descriptor: (Ljavax/persistence/spi/PersistenceUnitTransactionType;)V
INVOKEVIRTUAL org/hibernate/jpa/boot/internal/ParsedPersistenceXmlDescriptor#setTransactionType
ALOAD 7
CHECKCAST org/hibernate/jpa/boot/internal/ParsedPersistenceXmlDescriptor
LDC (String) "default"
// Method descriptor: (Ljava/lang/String;)V
INVOKEVIRTUAL org/hibernate/jpa/boot/internal/ParsedPersistenceXmlDescriptor#setName
LDC (Boolean) false
// Method descriptor: (Z)Ljava/lang/Boolean;
INVOKESTATIC java/lang/Boolean#valueOf
ASTORE 10
ALOAD 7
CHECKCAST org/hibernate/jpa/boot/internal/ParsedPersistenceXmlDescriptor
ALOAD 10
CHECKCAST java/lang/Boolean
// Method descriptor: ()Z
INVOKEVIRTUAL java/lang/Boolean#booleanValue
// Method descriptor: (Z)V
INVOKEVIRTUAL org/hibernate/jpa/boot/internal/ParsedPersistenceXmlDescriptor#setUseQuotedIdentifiers
ALOAD 7
CHECKCAST org/hibernate/jpa/boot/internal/ParsedPersistenceXmlDescriptor
// Method descriptor: ()Ljava/util/Properties;
INVOKEVIRTUAL org/hibernate/jpa/boot/internal/ParsedPersistenceXmlDescriptor#getProperties
ASTORE 11
ALOAD 11
CHECKCAST java/util/Map
LDC (String) "hibernate.hbm2ddl.import_files_sql_extractor"
LDC (String) "org.hibernate.tool.hbm2ddl.MultipleLinesSqlCommandExtractor"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 11
CHECKCAST java/util/Map
LDC (String) "hibernate.dialect"
LDC (String) "org.hibernate.dialect.H2Dialect"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 11
CHECKCAST java/util/Map
LDC (String) "javax.persistence.schema-generation.database.action"
LDC (String) "drop-and-create"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 11
CHECKCAST java/util/Map
LDC (String) "hibernate.hbm2ddl.import_files"
LDC (String) "import.sql"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 2
LDC (Integer) 2
ALOAD 7
AASTORE
ALOAD 2
LDC (Integer) 3
AALOAD
ASTORE 13
ALOAD 2
LDC (Integer) 2
AALOAD
ASTORE 12
ALOAD 13
CHECKCAST java/util/Collection
ALOAD 12
// Method descriptor: (Ljava/lang/Object;)Z
INVOKEINTERFACE java/util/Collection#add
POP
ALOAD 2
LDC (Integer) 4
ALOAD 13
AASTORE
NEW io/quarkus/hibernate/orm/runtime/boot/scan/QuarkusScanner
DUP
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/hibernate/orm/runtime/boot/scan/QuarkusScanner#<init>
ASTORE 14
ALOAD 2
LDC (Integer) 17
ALOAD 14
AASTORE
NEW java/util/HashSet
DUP
// Method descriptor: ()V
INVOKESPECIAL java/util/HashSet#<init>
ASTORE 15
ALOAD 2
LDC (Integer) 15
ALOAD 15
AASTORE
NEW io/quarkus/hibernate/orm/runtime/boot/scan/QuarkusScanner$ClassDescriptorImpl
DUP
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/hibernate/orm/runtime/boot/scan/QuarkusScanner$ClassDescriptorImpl#<init>
ASTORE 16
ALOAD 2
LDC (Integer) 5
ALOAD 16
AASTORE
ALOAD 2
LDC (Integer) 5
AALOAD
ASTORE 17
LDC (String) "MODEL"
// Method descriptor: (Ljava/lang/String;)Lorg/hibernate/boot/archive/scan/spi/ClassDescriptor$Categorization;
INVOKESTATIC org/hibernate/boot/archive/scan/spi/ClassDescriptor$Categorization#valueOf
ASTORE 18
ALOAD 17
CHECKCAST io/quarkus/hibernate/orm/runtime/boot/scan/QuarkusScanner$ClassDescriptorImpl
ALOAD 18
// Method descriptor: (Lorg/hibernate/boot/archive/scan/spi/ClassDescriptor$Categorization;)V
INVOKEVIRTUAL io/quarkus/hibernate/orm/runtime/boot/scan/QuarkusScanner$ClassDescriptorImpl#setCategorization
ALOAD 17
CHECKCAST io/quarkus/hibernate/orm/runtime/boot/scan/QuarkusScanner$ClassDescriptorImpl
LDC (String) "io.openshift.booster.database.Fruit"
// Method descriptor: (Ljava/lang/String;)V
INVOKEVIRTUAL io/quarkus/hibernate/orm/runtime/boot/scan/QuarkusScanner$ClassDescriptorImpl#setName
ALOAD 2
LDC (Integer) 6
ALOAD 17
AASTORE
NEW io/quarkus/hibernate/orm/runtime/boot/scan/QuarkusScanner$ClassDescriptorImpl
DUP
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/hibernate/orm/runtime/boot/scan/QuarkusScanner$ClassDescriptorImpl#<init>
ASTORE 19
ALOAD 2
LDC (Integer) 7
ALOAD 19
AASTORE
ALOAD 2
LDC (Integer) 7
AALOAD
ASTORE 21
LDC (String) "MODEL"
// Method descriptor: (Ljava/lang/String;)Lorg/hibernate/boot/archive/scan/spi/ClassDescriptor$Categorization;
INVOKESTATIC org/hibernate/boot/archive/scan/spi/ClassDescriptor$Categorization#valueOf
ASTORE 20
ALOAD 21
CHECKCAST io/quarkus/hibernate/orm/runtime/boot/scan/QuarkusScanner$ClassDescriptorImpl
ALOAD 20
// Method descriptor: (Lorg/hibernate/boot/archive/scan/spi/ClassDescriptor$Categorization;)V
INVOKEVIRTUAL io/quarkus/hibernate/orm/runtime/boot/scan/QuarkusScanner$ClassDescriptorImpl#setCategorization
ALOAD 21
CHECKCAST io/quarkus/hibernate/orm/runtime/boot/scan/QuarkusScanner$ClassDescriptorImpl
LDC (String) "com.pursuitbank.models.Location"
// Method descriptor: (Ljava/lang/String;)V
INVOKEVIRTUAL io/quarkus/hibernate/orm/runtime/boot/scan/QuarkusScanner$ClassDescriptorImpl#setName
ALOAD 2
LDC (Integer) 8
ALOAD 21
AASTORE
NEW io/quarkus/hibernate/orm/runtime/boot/scan/QuarkusScanner$ClassDescriptorImpl
DUP
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/hibernate/orm/runtime/boot/scan/QuarkusScanner$ClassDescriptorImpl#<init>
ASTORE 22
ALOAD 2
LDC (Integer) 9
ALOAD 22
AASTORE
ALOAD 2
LDC (Integer) 9
AALOAD
ASTORE 23
LDC (String) "MODEL"
// Method descriptor: (Ljava/lang/String;)Lorg/hibernate/boot/archive/scan/spi/ClassDescriptor$Categorization;
INVOKESTATIC org/hibernate/boot/archive/scan/spi/ClassDescriptor$Categorization#valueOf
ASTORE 24
ALOAD 23
CHECKCAST io/quarkus/hibernate/orm/runtime/boot/scan/QuarkusScanner$ClassDescriptorImpl
ALOAD 24
// Method descriptor: (Lorg/hibernate/boot/archive/scan/spi/ClassDescriptor$Categorization;)V
INVOKEVIRTUAL io/quarkus/hibernate/orm/runtime/boot/scan/QuarkusScanner$ClassDescriptorImpl#setCategorization
ALOAD 23
CHECKCAST io/quarkus/hibernate/orm/runtime/boot/scan/QuarkusScanner$ClassDescriptorImpl
LDC (String) "com.pursuitbank.models.Offer"
// Method descriptor: (Ljava/lang/String;)V
INVOKEVIRTUAL io/quarkus/hibernate/orm/runtime/boot/scan/QuarkusScanner$ClassDescriptorImpl#setName
ALOAD 2
LDC (Integer) 10
ALOAD 23
AASTORE
NEW io/quarkus/hibernate/orm/runtime/boot/scan/QuarkusScanner$ClassDescriptorImpl
DUP
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/hibernate/orm/runtime/boot/scan/QuarkusScanner$ClassDescriptorImpl#<init>
ASTORE 25
ALOAD 2
LDC (Integer) 11
ALOAD 25
AASTORE
ALOAD 2
LDC (Integer) 11
AALOAD
ASTORE 26
LDC (String) "MODEL"
// Method descriptor: (Ljava/lang/String;)Lorg/hibernate/boot/archive/scan/spi/ClassDescriptor$Categorization;
INVOKESTATIC org/hibernate/boot/archive/scan/spi/ClassDescriptor$Categorization#valueOf
ASTORE 27
ALOAD 26
CHECKCAST io/quarkus/hibernate/orm/runtime/boot/scan/QuarkusScanner$ClassDescriptorImpl
ALOAD 27
// Method descriptor: (Lorg/hibernate/boot/archive/scan/spi/ClassDescriptor$Categorization;)V
INVOKEVIRTUAL io/quarkus/hibernate/orm/runtime/boot/scan/QuarkusScanner$ClassDescriptorImpl#setCategorization
ALOAD 26
CHECKCAST io/quarkus/hibernate/orm/runtime/boot/scan/QuarkusScanner$ClassDescriptorImpl
LDC (String) "com.pursuitbank.models.Company"
// Method descriptor: (Ljava/lang/String;)V
INVOKEVIRTUAL io/quarkus/hibernate/orm/runtime/boot/scan/QuarkusScanner$ClassDescriptorImpl#setName
ALOAD 2
LDC (Integer) 12
ALOAD 26
AASTORE
NEW io/quarkus/hibernate/orm/runtime/boot/scan/QuarkusScanner$ClassDescriptorImpl
DUP
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/hibernate/orm/runtime/boot/scan/QuarkusScanner$ClassDescriptorImpl#<init>
ASTORE 28
ALOAD 2
LDC (Integer) 13
ALOAD 28
AASTORE
ALOAD 2
LDC (Integer) 13
AALOAD
ASTORE 29
LDC (String) "MODEL"
// Method descriptor: (Ljava/lang/String;)Lorg/hibernate/boot/archive/scan/spi/ClassDescriptor$Categorization;
INVOKESTATIC org/hibernate/boot/archive/scan/spi/ClassDescriptor$Categorization#valueOf
ASTORE 30
ALOAD 29
CHECKCAST io/quarkus/hibernate/orm/runtime/boot/scan/QuarkusScanner$ClassDescriptorImpl
ALOAD 30
// Method descriptor: (Lorg/hibernate/boot/archive/scan/spi/ClassDescriptor$Categorization;)V
INVOKEVIRTUAL io/quarkus/hibernate/orm/runtime/boot/scan/QuarkusScanner$ClassDescriptorImpl#setCategorization
ALOAD 29
CHECKCAST io/quarkus/hibernate/orm/runtime/boot/scan/QuarkusScanner$ClassDescriptorImpl
LDC (String) "com.pursuitbank.models.Customer"
// Method descriptor: (Ljava/lang/String;)V
INVOKEVIRTUAL io/quarkus/hibernate/orm/runtime/boot/scan/QuarkusScanner$ClassDescriptorImpl#setName
ALOAD 2
LDC (Integer) 14
ALOAD 29
AASTORE
ALOAD 2
LDC (Integer) 15
AALOAD
ASTORE 31
ALOAD 2
LDC (Integer) 6
AALOAD
ASTORE 32
ALOAD 31
CHECKCAST java/util/Collection
ALOAD 32
// Method descriptor: (Ljava/lang/Object;)Z
INVOKEINTERFACE java/util/Collection#add
POP
ALOAD 2
LDC (Integer) 8
AALOAD
ASTORE 33
ALOAD 31
CHECKCAST java/util/Collection
ALOAD 33
// Method descriptor: (Ljava/lang/Object;)Z
INVOKEINTERFACE java/util/Collection#add
POP
ALOAD 2
LDC (Integer) 10
AALOAD
ASTORE 34
ALOAD 31
CHECKCAST java/util/Collection
ALOAD 34
// Method descriptor: (Ljava/lang/Object;)Z
INVOKEINTERFACE java/util/Collection#add
POP
ALOAD 2
LDC (Integer) 12
AALOAD
ASTORE 35
ALOAD 31
CHECKCAST java/util/Collection
ALOAD 35
// Method descriptor: (Ljava/lang/Object;)Z
INVOKEINTERFACE java/util/Collection#add
POP
ALOAD 2
LDC (Integer) 14
AALOAD
ASTORE 36
ALOAD 31
CHECKCAST java/util/Collection
ALOAD 36
// Method descriptor: (Ljava/lang/Object;)Z
INVOKEINTERFACE java/util/Collection#add
POP
ALOAD 2
LDC (Integer) 16
ALOAD 31
AASTORE
ALOAD 2
LDC (Integer) 17
AALOAD
ASTORE 38
ALOAD 2
LDC (Integer) 16
AALOAD
ASTORE 37
ALOAD 38
CHECKCAST io/quarkus/hibernate/orm/runtime/boot/scan/QuarkusScanner
ALOAD 37
CHECKCAST java/util/Set
// Method descriptor: (Ljava/util/Set;)V
INVOKEVIRTUAL io/quarkus/hibernate/orm/runtime/boot/scan/QuarkusScanner#setClassDescriptors
ALOAD 2
LDC (Integer) 18
ALOAD 38
AASTORE
NEW java/util/LinkedHashSet
DUP
// Method descriptor: ()V
INVOKESPECIAL java/util/LinkedHashSet#<init>
ASTORE 39
ALOAD 2
LDC (Integer) 19
ALOAD 39
AASTORE
ALOAD 2
LDC (Integer) 19
AALOAD
ASTORE 40
ALOAD 2
LDC (Integer) 20
ALOAD 40
AASTORE
NEW java/util/LinkedHashSet
DUP
// Method descriptor: ()V
INVOKESPECIAL java/util/LinkedHashSet#<init>
ASTORE 41
ALOAD 2
LDC (Integer) 21
ALOAD 41
AASTORE
ALOAD 2
LDC (Integer) 21
AALOAD
ASTORE 42
ALOAD 2
LDC (Integer) 22
ALOAD 42
AASTORE
ALOAD 2
LDC (Integer) 4
AALOAD
ASTORE 43
ALOAD 2
LDC (Integer) 18
AALOAD
ASTORE 44
ALOAD 2
LDC (Integer) 20
AALOAD
ASTORE 45
ALOAD 2
LDC (Integer) 22
AALOAD
ASTORE 46
ALOAD 4
CHECKCAST io/quarkus/hibernate/orm/runtime/HibernateOrmRecorder
ALOAD 43
CHECKCAST java/util/List
ALOAD 44
CHECKCAST org/hibernate/boot/archive/scan/spi/Scanner
ALOAD 45
CHECKCAST java/util/Collection
ALOAD 46
CHECKCAST java/util/Collection
// Method descriptor: (Ljava/util/List;Lorg/hibernate/boot/archive/scan/spi/Scanner;Ljava/util/Collection;Ljava/util/Collection;)Lio/quarkus/arc/runtime/BeanContainerListener;
INVOKEVIRTUAL io/quarkus/hibernate/orm/runtime/HibernateOrmRecorder#initMetadata
ASTORE 47
ALOAD 1
LDC (String) "proxykey24"
ALOAD 47
// Method descriptor: (Ljava/lang/String;Ljava/lang/Object;)V
INVOKEVIRTUAL io/quarkus/runtime/StartupContext#putValue
RETURN
** label2
} | target/generated-sources/gizmo/io/quarkus/deployment/steps/HibernateOrmProcessor$build8.zig |
const std = @import("std");
pub const VectorError = error{
OutOfBounds,
ZeroMaxCountIsUngrowable,
};
pub fn Vector(comptime T: type) type {
const DEFAULT_MAX = 20;
return struct {
arr: []T,
allocator: *std.mem.Allocator,
len: usize,
pub fn initSize(allocator: *std.mem.Allocator, init_max: usize) !Vector(T) {
return Vector(T){
.arr = try allocator.alloc(T,init_max),
.allocator = allocator,
.len = 0,
};
}
//NOTE: 0*2 = 0, so push would need an additional check for when arr.len==0, and then allocate the array
//pub fn initEmpty(allocator: *std.mem.Allocator) Vector(T) {
// return Vector(T){
// .arr = [_]T{},
// .allocator = allocator,
// .len = 0,
// };
//}
pub fn init(allocator: *std.mem.Allocator) !Vector(T) {
return Vector(T){
.arr = try allocator.alloc(T,DEFAULT_MAX),
.allocator = allocator,
.len = 0,
};
}
pub fn deinit(self: *Vector(T)) void {
self.allocator.free(self.arr);
}
pub fn push(self: *Vector(T), item: T) !void {
if(self.len==self.arr.len){
const new_max = self.arr.len*2;
self.arr = try self.allocator.realloc(self.arr,new_max);
}
self.arr[self.len] = item;
self.len += 1;
}
pub fn pop(self: *Vector(T)) void {
if(self.len!=0){
self.len -= 1;
}
}
pub fn shrinkToCount(self: *Vector(T)) !void {
if(self.len==0)
return VectorError.ZeroMaxCountIsUngrowable;
self.arr = try self.allocator.realloc(self.arr,self.len);
}
pub fn count(self: Vector(T)) usize {
return self.len;
}
pub fn maxCount(self: Vector(T)) usize {
return self.arr.len;
}
pub fn at(self: Vector(T), index: usize) T {
return self.arr[index];
}
pub fn safeAt(self: Vector(T), index: usize) !T {
if(index>=self.len)
return VectorError.OutOfBounds;
return self.arr[index];
}
};
} | vector.zig |
const builtin = @import("builtin");
const TypeId = builtin.TypeId;
const std = @import("std");
const assert = std.debug.assert;
const warn = std.debug.warn;
const matrix = @import("matrix.zig");
const Matrix = matrix.Matrix;
const M44f32 = matrix.M44f32;
const vec = @import("vec.zig");
const V3f32 = vec.V3f32;
const V2f32 = vec.V2f32;
const sc = @import("screencoord.zig");
const projectToScreenCoord = sc.projectToScreenCoord;
const pointToScreenCoord = sc.pointToScreenCoord;
const DBG = false;
/// Create look-at matrix "Left Hand"
pub fn lookAtLh(eye: *const V3f32, target: *const V3f32, up: *const V3f32) M44f32 {
if (DBG) warn("math3d.lookAtLh: eye {} target {}\n", eye, target);
var zaxis = target.sub(eye).normalize();
var xaxis = up.cross(&zaxis).normalize();
var yaxis = zaxis.cross(&xaxis).normalize();
// Column major order?
var cmo = M44f32{ .data = [][4]f32{
[]f32{ xaxis.x(), yaxis.x(), zaxis.x(), 0 },
[]f32{ xaxis.y(), yaxis.y(), zaxis.y(), 0 },
[]f32{ xaxis.z(), yaxis.z(), zaxis.z(), 0 },
[]f32{ -xaxis.dot(eye), -yaxis.dot(eye), -zaxis.dot(eye), 1 },
} };
// Row major order?
var rmo = M44f32{ .data = [][4]f32{
[]f32{ xaxis.x(), xaxis.y(), xaxis.z(), -xaxis.dot(eye) },
[]f32{ yaxis.x(), yaxis.y(), yaxis.z(), -yaxis.dot(eye) },
[]f32{ zaxis.x(), zaxis.y(), zaxis.z(), -zaxis.dot(eye) },
[]f32{ 0, 0, 0, 1 },
} };
var result = cmo;
if (DBG) warn("math3d.lookAtLh: result\n{}", &result);
return result;
}
/// Create look-at matrix "Right Hand"
pub fn lookAtRh(eye: *const V3f32, target: *const V3f32, up: *const V3f32) M44f32 {
if (DBG) warn("math3d.lookAtRh: eye {} target {}\n", eye, target);
// This is eye - target Left Hand is target - eye
var zaxis = eye.sub(target).normalize();
var xaxis = up.cross(&zaxis).normalize();
var yaxis = zaxis.cross(&xaxis).normalize();
// Column major order?
var cmo = M44f32{ .data = [][4]f32{
[]f32{ xaxis.x(), yaxis.x(), zaxis.x(), 0 },
[]f32{ xaxis.y(), yaxis.y(), zaxis.y(), 0 },
[]f32{ xaxis.z(), yaxis.z(), zaxis.z(), 0 },
[]f32{ -xaxis.dot(eye), -yaxis.dot(eye), -zaxis.dot(eye), 1 },
} };
// Row major order?
var rmo = M44f32{ .data = [][4]f32{
[]f32{ xaxis.x(), xaxis.y(), xaxis.z(), -xaxis.dot(eye) },
[]f32{ yaxis.x(), yaxis.y(), yaxis.z(), -yaxis.dot(eye) },
[]f32{ zaxis.x(), zaxis.y(), zaxis.z(), -zaxis.dot(eye) },
[]f32{ 0, 0, 0, 1 },
} };
var result = cmo;
if (DBG) warn("math3d.lookAtRh: result\n{}", &result);
return result;
}
test "lookat" {
var width: f32 = 640;
var height: f32 = 480;
var scn_x: f32 = undefined;
var scn_y: f32 = undefined;
var coord: V3f32 = undefined;
var screen: V2f32 = undefined;
var point: V2f32 = undefined;
var eye = V3f32.init(0, 0, -10);
var target = V3f32.init(0, 0, 0);
var view_matrix = lookAtLh(&eye, &target, &V3f32.unitY());
const expected = M44f32{ .data = [][4]f32{
[]f32{ 1.00000, 0.00000, 0.00000, 0.00000 },
[]f32{ 0.00000, 1.00000, 0.00000, 0.00000 },
[]f32{ 0.00000, 0.00000, 1.00000, 0.00000 },
[]f32{ 0.00000, 0.00000, 10.00000, 1.00000 },
} };
assert(matrix.approxEql(&view_matrix, &expected, 7));
coord = V3f32.init(0, 0, 0);
screen = projectToScreenCoord(width, height, coord, &view_matrix);
if (DBG) warn("math3d.lookAtLh: coord={} screen={}\n", &coord, &screen);
assert(screen.x() == 320);
assert(screen.y() == 240);
coord = V3f32.init(0.1, 0.1, 0);
screen = projectToScreenCoord(width, height, coord, &view_matrix);
if (DBG) warn("math3d.lookAtLh: coord={} screen={}\n", &coord, &screen);
point = pointToScreenCoord(width, height, 0.1, 0.1);
if (DBG) warn("math3d.lookAtLh: point={}\n", &point);
assert(screen.x() == point.x());
assert(screen.y() == point.y());
coord = V3f32.init(-0.1, -0.1, 0);
screen = projectToScreenCoord(width, height, coord, &view_matrix);
if (DBG) warn("math3d.lookAtLh: coord={} screen={}\n", &coord, &screen);
point = pointToScreenCoord(width, height, -0.1, -0.1);
if (DBG) warn("math3d.lookAtLh: point={}\n", &point);
assert(screen.x() == point.x());
assert(screen.y() == point.y());
} | lookat.zig |
const std = @import("std");
const util = @import("util.zig");
const data = @embedFile("../data/day12.txt");
const Input = struct {
nodes: std.StringHashMap(std.ArrayList([]const u8)),
node_masks: std.StringHashMap(u25),
allocator: std.mem.Allocator,
pub fn init(input_text: []const u8, allocator: std.mem.Allocator) !@This() {
var input = Input{
.nodes = std.StringHashMap(std.ArrayList([]const u8)).init(allocator),
.node_masks = std.StringHashMap(u25).init(allocator),
.allocator = allocator,
};
errdefer input.deinit();
try input.nodes.ensureTotalCapacity(25);
try input.node_masks.ensureTotalCapacity(25);
var lines = std.mem.tokenize(u8, input_text, "\r\n");
var node_count: u5 = 0;
while (lines.next()) |line| {
var kv = std.mem.tokenize(u8, line, "-");
const node1 = kv.next().?;
const node2 = kv.next().?;
if (input.nodes.getOrPut(node1)) |result| {
if (!result.found_existing) {
result.value_ptr.* = try std.ArrayList([]const u8).initCapacity(input.allocator, 25);
try input.node_masks.put(node1, @as(u25, 1) << node_count);
node_count += 1;
}
try result.value_ptr.append(node2);
} else |_| {
print("GetOrPut error\n", .{});
}
// TODO: do it again
if (input.nodes.getOrPut(node2)) |result| {
if (!result.found_existing) {
result.value_ptr.* = try std.ArrayList([]const u8).initCapacity(input.allocator, 25);
try input.node_masks.put(node2, @as(u25, 1) << node_count);
node_count += 1;
}
try result.value_ptr.append(node1);
} else |_| {
print("GetOrPut error\n", .{});
}
}
return input;
}
pub fn deinit(self: *@This()) void {
var itor = self.nodes.valueIterator();
while (itor.next()) |val| {
val.deinit();
}
self.nodes.deinit();
self.node_masks.deinit();
}
};
fn numPathsToEnd(input: Input, node: []const u8, visited: u25, can_visit_twice: bool) i64 {
if (std.mem.eql(u8, node, "end")) {
return 1;
}
var new_visited = visited;
var new_can_visit_twice = can_visit_twice;
if (std.ascii.isLower(node[0])) {
const mask = input.node_masks.get(node).?;
assert(mask != 0);
if ((new_visited & mask) != 0) {
// we've already been here. Can we visit twice?
if (!new_can_visit_twice or std.mem.eql(u8, node, "start")) {
return 0; // can't visit this node twice
}
new_can_visit_twice = false; // no more double-visits on this path
}
new_visited |= mask; // mark node as visited
}
var sum: i64 = 0;
const neighbors = input.nodes.get(node).?;
for (neighbors.items) |neighbor| {
sum += numPathsToEnd(input, neighbor, new_visited, new_can_visit_twice);
}
return sum;
}
fn part1(input: Input) i64 {
return numPathsToEnd(input, "start", 0, false);
}
fn part2(input: Input) i64 {
return numPathsToEnd(input, "start", 0, true);
}
const test_data =
\\start-A
\\start-b
\\A-c
\\A-b
\\b-d
\\A-end
\\b-end
;
const part1_test_solution: ?i64 = 10;
const part1_solution: ?i64 = 4720;
const part2_test_solution: ?i64 = 36;
const part2_solution: ?i64 = 147848;
const test_data2 =
\\dc-end
\\HN-start
\\start-kj
\\dc-start
\\dc-HN
\\LN-dc
\\HN-end
\\kj-sa
\\kj-HN
\\kj-dc
;
const test_data3 =
\\fs-end
\\he-DX
\\fs-he
\\start-DX
\\pj-DX
\\end-zg
\\zg-sl
\\zg-pj
\\pj-he
\\RW-he
\\fs-DX
\\pj-RW
\\zg-RW
\\start-pj
\\he-WI
\\zg-he
\\pj-fs
\\start-RW
;
// Just boilerplate below here, nothing to see
fn testPart1() !void {
var test_input = try Input.init(test_data, std.testing.allocator);
defer test_input.deinit();
if (part1_test_solution) |solution| {
try std.testing.expectEqual(solution, part1(test_input));
}
var test_input2 = try Input.init(test_data2, std.testing.allocator);
defer test_input2.deinit();
try std.testing.expectEqual(@as(i64, 19), part1(test_input2));
var test_input3 = try Input.init(test_data3, std.testing.allocator);
defer test_input3.deinit();
try std.testing.expectEqual(@as(i64, 226), part1(test_input3));
var timer = try std.time.Timer.start();
var input = try Input.init(data, std.testing.allocator);
defer input.deinit();
if (part1_solution) |solution| {
try std.testing.expectEqual(solution, part1(input));
print("part1 took {d:9.3}ms\n", .{@intToFloat(f64, timer.lap()) / 1000000.0});
}
}
fn testPart2() !void {
var test_input = try Input.init(test_data, std.testing.allocator);
defer test_input.deinit();
if (part2_test_solution) |solution| {
try std.testing.expectEqual(solution, part2(test_input));
}
var test_input2 = try Input.init(test_data2, std.testing.allocator);
defer test_input2.deinit();
try std.testing.expectEqual(@as(i64, 103), part2(test_input2));
var test_input3 = try Input.init(test_data3, std.testing.allocator);
defer test_input3.deinit();
try std.testing.expectEqual(@as(i64, 3509), part2(test_input3));
var timer = try std.time.Timer.start();
var input = try Input.init(data, std.testing.allocator);
defer input.deinit();
if (part2_solution) |solution| {
try std.testing.expectEqual(solution, part2(input));
print("part2 took {d:9.3}ms\n", .{@intToFloat(f64, timer.lap()) / 1000000.0});
}
}
pub fn main() !void {
try testPart1();
try testPart2();
}
test "part1" {
try testPart1();
}
test "part2" {
try testPart2();
}
// Useful stdlib functions
const tokenize = std.mem.tokenize;
const split = std.mem.split;
const parseInt = std.fmt.parseInt;
const min = std.math.min;
const max = std.math.max;
const print = std.debug.print;
const expect = std.testing.expect;
const assert = std.debug.assert; | src/day12.zig |
const std = @import("std");
const allocator = std.heap.page_allocator;
const assert = std.debug.assert;
const hash = std.hash;
const math = std.math;
const mem = std.mem;
const time = @import("./time.zig");
const bits = @import("./bits.zig");
const deflate = @import("deflate.zig");
const implode = @import("implode.zig");
const reduce = @import("reduce.zig");
const shrink = @import("shrink.zig");
const SIZE_MAX = math.maxInt(usize);
const UINT16_MAX = math.maxInt(u16);
const UINT32_MAX = math.maxInt(u32);
fn strlen(str: [*:0]const u8) usize {
return mem.indexOfSentinel(u8, 0x0, str);
}
fn crc32(data: [*]const u8, size: usize) u32 {
return hash.Crc32.hash(data[0..size]);
}
pub const CallbackError = error{
WriteCallbackError,
};
pub const zipiter_t: type = usize; // Zip archive member iterator.
pub const zip_t: type = struct {
num_members: u16, // Number of members.
comment: [*]const u8, // Zip file comment (not terminated).
comment_len: u16, // Zip file comment length.
members_begin: zipiter_t, // Iterator to the first member.
members_end: zipiter_t, // Iterator to the end of members.
src: [*]const u8,
src_len: usize,
};
pub const method_t: type = enum(u4) {
ZIP_STORE, // 0,
ZIP_SHRINK, // 1,
ZIP_REDUCE1, // 2,
ZIP_REDUCE2, // 3,
ZIP_REDUCE3, // 4,
ZIP_REDUCE4, //5,
ZIP_IMPLODE, // 6,
NA, // 7, not available
ZIP_DEFLATE, // 8
};
fn method_to_comp_factor(m: method_t) u3 {
var method = @intCast(i16, @enumToInt(m));
var first_reduce_method = @intCast(i16, @enumToInt(method_t.ZIP_REDUCE1));
var comp_factor = method - first_reduce_method + 1;
return @intCast(u3, comp_factor);
}
pub const zipmemb_t: type = struct {
name: [*]const u8, // Member name (not null terminated).
name_len: u16, // Member name length.
mtime: time.time_t, // Modification time.
comp_size: u32, // Compressed size.
comp_data: [*]const u8, // Compressed data.
made_by_ver: u16, // Made-by version, e.g. 20 for PKZip 2.0.
method: method_t, // Compression method.
imp_large_wnd: bool, // For implode: compressed with 8K window?
imp_lit_tree: bool, // For implode: Huffman coded literals?
uncomp_size: u32, // Uncompressed size.
crc32: u32, // CRC-32 checksum.
comment: [*]const u8, // Comment (not null terminated).
comment_len: u16, // Comment length.
is_dir: bool, // Whether this is a directory.
next: zipiter_t, // Iterator to the next member.
};
// Read 16/32 bits little-endian and bump p forward afterwards.
inline fn READ16(p: *[*]const u8) u16 {
p.* += 2;
return bits.read16le(p.* - 2);
}
inline fn READ32(p: *[*]const u8) u32 {
p.* += 4;
return bits.read32le(p.* - 4);
}
// Write 16/32 bits little-endian and bump p forward afterwards.
inline fn WRITE16(p: *[*]u8, x: u16) void {
bits.write16le(p.*, x);
p.* += 2;
}
inline fn WRITE32(p: *[*]u8, x: u32) void {
bits.write32le(p.*, x);
p.* += 4;
}
// End of Central Directory Record.
const eocdr_t: type = struct {
disk_nbr: u16, // Number of this disk.
cd_start_disk: u16, // Nbr. of disk with start of the CD.
disk_cd_entries: u16, // Nbr. of CD entries on this disk.
cd_entries: u16, // Nbr. of Central Directory entries.
cd_size: u32, // Central Directory size in bytes.
cd_offset: u32, // Central Directory file offset.
comment_len: u16, // Archive comment length.
comment: [*]const u8, // Archive comment.
};
// Size of the End of Central Directory Record, not including comment.
const EOCDR_BASE_SZ = 22;
const EOCDR_SIGNATURE = 0x06054b50; // "PK\5\6" little-endian.
const MAX_BACK_OFFSET = (1024 * 100);
pub fn find_eocdr(r: *eocdr_t, src: [*]const u8, src_len: usize) bool {
var back_offset: usize = 0;
var p: [*]const u8 = undefined;
var signature: u32 = 0;
back_offset = 0;
while (back_offset <= MAX_BACK_OFFSET) : (back_offset += 1) {
if (src_len < EOCDR_BASE_SZ + back_offset) {
break;
}
p = src[src_len - EOCDR_BASE_SZ - back_offset .. src_len].ptr;
signature = READ32(&p);
if (signature == EOCDR_SIGNATURE) {
r.disk_nbr = READ16(&p);
r.cd_start_disk = READ16(&p);
r.disk_cd_entries = READ16(&p);
r.cd_entries = READ16(&p);
r.cd_size = READ32(&p);
r.cd_offset = READ32(&p);
r.comment_len = READ16(&p);
r.comment = @ptrCast([*:0]const u8, p);
assert(@ptrToInt(p) == @ptrToInt(&src[src_len - back_offset])); // "All fields read."
if (r.comment_len > back_offset) {
return false;
}
return true;
}
}
return false;
}
pub fn write_eocdr(dst: [*]u8, r: *const eocdr_t) usize {
var p: [*]u8 = dst;
WRITE32(&p, EOCDR_SIGNATURE);
WRITE16(&p, r.disk_nbr);
WRITE16(&p, r.cd_start_disk);
WRITE16(&p, r.disk_cd_entries);
WRITE16(&p, r.cd_entries);
WRITE32(&p, r.cd_size);
WRITE32(&p, r.cd_offset);
WRITE16(&p, r.comment_len);
assert(@ptrToInt(p) - @ptrToInt(dst) == EOCDR_BASE_SZ);
if (r.comment_len != 0) {
mem.copy(u8, p[0..r.comment_len], r.comment[0..r.comment_len]);
p += r.comment_len;
}
return @intCast(usize, @ptrToInt(p) - @ptrToInt(dst));
}
const EXT_ATTR_DIR = @as(u32, 1) << 4;
const EXT_ATTR_ARC = @as(u32, 1) << 5;
// Central File Header (Central Directory Entry)
const cfh_t: type = struct {
made_by_ver: u16, // Version made by.
extract_ver: u16, // Version needed to extract.
gp_flag: u16, // General-purpose bit flag.
method: u16, // Compression method.
mod_time: u16, // Modification time.
mod_date: u16, // Modification date.
crc32: u32, // CRC-32 checksum.
comp_size: u32, // Compressed size.
uncomp_size: u32, // Uncompressed size.
name_len: u16, // Filename length.
extra_len: u16, // Extra data length.
comment_len: u16, // Comment length.
disk_nbr_start: u16, // Disk nbr. where file begins.
int_attrs: u16, // Internal file attributes.
ext_attrs: u32, // External file attributes.
lfh_offset: u32, // Local File Header offset.
name: [*]const u8, // Filename (not null terminated)
extra: [*]const u8, // Extra data such as Unix file ownership information, higher resolution modification date and time, or Zip64 fields
comment: [*]const u8, // File comment. (not null terminated)
};
// Size of a Central File Header, not including name, extra, and comment.
const CFH_BASE_SZ = 46;
const CFH_SIGNATURE = 0x02014b50; // "PK\1\2" little-endian.
pub fn read_cfh(cfh: *cfh_t, src: [*]const u8, src_len: usize, offset: usize) bool {
var p: [*]const u8 = undefined;
var signature: u32 = 0;
if (offset > src_len or src_len - offset < CFH_BASE_SZ) {
return false;
}
p = src[offset..src_len].ptr;
signature = READ32(&p);
if (signature != CFH_SIGNATURE) {
return false;
}
cfh.made_by_ver = READ16(&p);
cfh.extract_ver = READ16(&p);
cfh.gp_flag = READ16(&p);
cfh.method = READ16(&p);
cfh.mod_time = READ16(&p);
cfh.mod_date = READ16(&p);
cfh.crc32 = READ32(&p);
cfh.comp_size = READ32(&p);
cfh.uncomp_size = READ32(&p);
cfh.name_len = READ16(&p);
cfh.extra_len = READ16(&p);
cfh.comment_len = READ16(&p);
cfh.disk_nbr_start = READ16(&p);
cfh.int_attrs = READ16(&p);
cfh.ext_attrs = READ32(&p);
cfh.lfh_offset = READ32(&p);
cfh.name = p;
cfh.extra = cfh.name + cfh.name_len;
cfh.comment = cfh.extra + cfh.extra_len;
assert(@ptrToInt(p) == @ptrToInt(&src[offset + CFH_BASE_SZ])); // "All fields read."
if (src_len - offset - CFH_BASE_SZ < @intCast(usize, cfh.name_len) + cfh.extra_len + cfh.comment_len) {
return false;
}
return true;
}
pub fn write_cfh(dst: [*]u8, cfh: *const cfh_t) usize {
var p: [*]u8 = dst;
WRITE32(&p, CFH_SIGNATURE);
WRITE16(&p, cfh.made_by_ver);
WRITE16(&p, cfh.extract_ver);
WRITE16(&p, cfh.gp_flag);
WRITE16(&p, cfh.method);
WRITE16(&p, cfh.mod_time);
WRITE16(&p, cfh.mod_date);
WRITE32(&p, cfh.crc32);
WRITE32(&p, cfh.comp_size);
WRITE32(&p, cfh.uncomp_size);
WRITE16(&p, cfh.name_len);
WRITE16(&p, cfh.extra_len);
WRITE16(&p, cfh.comment_len);
WRITE16(&p, cfh.disk_nbr_start);
WRITE16(&p, cfh.int_attrs);
WRITE32(&p, cfh.ext_attrs);
WRITE32(&p, cfh.lfh_offset);
assert(@ptrToInt(p) - @ptrToInt(dst) == CFH_BASE_SZ);
if (cfh.name_len != 0) {
mem.copy(u8, p[0..cfh.name_len], cfh.name[0..cfh.name_len]);
p += cfh.name_len;
}
if (cfh.extra_len != 0) {
mem.copy(u8, p[0..cfh.extra_len], cfh.extra[0..cfh.extra_len]);
p += cfh.extra_len;
}
if (cfh.comment_len != 0) {
mem.copy(u8, p[0..cfh.comment_len], cfh.comment[0..cfh.comment_len]);
p += cfh.comment_len;
}
return @intCast(usize, @ptrToInt(p) - @ptrToInt(dst));
}
// Local File Header.
const lfh_t: type = struct {
extract_ver: u16,
gp_flag: u16,
method: u16,
mod_time: u16,
mod_date: u16,
crc32: u32,
comp_size: u32,
uncomp_size: u32,
name_len: u16,
extra_len: u16,
name: [*]const u8,
extra: [*]const u8,
};
// Size of a Local File Header, not including name and extra.
const LFH_BASE_SZ = 30;
const LFH_SIGNATURE = 0x04034b50; // "PK\3\4" little-endian.
pub fn read_lfh(lfh: *lfh_t, src: [*]const u8, src_len: usize, offset: usize) bool {
var p: [*]const u8 = undefined;
var signature: u32 = 0;
if (offset > src_len or src_len - offset < LFH_BASE_SZ) {
return false;
}
p = src[offset..src_len].ptr;
signature = READ32(&p);
if (signature != LFH_SIGNATURE) {
return false;
}
lfh.extract_ver = READ16(&p);
lfh.gp_flag = READ16(&p);
lfh.method = READ16(&p);
lfh.mod_time = READ16(&p);
lfh.mod_date = READ16(&p);
lfh.crc32 = READ32(&p);
lfh.comp_size = READ32(&p);
lfh.uncomp_size = READ32(&p);
lfh.name_len = READ16(&p);
lfh.extra_len = READ16(&p);
lfh.name = p;
lfh.extra = lfh.name + lfh.name_len;
assert(@ptrToInt(p) == @ptrToInt(&src[offset + LFH_BASE_SZ])); // "All fields read."
if (src_len - offset - LFH_BASE_SZ < lfh.name_len + lfh.extra_len) {
return false;
}
return true;
}
pub fn write_lfh(dst: [*]u8, lfh: *const lfh_t) usize {
var p: [*]u8 = dst;
WRITE32(&p, LFH_SIGNATURE);
WRITE16(&p, lfh.extract_ver);
WRITE16(&p, lfh.gp_flag);
WRITE16(&p, lfh.method);
WRITE16(&p, lfh.mod_time);
WRITE16(&p, lfh.mod_date);
WRITE32(&p, lfh.crc32);
WRITE32(&p, lfh.comp_size);
WRITE32(&p, lfh.uncomp_size);
WRITE16(&p, lfh.name_len);
WRITE16(&p, lfh.extra_len);
assert(@ptrToInt(p) - @ptrToInt(dst) == LFH_BASE_SZ);
if (lfh.name_len != 0) {
mem.copy(u8, p[0..lfh.name_len], lfh.name[0..lfh.name_len]);
p += lfh.name_len;
}
if (lfh.extra_len != 0) {
mem.copy(u8, p[0..lfh.extra_len], lfh.name[0..lfh.extra_len]);
p += lfh.extra_len;
}
return @intCast(usize, @ptrToInt(p) - @ptrToInt(dst));
}
// Convert DOS date and time to time_t.
pub fn dos2ctime(dos_date: u16, dos_time: u16) time.time_t {
var tm: time.tm_t = time.tm_t{};
tm.tm_sec = @intCast(i16, (dos_time & 0x1f) * 2); // Bits 0--4: Secs divided by 2.
tm.tm_min = @intCast(i16, dos_time >> 5) & 0x3f; // Bits 5--10: Minute.
tm.tm_hour = @intCast(i16, dos_time >> 11); // Bits 11-15: Hour (0--23).
tm.tm_mday = @intCast(i16, (dos_date & 0x1f)); // Bits 0--4: Day (1--31).
tm.tm_mon = ((@intCast(i16, dos_date) >> 5) & 0xf) - 1; // Bits 5--8: Month (1--12).
tm.tm_year = (@intCast(i16, dos_date) >> 9) + 80; // Bits 9--15: Year-1980.
tm.tm_isdst = -1;
return time.mktime(&tm);
}
// Convert time_t to DOS date and time.
// The valid range of MS-DOS dates is January 1, 1980, to December 31, 2099
// https://docs.microsoft.com/en-us/windows/win32/api/oleauto/nf-oleauto-dosdatetimetovarianttime
pub fn ctime2dos(t: time.time_t, dos_date: *u16, dos_time: *u16) !void {
var tm: *time.tm_t = try time.localtime(&t);
// cannot store a date prior to the year 1980
// returns MS/DOS time format epoch
if (tm.tm_year - 80 < 0) {
dos_time.* = 0; // Time: 00:00:00
dos_date.* = 0;
dos_date.* |= 1; // Bits 0--4: Day: 01 (1).
dos_date.* |= 1 << 5; // Bits 5--8: Month: Jan (1).
dos_date.* |= 0 << 9; // Bits 9--15: Year: 1980 (0).
return;
}
// cannot store a date after the year 2099
if (tm.tm_year - 80 > 119) {
dos_time.* = 0;
dos_time.* |= @as(u16, 58); // Second: 58.
dos_time.* |= @as(u16, 59) << 5; // Minute: 59.
dos_time.* |= @as(u16, 23) << 11; // Hour: 23.
dos_date.* = 0;
dos_date.* |= 31; // Day: 01 (31).
dos_date.* |= 12 << 5; // Month: Dec (12).
dos_date.* |= 119 << 9; // Year: 2099 (119).
return;
}
dos_time.* = 0;
dos_time.* |= @intCast(u16, @divTrunc(tm.tm_sec, 2)); // Bits 0--4: Second divided by two.
dos_time.* |= @intCast(u16, tm.tm_min) << 5; // Bits 5--10: Minute.
dos_time.* |= @intCast(u16, tm.tm_hour) << 11; // Bits 11-15: Hour.
dos_date.* = 0;
dos_date.* |= @intCast(u16, tm.tm_mday); // Bits 0--4: Day (1--31).
dos_date.* |= @intCast(u16, tm.tm_mon + 1) << 5; // Bits 5--8: Month (1--12).
dos_date.* |= @intCast(u16, tm.tm_year - 80) << 9; // Bits 9--15: Year from 1980.
}
// Initialize zip based on the source data. Returns true on success, or false
// if the data could not be parsed as a valid Zip file.
pub fn zip_read(zip: *zip_t, src: [*]const u8, src_len: usize) bool {
var eocdr: eocdr_t = undefined;
var cfh: cfh_t = undefined;
var lfh: lfh_t = undefined;
var i: usize = 0;
var offset: usize = 0;
var comp_data: [*]const u8 = undefined;
zip.src = src;
zip.src_len = src_len;
if (!find_eocdr(&eocdr, src, src_len)) {
return false;
}
if (eocdr.disk_nbr != 0 or eocdr.cd_start_disk != 0 or
eocdr.disk_cd_entries != eocdr.cd_entries)
{
return false; // Cannot handle multi-volume archives.
}
zip.num_members = eocdr.cd_entries;
zip.comment = eocdr.comment;
zip.comment_len = eocdr.comment_len;
offset = eocdr.cd_offset;
zip.members_begin = offset;
// Read the member info and do a few checks.
i = 0;
while (i < eocdr.cd_entries) : (i += 1) {
if (!read_cfh(&cfh, src, src_len, offset)) {
return false;
}
if ((cfh.gp_flag & 1) == 1) {
return false; // The member is encrypted.
}
if (cfh.method != @enumToInt(method_t.ZIP_STORE) and
cfh.method != @enumToInt(method_t.ZIP_SHRINK) and
cfh.method != @enumToInt(method_t.ZIP_REDUCE1) and
cfh.method != @enumToInt(method_t.ZIP_REDUCE2) and
cfh.method != @enumToInt(method_t.ZIP_REDUCE3) and
cfh.method != @enumToInt(method_t.ZIP_REDUCE4) and
cfh.method != @enumToInt(method_t.ZIP_IMPLODE) and
cfh.method != @enumToInt(method_t.ZIP_DEFLATE))
{
return false; // Unsupported compression method.
}
if (cfh.method == @enumToInt(method_t.ZIP_STORE) and
cfh.uncomp_size != cfh.comp_size)
{
return false;
}
if (cfh.disk_nbr_start != 0) {
return false; // Cannot handle multi-volume archives.
}
if (mem.indexOfScalar(u8, cfh.name[0..cfh.name_len], 0x00) != null) {
return false; // Bad filename.
}
if (!read_lfh(&lfh, src, src_len, cfh.lfh_offset)) {
return false;
}
comp_data = lfh.extra + lfh.extra_len;
if (cfh.comp_size > src_len - @intCast(usize, @ptrToInt(comp_data) - @ptrToInt(src))) {
return false; // Member data does not fit in src.
}
offset += CFH_BASE_SZ + cfh.name_len + cfh.extra_len + cfh.comment_len;
}
zip.members_end = offset;
return true;
}
// Get the Zip archive member through iterator it.
pub fn zip_member(zip: *const zip_t, it: zipiter_t) zipmemb_t {
var cfh: cfh_t = undefined;
var lfh: lfh_t = undefined;
var ok: bool = false;
var m: zipmemb_t = undefined;
assert(it >= zip.members_begin and it < zip.members_end);
ok = read_cfh(&cfh, zip.src, zip.src_len, it);
assert(ok);
ok = read_lfh(&lfh, zip.src, zip.src_len, cfh.lfh_offset);
assert(ok);
m.name = cfh.name;
m.name_len = cfh.name_len;
m.mtime = dos2ctime(cfh.mod_date, cfh.mod_time);
m.comp_size = cfh.comp_size;
m.comp_data = lfh.extra + lfh.extra_len;
m.method = @intToEnum(method_t, @intCast(u4, cfh.method));
m.made_by_ver = cfh.made_by_ver;
m.imp_large_wnd = if (m.method == method_t.ZIP_IMPLODE) (cfh.gp_flag & 2) == 2 else false;
m.imp_lit_tree = if (m.method == method_t.ZIP_IMPLODE) (cfh.gp_flag & 4) == 4 else false;
m.uncomp_size = cfh.uncomp_size;
m.crc32 = cfh.crc32;
m.comment = cfh.comment;
m.comment_len = cfh.comment_len;
m.is_dir = (cfh.ext_attrs & EXT_ATTR_DIR) != 0;
m.next = it + CFH_BASE_SZ + cfh.name_len + cfh.extra_len + cfh.comment_len;
assert(m.next <= zip.members_end);
return m;
}
// Extract a zip member into dst. Returns true on success. The CRC-32 is not
// checked.
pub fn zip_extract_member(m: *const zipmemb_t, dst: [*]u8) !bool {
var src_used: usize = 0;
var dst_used: usize = 0;
var comp_factor: u3 = 0;
switch (m.method) {
method_t.ZIP_STORE => {
assert(m.comp_size == m.uncomp_size);
mem.copy(u8, dst[0..m.comp_size], m.comp_data[0..m.comp_size]);
return true;
},
method_t.ZIP_SHRINK => {
if (shrink.hwunshrink(m.comp_data, m.comp_size, &src_used, dst, m.uncomp_size, &dst_used) != shrink.unshrnk_stat_t.HWUNSHRINK_OK) {
return false;
}
if (src_used != m.comp_size or dst_used != m.uncomp_size) {
return false;
}
return true;
},
method_t.ZIP_REDUCE1,
method_t.ZIP_REDUCE2,
method_t.ZIP_REDUCE3,
method_t.ZIP_REDUCE4,
=> {
comp_factor = method_to_comp_factor(m.method);
if (reduce.hwexpand(m.comp_data, m.comp_size, m.uncomp_size, comp_factor, &src_used, dst) != reduce.expand_stat_t.HWEXPAND_OK) {
return false;
}
if (src_used != m.comp_size) {
return false;
}
return true;
},
method_t.ZIP_IMPLODE => {
// If the compressed data assumes an incorrect minimum backref
// length because of the PKZip 1.01/1.02 bug, the length of the
// decompressed data will likely not match the expectations, in
// which case we try pk101_bug_compat mode.
if (((try implode.hwexplode(
m.comp_data,
m.comp_size,
m.uncomp_size,
m.imp_large_wnd,
m.imp_lit_tree,
false, // pk101_bug_compat=false
&src_used,
dst,
)) == implode.explode_stat_t.HWEXPLODE_OK) and
src_used == m.comp_size)
{
return true;
}
if ((try implode.hwexplode(
m.comp_data,
m.comp_size,
m.uncomp_size,
m.imp_large_wnd,
m.imp_lit_tree,
true, // pk101_bug_compat=true
&src_used,
dst,
)) == implode.explode_stat_t.HWEXPLODE_OK and
src_used == m.comp_size)
{
return true;
}
return false;
},
method_t.ZIP_DEFLATE => {
if (deflate.hwinflate(m.comp_data, m.comp_size, &src_used, dst, m.uncomp_size, &dst_used) != deflate.inf_stat_t.HWINF_OK) {
return false;
}
if (src_used != m.comp_size or dst_used != m.uncomp_size) {
return false;
}
return true;
},
else => unreachable,
}
assert(false); // "Invalid method."
return false;
}
// Write a Zip file containing num_memb members into dst, which must be large
// enough to hold the resulting data. Returns the number of bytes written, which
// is guaranteed to be less than or equal to the result of zip_max_size() when
// called with the corresponding arguments. comment shall be a null-terminated
// string or null. callback shall be null or point to a function which will
// get called after the compression of each member.
pub fn zip_write(
dst: [*]u8,
num_memb: u16,
filenames: ?[*][*:0]const u8,
file_data: ?[*][*]const u8,
file_sizes: ?[*]const u32,
mtimes: ?[*]const time.time_t,
comment: ?[*:0]const u8,
method: method_t,
callback: ?fn (filename: [*:0]const u8, method: method_t, size: u32, comp_size: u32) CallbackError!void,
) !u32 {
var i: u16 = 0;
var p: [*]u8 = undefined;
var eocdr: eocdr_t = undefined;
var cfh: cfh_t = undefined;
var lfh: lfh_t = undefined;
var ok: bool = false;
var name_len: u16 = 0;
var data_dst: [*]u8 = undefined;
var data_dst_sz: usize = 0;
var comp_sz: usize = 0;
var lfh_offset: u32 = 0;
var cd_offset: u32 = 0;
var eocdr_offset: u32 = 0;
p = dst;
// Write Local File Headers and compressed or stored data.
i = 0;
while (i < num_memb) : (i += 1) {
assert(filenames != null);
assert(strlen(filenames.?[i]) <= UINT16_MAX);
name_len = @intCast(u16, strlen(filenames.?[i]));
data_dst = p + LFH_BASE_SZ + name_len;
data_dst_sz = if (file_sizes.?[i] > 0) file_sizes.?[i] - 1 else 0;
if (method == method_t.ZIP_SHRINK and
file_sizes.?[i] > 0 and
shrink.hwshrink(
file_data.?[i],
file_sizes.?[i],
data_dst,
data_dst_sz,
&comp_sz,
)) {
lfh.method = @enumToInt(method_t.ZIP_SHRINK);
assert(comp_sz <= UINT32_MAX);
lfh.comp_size = @intCast(u32, comp_sz);
lfh.gp_flag = 0;
lfh.extract_ver = (0 << 8) | 10; // DOS | PKZip 1.0
} else if ((method == method_t.ZIP_REDUCE1 or
method == method_t.ZIP_REDUCE2 or
method == method_t.ZIP_REDUCE3 or
method == method_t.ZIP_REDUCE4) and
reduce.hwreduce(
file_data.?[i],
file_sizes.?[i],
method_to_comp_factor(method),
data_dst,
data_dst_sz,
&comp_sz,
)) {
lfh.method = @enumToInt(method);
assert(comp_sz <= UINT32_MAX);
lfh.comp_size = @intCast(u32, comp_sz);
lfh.gp_flag = 0;
lfh.extract_ver = (0 << 8) | 10; // DOS | PKZip 1.0
} else if (method == method_t.ZIP_IMPLODE and
implode.hwimplode(
file_data.?[i],
file_sizes.?[i],
true, // large_wnd = true
true, // lit_tree = true
data_dst,
data_dst_sz,
&comp_sz,
)) {
lfh.method = @enumToInt(method_t.ZIP_IMPLODE);
assert(comp_sz <= UINT32_MAX);
lfh.comp_size = @intCast(u32, comp_sz);
lfh.gp_flag = (0x1 << 1); // large_wnd
lfh.gp_flag |= (0x1 << 2); // lit_tree
lfh.extract_ver = (0 << 8) | 10; // DOS | PKZip 1.0
} else if (method == method_t.ZIP_DEFLATE and
deflate.hwdeflate(
file_data.?[i],
file_sizes.?[i],
data_dst,
data_dst_sz,
&comp_sz,
)) {
lfh.method = @enumToInt(method_t.ZIP_DEFLATE);
assert(comp_sz <= UINT32_MAX);
lfh.comp_size = @intCast(u32, comp_sz);
lfh.gp_flag = (0x1 << 1);
lfh.extract_ver = (0 << 8) | 20; // DOS | PKZip 2.0
} else {
mem.copy(u8, data_dst[0..file_sizes.?[i]], file_data.?[i][0..file_sizes.?[i]]);
lfh.method = @enumToInt(method_t.ZIP_STORE);
lfh.comp_size = file_sizes.?[i];
lfh.gp_flag = 0;
lfh.extract_ver = (0 << 8) | 10; // DOS | PKZip 1.0
}
if (callback != null) {
try callback.?(filenames.?[i], @intToEnum(method_t, @intCast(u4, lfh.method)), file_sizes.?[i], lfh.comp_size);
}
try ctime2dos(mtimes.?[i], &lfh.mod_date, &lfh.mod_time);
lfh.crc32 = crc32(file_data.?[i], file_sizes.?[i]);
lfh.uncomp_size = file_sizes.?[i];
lfh.name_len = name_len;
lfh.extra_len = 0;
lfh.name = @ptrCast([*]const u8, filenames.?[i]);
p += write_lfh(p, &lfh);
p += lfh.comp_size;
}
assert(@intCast(usize, @ptrToInt(p) - @ptrToInt(dst)) <= UINT32_MAX);
cd_offset = @intCast(u32, @ptrToInt(p) - @ptrToInt(dst));
// Write the Central Directory based on the Local File Headers.
lfh_offset = 0;
i = 0;
while (i < num_memb) : (i += 1) {
ok = read_lfh(&lfh, dst, SIZE_MAX, lfh_offset);
assert(ok);
cfh.made_by_ver = lfh.extract_ver;
cfh.extract_ver = lfh.extract_ver;
cfh.gp_flag = lfh.gp_flag;
cfh.method = lfh.method;
cfh.mod_time = lfh.mod_time;
cfh.mod_date = lfh.mod_date;
cfh.crc32 = lfh.crc32;
cfh.comp_size = lfh.comp_size;
cfh.uncomp_size = lfh.uncomp_size;
cfh.name_len = lfh.name_len;
cfh.extra_len = 0;
cfh.comment_len = 0;
cfh.disk_nbr_start = 0;
cfh.int_attrs = 0;
cfh.ext_attrs = EXT_ATTR_ARC;
cfh.lfh_offset = lfh_offset;
cfh.name = lfh.name;
p += write_cfh(p, &cfh);
lfh_offset += LFH_BASE_SZ + lfh.name_len + lfh.comp_size;
}
assert(@intCast(usize, @ptrToInt(p) - @ptrToInt(dst)) <= UINT32_MAX);
eocdr_offset = @intCast(u32, @ptrToInt(p) - @ptrToInt(dst));
// Write the End of Central Directory Record.
eocdr.disk_nbr = 0;
eocdr.cd_start_disk = 0;
eocdr.disk_cd_entries = num_memb;
eocdr.cd_entries = num_memb;
eocdr.cd_size = eocdr_offset - cd_offset;
eocdr.cd_offset = cd_offset;
eocdr.comment_len = @intCast(u16, if (comment == null) 0 else strlen(comment.?));
eocdr.comment = if (comment == null) "" else comment.?;
p += write_eocdr(p, &eocdr);
assert(@intCast(usize, @ptrToInt(p) - @ptrToInt(dst)) <= zip_max_size(num_memb, filenames, file_sizes, comment));
return @intCast(u32, @ptrToInt(p) - @ptrToInt(dst));
}
// Compute an upper bound on the dst size required by zip_write() for an
// archive with num_memb members with certain filenames, sizes, and archive
// comment. Returns zero on error, e.g. if a filename is longer than 2^16-1, or
// if the total file size is larger than 2^32-1.
pub fn zip_max_size(
num_memb: u16,
filenames: ?[*][*:0]const u8,
file_sizes: ?[*]const u32,
comment: ?[*:0]const u8,
) u32 {
var comment_len: usize = 0;
var name_len: usize = 0;
var total: u64 = 0;
var i: u16 = 0;
comment_len = if (comment == null) 0 else strlen(comment.?);
if (comment_len > UINT16_MAX) {
return 0;
}
total = EOCDR_BASE_SZ + comment_len; // EOCDR
i = 0;
while (i < num_memb) : (i += 1) {
assert(filenames != null);
assert(file_sizes != null);
name_len = strlen(filenames.?[i]);
if (name_len > UINT16_MAX) {
return 0;
}
total += CFH_BASE_SZ + name_len; // Central File Header
total += LFH_BASE_SZ + name_len; // Local File Header
total += file_sizes.?[i]; // Uncompressed data size.
}
if (total > UINT32_MAX) {
return 0;
}
return @intCast(u32, total);
} | src/zip.zig |
const std = @import("std");
const wren = @import("wren");
pub var alloc = std.testing.allocator;
pub const Point = struct {
size:f64 = 0,
pub fn setSize (vm:?*wren.VM) callconv(.C) void {
if(wren.getSlotForeign(vm, 0)) |ptr| {
var point = @ptrCast(*Point,@alignCast(@alignOf(*Point),ptr));
var nsize:f64 = wren.getSlotDouble(vm, 1);
std.debug.print(" [+] Setting point to: {d}\n",.{nsize});
if(nsize < 1.0) {
wren.setSlotString(vm, 0, "That is way too small!");
wren.abortFiber(vm, 0);
return;
}
point.*.size = nsize;
std.debug.print(" [+] Point is now: {d}\n",.{nsize});
}
}
};
pub fn main() anyerror!void {
// Set up a VM configuration
var config:wren.Configuration = undefined;
wren.initConfiguration(&config);
config.writeFn = writeFn;
config.errorFn = errorFn;
config.bindForeignMethodFn = bindForeignMethodFn;
config.bindForeignClassFn = bindForeignClassFn;
config.loadModuleFn = loadModuleFn;
// Create VM from our config
var vm = wren.newVM(&config);
defer wren.freeVM(vm);
// Interpret code in the "main" module
std.debug.print("\n=== Basic Test ===\n",.{});
runCode(vm,"main",
\\ System.print("Hello from Wren!")
\\ System.print("Testing line 2!")
);
// Interpret known-bad code
std.debug.print("\n=== Have an Error ===\n",.{});
runCode(vm,"main",
\\ System.print("Hello from error!)
\\ System.prit("Ohno!")
);
std.debug.print("\n=== Calling Zig from Wren ===\n",.{});
runCode(vm,"main",
\\ class Math {
\\ foreign static add(a, b)
\\ }
\\ System.print(Math.add(3,5))
);
std.debug.print("\n=== Calling Wren from Zig ===\n",.{});
runCode(vm,"main",
\\ class TestClass {
\\ static doubleUp(num) {
\\ return num + num
\\ }
\\ }
);
// Get the method signature handle
var mhandle:?*wren.Handle = wren.makeCallHandle(vm,"doubleUp(_)");
defer wren.releaseHandle(vm,mhandle);
// Get a handle to the class that owns the method
wren.ensureSlots(vm, 2);
wren.getVariable(vm, "main", "TestClass", 0);
var testClass:?*wren.Handle = wren.getSlotHandle(vm, 0);
defer wren.releaseHandle(vm,testClass);
// Set up local data
var needs_adding:usize = 41;
std.debug.print("Before Call: {}\n",.{needs_adding});
// Load the slots with the receiver (class) and parameters
wren.setSlotHandle(vm, 0, testClass);
wren.setSlotDouble(vm, 1, @intToFloat(f64,needs_adding));
// Call the method
var cres:wren.InterpretResult = wren.call(vm,mhandle);
_=cres;
needs_adding = @floatToInt(usize,wren.getSlotDouble(vm,0));
std.debug.print("Call result: {}",.{needs_adding});
std.debug.print("\n=== Using foreign classes ===\n",.{});
runCode(vm,"main",
\\ foreign class Point {
\\ construct create(size) {}
\\
\\ foreign setSize(size)
\\ }
\\ var point = Point.create(20)
\\ point.setSize(40)
\\ point.setSize(0)
);
std.debug.print("\n=== Imports ===\n",.{});
runCode(vm,"main",
\\ System.print("start import")
\\ import "test"
\\ System.print("end import")
);
}
pub fn runCode (vm:?*wren.VM,module:[*c]const u8,code:[*c]const u8) void {
var call_res:wren.InterpretResult = wren.interpret(vm,module,code);
switch (call_res) {
wren.RESULT_COMPILE_ERROR => std.debug.print("Compile Error!\n",.{}),
wren.RESULT_RUNTIME_ERROR => std.debug.print("Runtime Error!\n",.{}),
wren.RESULT_SUCCESS => std.debug.print("Success!\n",.{}),
else => unreachable,
}
}
pub fn writeFn(vm:?*wren.VM, text:[*c]const u8) callconv(.C) void {
_=vm;
std.debug.print("{s}",.{text});
}
pub fn errorFn(vm:?*wren.VM, err_type:wren.ErrorType, module:[*c]const u8, line:c_int, msg:[*c]const u8) callconv(.C) void {
_=vm;
var err_desc = switch(err_type) {
wren.ERROR_COMPILE => "Compile Error",
wren.ERROR_RUNTIME => "Runtime Error",
wren.ERROR_STACK_TRACE => "Stack Trace",
else => unreachable,
};
std.debug.print("{s} @ ",.{err_desc});
if(module) |mod| {
std.debug.print("{s}:{}\n",.{mod,line});
} else std.debug.print("{s}:{}\n",.{"[null]",line});
if(msg) |mg| {
std.debug.print(" {s}\n",.{mg});
} else std.debug.print(" {s}\n",.{"[null]"});
}
pub fn bindForeignMethodFn(
vm:?*wren.VM,
module:[*c]const u8,
className:[*c]const u8,
isStatic:bool,
signature:[*c]const u8
) callconv(.C) wren.ForeignMethodFnC {
_=vm;
std.debug.print(" [+] Looking up method {s}:{s}.{s}\n",.{module,className,signature});
if (wren.util.matches(module,"main")) {
if (wren.util.matches(className,"Math")) {
if (isStatic and wren.util.matches(signature,"add(_,_)")) {
std.debug.print(" [+] Found mathAdd\n",.{});
return mathAdd; // C function for Math.add(_,_).
}
// Other foreign methods on Math...
}
if (wren.util.matches(className, "Point")) {
if (!isStatic and wren.util.matches(signature,"setSize(_)")) {
std.debug.print(" [+] Found setSize\n",.{});
return Point.setSize;
}
}
}
unreachable;
// Other modules...
}
pub fn bindForeignClassFn (
vm:?*wren.VM,
module:[*c]const u8,
className:[*c]const u8
) callconv(.C) wren.ForeignClassMethods {
std.debug.print(" [+] Foreign start\n",.{});
_=vm;
if (wren.util.matches(module, "main")) {
if (wren.util.matches(className, "Point")) {
std.debug.print(" [+] Foreign bind\n",.{});
return .{
.allocate = pointAllocate,
.finalize = pointFinalize,
};
}
}
std.debug.print(" [+] Foreign BIND FAIL\n",.{});
return .{
.allocate = null,
.finalize = null
};
}
pub fn pointAllocate(vm:?*wren.VM) callconv(.C) void {
std.debug.print(" [+] ALLOC Point\n",.{});
var ptr:?*c_void = wren.setSlotNewForeign(vm, 0, 0, @sizeOf(Point));
var size_param:f64 = wren.getSlotDouble(vm, 1);
var pt_ptr:*Point = @ptrCast(*Point,@alignCast(@alignOf(*Point),ptr));
pt_ptr.* = Point { .size = size_param };
std.debug.print(" [+] ALLOC Point Done\n",.{});
}
pub fn pointFinalize(data:?*c_void) callconv(.C) void {
_=data;
std.debug.print(" [+] Finalize Point\n",.{});
// Do cleanup here
}
pub fn mathAdd (vm:?*wren.VM) callconv(.C) void {
var a:f64 = wren.getSlotDouble(vm, 1);
var b:f64 = wren.getSlotDouble(vm, 2);
wren.setSlotDouble(vm, 0, a + b);
}
pub fn loadModuleFn(vm:?*wren.VM,name:[*c]const u8) callconv(.C) wren.LoadModuleResult {
_=vm;
var src = wren.util.loadWrenSourceFile(alloc,std.mem.span(name)) catch unreachable;
return .{
.source = src,
.onComplete = loadModuleCompleteFn, // ?fn, called on done running to free mem
.userData = null, // ?*c_void
};
}
pub fn loadModuleCompleteFn (vm:?*wren.VM,module:[*c]const u8,result:wren.LoadModuleResult) callconv(.C) void {
_=vm;
_=module;
if(result.source != null) {
var slice_len = std.mem.sliceTo(result.source,0).len;
alloc.free(result.source[0..slice_len]);
}
} | example/all_the_old_things.zig |
usingnamespace @import("bits.zig");
usingnamespace @import("system.zig");
var __psp_cwd: [PATH_MAX + 1]u8 = [_]u8{0} ** (PATH_MAX + 1);
pub fn __psp_init_cwd(path: ?*c_void) void {
if (path != null) {
var base_path: [PATH_MAX + 1]u8 = undefined;
var end: ?[*]u8 = null;
_ = strncpy(@ptrCast(?[*]u8, &base_path), @ptrCast([*]const u8, path), PATH_MAX);
base_path[PATH_MAX] = 0;
end = strrchr(@ptrCast([*]u8, base_path[0..]), '/');
if (end != null) {
(end.? + 1).* = 0;
_ = chdir(base_path[0..]);
}
}
}
pub fn strncpy(dest: ?[*]u8, src: [*]const u8, num: usize) ?[*]u8 {
if (dest == null) {
return null;
}
var ptr = dest.?;
var ptr2 = src;
var i: isize = @intCast(isize, num);
while (ptr[0] != 0 and i >= 0) : (i -= 1) {
ptr[0] = ptr2[0];
ptr += 1;
ptr2 += 1;
}
ptr[0] = 0;
return ptr;
}
pub fn strrchr(c: [*]u8, tbf: u8) ?[*]u8 {
var found: ?[*]u8 = null;
var ptr = c;
var i: usize = 0;
while (c[i] != 0) : (i += 1) {
if (c[i] == tbf) {
found = @ptrCast([*]u8, &c[i]);
}
}
return found;
}
usingnamespace @import("../sdk/pspiofilemgr.zig");
pub fn chdir(path: [*]const u8) c_int {
var dest: [PATH_MAX + 1]u8 = undefined;
var uid: c_int = 0;
if (__psp_path_absolute(path, dest[0..], PATH_MAX) < 0) {
errno = ENAMETOOLONG;
return -1;
}
uid = sceIoDopen(dest[0..]);
if (uid < 0) {
errno = ENOTDIR;
return -1;
}
_ = sceIoDclose(uid);
_ = sceIoChdir(dest[0..]);
_ = strcpy(__psp_cwd[0..], dest[0..]);
return 0;
}
// Like strcpy, but returns 0 if the string doesn't fit
pub fn __psp_safe_strcpy(out: [*]u8, in: [*]const u8, maxlen: usize) c_int {
var ptr = out;
var ptr2 = in;
var len: usize = maxlen;
while (len > 0 and ptr2[0] != 0) : (len -= 1) {
ptr[0] = ptr2[0];
ptr += 1;
ptr2 += 1;
}
if (len < 1) return 0;
ptr[0] = 0;
return 1;
}
const std = @import("std");
pub fn __psp_path_absolute(in: [*]const u8, out: [*]u8, len: usize) c_int {
var dr: isize = 0;
// See what the relative URL starts with
dr = __psp_get_drive(in);
if (dr > 0 and in[@intCast(usize, dr)] == '/') {
//It starts with "drive:/", so it's already absolute
if (__psp_safe_strcpy(out, in, len) == 0)
return -1;
} else if (in[0] == '/') {
// It's absolute, but missing the drive, so use cwd's drive
if (strlen(__psp_cwd[0..]) >= len)
return -2;
_ = strcpy(out, __psp_cwd[0..]);
dr = __psp_get_drive(out);
out[@intCast(usize, dr)] = 0;
if (__psp_safe_strcat(out, in, len) == 0)
return -3;
} else {
// It's not absolute, so append it to the current cwd
if (strlen(__psp_cwd[0..]) >= len)
return -4;
_ = strcpy(out, __psp_cwd[0..]);
var stat = __psp_safe_strcat(out, "/", len);
if (stat == 0) {
return -6;
}
if (__psp_safe_strcat(out, in, len) == 0)
return -7;
}
// Now normalize the pathname portion
dr = __psp_get_drive(out);
if (dr < 0) dr = 0;
return __psp_path_normalize(out + @intCast(usize, dr), @intCast(usize, @intCast(isize, len) - dr));
}
pub fn __psp_get_drive(d: [*]const u8) c_int {
var i: usize = 0;
while (d[i] != 0) : (i += 1) {
if (!((d[i] >= 'a' and d[i] <= 'z') or (d[i] >= '0' and d[i] <= '9')))
break;
}
if (d[i] == ':') return @intCast(c_int, i + 1);
return -1;
}
pub fn strcpy(destination: ?[*]u8, source: [*]const u8) ?[*]u8 {
// return if no memory is allocated to the destination
if (destination == null) {
return null;
}
// take a pointer pointing to the beginning of destination string
var ptr = destination.?;
var ptr2 = source;
// copy the C-string pointed by source into the array
// pointed by destination
while (ptr2[0] != 0) {
ptr[0] = ptr2[0];
ptr += 1;
ptr2 += 1;
}
// include the terminating null character
ptr[0] = 0;
// destination is returned by standard strcpy()
return ptr;
}
pub fn strlen(s: [*]const u8) usize {
var i: usize = 0;
while (s[i] != 0) : (i += 1) {}
return i;
}
pub fn __psp_safe_strcat(out: [*]u8, in: [*]const u8, maxlen: usize) c_int {
var len = maxlen;
var ptr = out;
while (ptr[0] != 0) : (len -= 1) {
ptr += 1;
}
return __psp_safe_strcpy(ptr, in, len);
}
pub fn __psp_path_normalize(out: [*]u8, len: usize) c_int {
var i: isize = 0;
var j: isize = 0;
var first: usize = 0;
var next: usize = 0;
// First append "/" to make the rest easier */
if (__psp_safe_strcat(out, "/", len) == 0) return -10;
// Convert "//" to "/" */
while (out[@intCast(usize, i) + 1] != 0) : (i += 1) {
if (out[@intCast(usize, i)] == '/' and out[@intCast(usize, i) + 1] == '/') {
j = i + 1;
while (out[@intCast(usize, j)] != 0) : (j += 1) {
out[@intCast(usize, j)] = out[@intCast(usize, j + 1)];
}
i -= 1;
}
}
// Convert "/./" to "/" */
i = 0;
while (out[@intCast(usize, i)] != 0 and out[@intCast(usize, i + 1)] != 0 and out[@intCast(usize, i + 2)] != 0) : (i += 1) {
if (out[@intCast(usize, i)] == '/' and out[@intCast(usize, i + 1)] == '.' and out[@intCast(usize, i + 2)] == '/') {
j = i + 1;
while (out[@intCast(usize, j)] != 0) : (j += 1) {
out[@intCast(usize, j)] = out[@intCast(usize, j + 2)];
}
i -= 1;
}
}
// Convert "/asdf/../" to "/" until we can't anymore. Also
// convert leading "/../" to "/" */
first = 0;
next = 0;
while (true) {
// If a "../" follows, remove it and the parent */
if (out[next + 1] != 0 and out[next + 1] == '.' and
out[next + 2] != 0 and out[next + 2] == '.' and
out[next + 3] != 0 and out[next + 3] == '/')
{
j = 0;
while (out[first + @intCast(usize, j + 1)] != 0) : (j += 1) {
out[first + @intCast(usize, j + 1)] = out[next + @intCast(usize, j + 4)];
}
first = 0;
next = 0;
continue;
}
// Find next slash */
first = next;
next = first + 1;
while (out[next] != 0 and out[next] != '/') : (next += 1) {
continue;
}
if (out[next] == 0) break;
}
// Remove trailing "/" */
i = 1;
while (out[@intCast(usize, i)] != 0) : (i += 1) {
continue;
}
if (i >= 1 and out[@intCast(usize, i - 1)] == '/')
out[@intCast(usize, i - 1)] = 0;
return 0;
} | src/psp/os/cwd.zig |
const std = @import("std");
const fs = std.fs;
const math = std.math;
const mem = std.mem;
const whitelist = std.ComptimeStringMap([]const u32, .{
.{ "src/cli.zig", &.{ 35, 39 } },
});
fn whitelisted(path: []const u8, line: u32) bool {
const lines = whitelist.get(path) orelse return false;
return mem.indexOfScalar(u32, lines, line) != null;
}
const Stats = struct {
path: []const u8,
assert_count: u32,
function_count: u32,
ratio: f64,
};
var file_stats = std.ArrayListUnmanaged(Stats){};
var seen = std.AutoArrayHashMapUnmanaged(fs.File.INode, void){};
var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){};
const gpa = general_purpose_allocator.allocator();
pub fn main() !void {
const argv = std.os.argv;
for (argv[1..]) |raw_path| {
const path = mem.span(raw_path);
lint_file(path, fs.cwd(), path) catch |err| switch (err) {
error.IsDir, error.AccessDenied => try lint_dir(path, fs.cwd(), path),
else => return err,
};
}
var max_path_len: usize = "total:".len;
var total_assert_count: usize = 0;
var total_function_count: usize = 0;
for (file_stats.items) |stats| {
max_path_len = math.max(max_path_len, stats.path.len);
total_assert_count += stats.assert_count;
total_function_count += stats.function_count;
}
std.sort.sort(Stats, file_stats.items, {}, struct {
fn less_than(_: void, a: Stats, b: Stats) bool {
return a.ratio > b.ratio;
}
}.less_than);
var buffered_writer = std.io.bufferedWriter(std.io.getStdOut().writer());
const stdout = buffered_writer.writer();
try stdout.writeAll("\npath");
try stdout.writeByteNTimes(' ', max_path_len - "path".len);
try stdout.writeAll(" asserts functions ratio\n");
for (file_stats.items) |stats| {
try stdout.writeAll(stats.path);
try stdout.writeByteNTimes(' ', max_path_len - stats.path.len);
try stdout.print(" {d: >7} {d: >9} {d: >5.2}\n", .{
stats.assert_count,
stats.function_count,
stats.ratio,
});
}
try stdout.writeByteNTimes(' ', max_path_len - "total:".len);
try stdout.print("total: {d: >7} {d: >9} {d: >5.2}\n", .{
total_assert_count,
total_function_count,
@intToFloat(f64, total_assert_count) / @intToFloat(f64, total_function_count),
});
try buffered_writer.flush();
}
const LintError = error{
OutOfMemory,
ParseError,
NotUtf8,
} || fs.File.OpenError || fs.File.ReadError || fs.File.WriteError;
fn lint_dir(file_path: []const u8, parent_dir: fs.Dir, parent_sub_path: []const u8) LintError!void {
var dir = try parent_dir.openDir(parent_sub_path, .{ .iterate = true });
defer dir.close();
const stat = try dir.stat();
if (try seen.fetchPut(gpa, stat.inode, {})) |_| return;
var dir_it = dir.iterate();
while (try dir_it.next()) |entry| {
const is_dir = entry.kind == .Directory;
if (is_dir and std.mem.eql(u8, entry.name, "zig-cache")) continue;
if (is_dir or mem.endsWith(u8, entry.name, ".zig")) {
const full_path = try fs.path.join(gpa, &[_][]const u8{ file_path, entry.name });
defer gpa.free(full_path);
if (is_dir) {
try lint_dir(full_path, dir, entry.name);
} else {
try lint_file(full_path, dir, entry.name);
}
}
}
}
fn lint_file(file_path: []const u8, dir: fs.Dir, sub_path: []const u8) LintError!void {
const source_file = try dir.openFile(sub_path, .{});
defer source_file.close();
const stat = try source_file.stat();
if (stat.kind == .Directory) return error.IsDir;
// Add to set after no longer possible to get error.IsDir.
if (try seen.fetchPut(gpa, stat.inode, {})) |_| return;
const source = try source_file.readToEndAllocOptions(
gpa,
math.maxInt(usize),
null,
@alignOf(u8),
0,
);
try check_line_length(source, file_path);
var tree = try std.zig.parse(gpa, source);
defer tree.deinit(gpa);
if (tree.errors.len != 0) return error.ParseError;
const node_tags = tree.nodes.items(.tag);
const main_tokens = tree.nodes.items(.main_token);
const node_datas = tree.nodes.items(.data);
var function_count: u32 = 0;
var assert_count: u32 = 0;
for (node_tags) |tag, node| {
switch (tag) {
.fn_decl => {
function_count += 1;
const body = node_datas[node].rhs;
const body_start = tree.tokenLocation(0, tree.firstToken(body));
const body_end = tree.tokenLocation(0, tree.lastToken(body));
// Add 1 as the count returned by tokenLocation() is
// 0-indexed while most editors start at 1.
const line = @intCast(u32, body_start.line + 1);
const body_lines = body_end.line - body_start.line;
if (body_lines > 70 and !whitelisted(file_path, line)) {
const stderr = std.io.getStdErr().writer();
try stderr.print("{s}:{d} function body exceeds 70 lines ({d} lines)\n", .{
file_path,
line,
body_lines,
});
}
},
.call_one, .call_one_comma => {
const lhs = node_datas[node].lhs;
if (node_tags[lhs] == .identifier and
mem.eql(u8, "assert", tree.tokenSlice(main_tokens[lhs])))
{
assert_count += 1;
}
},
.unreachable_literal => assert_count += 1,
else => {},
}
}
try file_stats.append(gpa, .{
.path = try gpa.dupe(u8, file_path),
.assert_count = assert_count,
.function_count = function_count,
.ratio = @intToFloat(f64, assert_count) / @intToFloat(f64, function_count),
});
}
fn check_line_length(source: []const u8, path: []const u8) !void {
var i: usize = 0;
var line: u32 = 1;
while (mem.indexOfScalar(u8, source[i..], '\n')) |newline| : (line += 1) {
const line_length = std.unicode.utf8CountCodepoints(
source[i..][0..newline],
) catch return error.NotUtf8;
if (line_length > 100 and !whitelisted(path, line)) {
const stderr = std.io.getStdErr().writer();
try stderr.print("{s}:{d} line exceeds 100 columns\n", .{ path, line });
}
i += newline + 1;
}
} | scripts/lint.zig |
const std = @import("std");
const stdx = @import("stdx");
const t = stdx.testing;
pub const document = @import("document.zig");
/// Simple UTF8 buffer that facilitates text editing.
pub const TextBuffer = struct {
buf: std.ArrayList(u8),
num_chars: u32,
const Self = @This();
pub fn init(alloc: std.mem.Allocator, buf: []const u8) !Self {
var new = Self{
.buf = std.ArrayList(u8).init(alloc),
.num_chars = 0,
};
if (buf.len > 0) {
const view = try std.unicode.Utf8View.init(buf);
var iter = view.iterator();
var i: u32 = 0;
while (iter.nextCodepoint()) |_| {
i += 1;
}
new.buf.appendSlice(buf) catch @panic("error");
new.num_chars = i;
}
return new;
}
pub fn deinit(self: Self) void {
self.buf.deinit();
}
pub fn clear(self: *Self) void {
self.buf.clearRetainingCapacity();
self.num_chars = 0;
}
pub fn insertCodepoint(self: *Self, idx: u32, cp: u21) !void {
const len = try std.unicode.utf8CodepointSequenceLength(cp);
const buf_idx = self.getBufferIdx(idx);
const old_len = self.buf.items.len;
self.buf.resize(old_len + len) catch @panic("error");
std.mem.copyBackwards(u8, self.buf.items[buf_idx+len..], self.buf.items[buf_idx..old_len]);
_ = std.unicode.utf8Encode(cp, self.buf.items[buf_idx..buf_idx+len]) catch @panic("error");
self.num_chars += 1;
}
pub fn appendCodepoint(self: *Self, cp: u21) !void {
const len = try std.unicode.utf8CodepointSequenceLength(cp);
const next = self.buf.items.len;
self.buf.resize(next + len) catch @panic("error");
_ = std.unicode.utf8Encode(cp, self.buf.items[next..self.buf.items.len]) catch @panic("error");
self.num_chars += 1;
}
pub fn appendSubStr(self: *Self, str: []const u8) !void {
const view = try std.unicode.Utf8View.init(str);
var iter = view.iterator();
var i: u32 = 0;
while (iter.nextCodepoint()) |_| {
i += 1;
}
self.buf.appendSlice(str) catch @panic("error");
self.num_chars += i;
}
pub fn appendFmt(self: *Self, comptime fmt: []const u8, args: anytype) void {
const next = self.buf.items.len;
self.buf.resize(next + @intCast(usize, std.fmt.count(fmt, args))) catch @panic("error");
_ = std.fmt.bufPrint(self.buf.items[next..], fmt, args) catch @panic("error");
const view = std.unicode.Utf8View.initUnchecked(self.buf.items[next..]);
var iter = view.iterator();
var i: u32 = 0;
while (iter.nextCodepoint()) |_| {
i += 1;
}
self.num_chars += i;
}
pub fn getSubStr(self: Self, start_idx: u32, end_idx: u32) []const u8 {
const range = self.getBufferRange(start_idx, end_idx);
return self.buf.items[range.buf_start_idx..range.buf_end_idx];
}
pub fn removeChar(self: *Self, idx: u32) void {
self.removeSubStr(idx, idx + 1);
}
pub fn removeSubStr(self: *Self, start_idx: u32, end_idx: u32) void {
const range = self.getBufferRange(start_idx, end_idx);
self.buf.replaceRange(range.buf_start_idx, range.buf_end_idx - range.buf_start_idx, "") catch @panic("error");
self.num_chars -= (end_idx - start_idx);
}
fn getBufferIdx(self: Self, idx: u32) u32 {
if (idx == 0) {
return 0;
}
var iter = std.unicode.Utf8View.initUnchecked(self.buf.items).iterator();
var cur_char_idx: u32 = 0;
var cur_buf_idx: u32 = 0;
while (iter.nextCodepointSlice()) |cp_slice| {
cur_char_idx += 1;
cur_buf_idx += @intCast(u32, cp_slice.len);
if (cur_char_idx == idx) {
return cur_buf_idx;
}
}
@panic("error");
}
fn getBufferRange(self: Self, start_idx: u32, end_idx: u32) Range {
var iter = std.unicode.Utf8View.initUnchecked(self.buf.items).iterator();
var i: u32 = 0;
var buf_start_idx: u32 = 0;
var buf_end_idx: u32 = 0;
var cur_buf_idx: u32 = 0;
while (iter.nextCodepointSlice()) |cp_slice| {
if (i == start_idx) {
buf_start_idx = cur_buf_idx;
}
i += 1;
cur_buf_idx += @intCast(u32, cp_slice.len);
if (i == end_idx) {
buf_end_idx = cur_buf_idx;
break;
}
}
return .{
.buf_start_idx = buf_start_idx,
.buf_end_idx = buf_end_idx,
};
}
};
const Range = struct {
buf_start_idx: u32,
buf_end_idx: u32,
};
test "TextBuffer.clear" {
var buf = try TextBuffer.init(t.alloc, "ab🫐c");
defer buf.deinit();
try t.eq(buf.buf.items.len, 7);
try t.eq(buf.num_chars, 4);
buf.clear();
try t.eq(buf.buf.items.len, 0);
try t.eq(buf.num_chars, 0);
}
test "TextBuffer.insertCodepoint" {
var buf = try TextBuffer.init(t.alloc, "");
defer buf.deinit();
try buf.insertCodepoint(0, 97);
try t.eq(buf.num_chars, 1);
try t.eqStr(buf.buf.items, "a");
try buf.insertCodepoint(1, 98);
try t.eq(buf.num_chars, 2);
try t.eqStr(buf.buf.items, "ab");
try buf.insertCodepoint(1, 129744);
try t.eq(buf.num_chars, 3);
try t.eqStr(buf.buf.items, "a🫐b");
// This would test for a backwards memory copy since dst and src would overlap.
try buf.insertCodepoint(1, 97);
try t.eq(buf.num_chars, 4);
try t.eqStr(buf.buf.items, "aa🫐b");
}
test "TextBuffer.appendCodepoint" {
var buf = try TextBuffer.init(t.alloc, "");
defer buf.deinit();
try buf.appendCodepoint(97);
try t.eq(buf.num_chars, 1);
try t.eqStr(buf.buf.items, "a");
try buf.appendCodepoint(129744);
try t.eq(buf.num_chars, 2);
try t.eqStr(buf.buf.items, "a🫐");
}
test "TextBuffer.appendSubStr" {
var buf = try TextBuffer.init(t.alloc, "");
defer buf.deinit();
try buf.appendSubStr("a");
try t.eq(buf.num_chars, 1);
try t.eqStr(buf.buf.items, "a");
try buf.appendSubStr("b🫐c");
try t.eq(buf.num_chars, 4);
try t.eqStr(buf.buf.items, "ab🫐c");
}
test "TextBuffer.appendFmt" {
var buf = try TextBuffer.init(t.alloc, "");
defer buf.deinit();
buf.appendFmt("a", .{});
try t.eq(buf.num_chars, 1);
try t.eqStr(buf.buf.items, "a");
buf.appendFmt("{}", .{123});
try t.eq(buf.num_chars, 4);
try t.eqStr(buf.buf.items, "a123");
}
test "TextBuffer.getSubStr" {
var buf = try TextBuffer.init(t.alloc, "ab🫐c");
defer buf.deinit();
try t.eq(buf.buf.items.len, 7);
try t.eqStr(buf.getSubStr(0, 1), "a");
try t.eqStr(buf.getSubStr(0, 2), "ab");
try t.eqStr(buf.getSubStr(0, 3), "ab🫐");
}
test "TextBuffer.removeSubStr" {
var buf = try TextBuffer.init(t.alloc, "ab🫐c");
defer buf.deinit();
try t.eq(buf.buf.items.len, 7);
buf.removeSubStr(1, 2);
try t.eq(buf.num_chars, 3);
try t.eqStr(buf.buf.items, "a🫐c");
buf.removeSubStr(1, 2);
try t.eq(buf.num_chars, 2);
try t.eqStr(buf.buf.items, "ac");
} | stdx/textbuf/textbuf.zig |
const std = @import("std");
const PixelBuffer = @import("../video.zig").PixelBuffer;
const console_ = @import("../console.zig");
const Config = console_.Config;
const Console = console_.Console;
const Cart = @import("../cart.zig").Cart;
const Cpu = @import("../cpu.zig").Cpu;
const common = @import("common.zig");
const Address = common.Address;
const flags_ = @import("../flags.zig");
const FieldFlags = flags_.FieldFlags;
const setMask = flags_.setMask;
const getMaskBool = flags_.getMaskBool;
pub fn Ppu(comptime config: Config) type {
return struct {
const Self = @This();
cart: *Cart(config),
cpu: *Cpu(config),
reg: Registers(config),
mem: Memory(config),
scanline: u9 = 0,
cycle: u9 = 0,
// internal registers
vram_addr: Address = .{ .value = 0 },
vram_temp: Address = .{ .value = 0 },
fine_x: u3 = 0,
w: bool = false,
sprite_list: SpriteList = SpriteList{},
scanline_sprites: ScanlineSprites = std.mem.zeroes(ScanlineSprites),
pixel_buffer: *PixelBuffer(config.method),
present_frame: bool = false,
pub fn init(console: *Console(config), pixel_buffer: *PixelBuffer(config.method)) Self {
return Self{
.cart = &console.cart,
.cpu = &console.cpu,
.reg = std.mem.zeroes(Registers(config)),
.mem = Memory(config).init(&console.cart),
.pixel_buffer = pixel_buffer,
};
}
pub fn deinit(_: Self) void {}
fn evaluateSpritesFrame(self: *Self) void {
self.sprite_list.reset();
var i: usize = 0;
while (i < 256) : (i += 4) {
if (self.mem.oam[i] < 0xef) {
self.sprite_list.addSprite(.{
.y = self.mem.oam[i],
.tile_index = self.mem.oam[i + 1],
.attributes = self.mem.oam[i + 2],
.x = self.mem.oam[i + 3],
.is_sprite_0 = i == 0,
});
}
}
self.sprite_list.sort();
}
fn evaluateSpritesScanline(self: *Self) void {
const tall_sprites = self.reg.getFlag(.{ .flags = "H" });
self.sprite_list.setYCutoff(@intCast(i16, self.scanline) - if (tall_sprites) @as(i16, 16) else 8);
self.scanline_sprites.sprite_0_index = null;
const unevaluated_sprites = self.sprite_list.getScanlineSprites(@truncate(u8, self.scanline));
for (unevaluated_sprites) |sprite, i| {
const y_offset_16 =
if (getMaskBool(u8, sprite.attributes, 0x80))
@truncate(u4, sprite.y -% self.scanline)
else
@truncate(u4, (self.scanline - sprite.y) -% 1);
const y_offset = @truncate(u3, y_offset_16);
const tile_offset = @as(u14, sprite.tile_index) << 4;
const pattern_offset = blk: {
if (tall_sprites) {
const bank = @as(u14, sprite.tile_index & 1) << 12;
const tile_offset_16 = tile_offset & ~@as(u14, 0x10);
if (y_offset_16 < 8) {
break :blk bank | tile_offset_16;
} else {
break :blk bank | tile_offset_16 | 0x10;
}
} else if (self.reg.getFlag(.{ .field = "ppu_ctrl", .flags = "S" })) {
break :blk 0x1000 | tile_offset;
} else {
break :blk tile_offset;
}
};
const pattern_byte_low = blk: {
var byte = self.mem.read(pattern_offset | y_offset);
if (sprite.attributes & 0x40 != 0) {
byte = @bitReverse(u8, byte);
}
break :blk byte;
};
const pattern_byte_high = blk: {
var byte = self.mem.read(pattern_offset | y_offset | 8);
if (sprite.attributes & 0x40 != 0) {
byte = @bitReverse(u8, byte);
}
break :blk byte;
};
self.scanline_sprites.sprite_pattern_srs1[i].load(pattern_byte_low);
self.scanline_sprites.sprite_pattern_srs2[i].load(pattern_byte_high);
self.scanline_sprites.sprite_attributes[i] = sprite.attributes;
self.scanline_sprites.sprite_x_positions[i] = sprite.x;
if (sprite.is_sprite_0) {
self.scanline_sprites.sprite_0_index = i;
}
}
self.scanline_sprites.sprite_count = unevaluated_sprites.len;
}
fn incCoarseX(self: *Self) void {
if ((self.vram_addr.value & @as(u15, 0x1f)) == 0x1f) {
self.vram_addr.value = (self.vram_addr.value & ~@as(u15, 0x1f)) ^ 0x400;
} else {
self.vram_addr.value +%= 1;
}
}
fn incCoarseY(self: *Self) void {
if ((self.vram_addr.value & 0x7000) != 0x7000) {
self.vram_addr.value += 0x1000;
} else {
self.vram_addr.value &= ~@as(u15, 0x7000);
var y = (self.vram_addr.value & @as(u15, 0x03e0)) >> 5;
if (y == 29) {
y = 0;
self.vram_addr.value ^= 0x0800;
} else if (y == 31) {
y = 0;
} else {
y += 1;
}
self.vram_addr.value = (self.vram_addr.value & ~@as(u15, 0x03e0)) | (y << 5);
}
}
fn renderingEnabled(self: Self) bool {
return self.reg.getFlags(.{ .flags = "sb" }) != 0;
}
pub fn runCycle(self: *Self) void {
switch (self.scanline) {
0...239 => self.runVisibleScanlineCycle(),
240 => {},
241...260 => {},
261 => if (self.renderingEnabled() and self.scanline == 261 and self.cycle >= 280 and self.cycle <= 304) {
// set coarse y
setMask(u15, &self.vram_addr.value, self.vram_temp.value, 0x7be0);
} else {
self.runVisibleScanlineCycle();
},
else => unreachable,
}
if (self.renderingEnabled() and self.scanline < 240 and self.cycle < 256) {
self.drawPixel();
}
self.cycle += 1;
if (self.cycle == 341) {
self.cycle = 0;
self.scanline = (self.scanline + 1) % 262;
self.evaluateSpritesScanline();
}
if (self.scanline == 241 and self.cycle == 1) {
self.reg.setFlag(.{ .field = "ppu_status", .flags = "V" }, true);
if (self.reg.getFlag(.{ .field = "ppu_ctrl", .flags = "V" })) {
self.cpu.setNmi();
}
self.present_frame = true;
} else if (self.scanline == 261 and self.cycle == 1) {
self.reg.setFlags(.{ .field = "ppu_status", .flags = "VS" }, 0);
self.evaluateSpritesFrame();
}
}
fn runVisibleScanlineCycle(self: *Self) void {
if (!self.renderingEnabled() or self.cycle == 0) {
return;
}
if (self.cycle > 257 and self.cycle < 321) {
self.reg.oam_addr = 0;
return;
}
if ((self.cycle & 255) == 0) {
self.incCoarseY();
} else if ((self.cycle & 7) == 0) {
self.incCoarseX();
} else if (self.cycle == 257) {
// set coarse x
setMask(u15, &self.vram_addr.value, self.vram_temp.value, 0x41f);
}
}
fn getBgPattern(self: Self, reverted_v: Address) u2 {
if (!self.reg.getFlag(.{ .flags = "b" })) {
return 0;
}
const nametable_byte: u14 = self.mem.peek(0x2000 | @truncate(u14, reverted_v.value));
const addr = (nametable_byte << 4) | reverted_v.fineY();
const offset = if (self.reg.getFlag(.{ .field = "ppu_ctrl", .flags = "B" })) @as(u14, 0x1000) else 0;
const pattern_table_byte1 = self.mem.peek(addr | offset);
const pattern_table_byte2 = self.mem.peek(addr | 8 | offset);
const p1: u1 = @truncate(u1, pattern_table_byte1 >> (7 - @truncate(u3, self.cycle +% self.fine_x)));
const p2: u1 = @truncate(u1, pattern_table_byte2 >> (7 - @truncate(u3, self.cycle +% self.fine_x)));
return p1 | (@as(u2, p2) << 1);
}
fn getSpriteIndex(self: *Self) ?u8 {
if (!self.reg.getFlag(.{ .flags = "s" })) {
return null;
}
const x = self.cycle;
var index: ?u8 = null;
var i: usize = 0;
while (i < self.scanline_sprites.sprite_count) : (i += 1) {
const sprite_x = self.scanline_sprites.sprite_x_positions[i];
if (sprite_x > x -% 8 and sprite_x <= x) {
self.scanline_sprites.sprite_pattern_srs1[i].feed();
self.scanline_sprites.sprite_pattern_srs2[i].feed();
if (index == null) {
index = @truncate(u8, i);
}
}
}
return index;
}
fn drawPixel(self: *Self) void {
const reverted_v = blk: {
var old_v = self.vram_addr;
const sub: u2 = if (7 - @truncate(u3, self.cycle) >= self.fine_x) 2 else 1;
if (old_v.coarseX() < sub) {
old_v.value ^= 0x400;
}
const new_coarse_x = old_v.coarseX() -% sub;
old_v.value = (old_v.value & ~@as(u15, 0x1f)) | new_coarse_x;
break :blk old_v;
};
const bg_pattern_index = self.getBgPattern(reverted_v);
const sprite_index = self.getSpriteIndex();
var sprite_behind: bool = undefined;
var sprite_pattern_index: u2 = 0;
if (sprite_index) |i| {
sprite_behind = getMaskBool(u8, self.scanline_sprites.sprite_attributes[i], 0x20);
const p1 = self.scanline_sprites.sprite_pattern_srs1[i].get();
const p2 = self.scanline_sprites.sprite_pattern_srs2[i].get();
sprite_pattern_index = p1 | (@as(u2, p2) << 1);
}
const addr = blk: {
if (bg_pattern_index == 0 and sprite_pattern_index == 0) {
break :blk 0x3f00;
} else {
var pattern_index: u2 = undefined;
var attribute_index: u14 = undefined;
var palette_base: u14 = undefined;
if (sprite_pattern_index != 0 and bg_pattern_index != 0) {
if (self.scanline_sprites.sprite_0_index) |i| {
if (sprite_index.? == i) {
self.reg.setFlag(.{ .field = "ppu_status", .flags = "S" }, true);
}
}
}
if (sprite_pattern_index != 0 and !(sprite_behind and bg_pattern_index != 0)) {
pattern_index = sprite_pattern_index;
attribute_index = self.scanline_sprites.sprite_attributes[sprite_index.?];
palette_base = 0x3f10;
} else {
pattern_index = bg_pattern_index;
const attribute_table_byte = self.mem.read(@as(u14, 0x23c0) |
(@as(u14, reverted_v.nametableSelect()) << 10) |
((@as(u14, reverted_v.coarseY()) << 1) & 0x38) |
((reverted_v.coarseX() >> 2) & 7));
const x_quadrant = reverted_v.value & 2;
const y_quadrant = (reverted_v.value >> 4) & 4;
const shift = @truncate(u3, x_quadrant | y_quadrant);
attribute_index = @truncate(u2, attribute_table_byte >> shift);
palette_base = 0x3f00;
}
break :blk palette_base | (attribute_index << 2) | pattern_index;
}
};
const palette_byte = self.mem.peek(addr);
self.pixel_buffer.putPixel(self.cycle, self.scanline, common.palette[palette_byte]);
}
};
}
const SpritePatternShiftRegister = struct {
bits: u8 = 0,
output_bit: u1 = 0,
fn feed(self: *SpritePatternShiftRegister) void {
self.output_bit = @truncate(u1, (self.bits & 0x80) >> 7);
self.bits <<= 1;
}
fn load(self: *SpritePatternShiftRegister, byte: u8) void {
self.bits = byte;
}
fn get(self: SpritePatternShiftRegister) u1 {
return self.output_bit;
}
};
// contains all sprites visible on screen sorted by y position
// initially goes from 0..last_sprite, as setYCutoff is called,
// start_index starts the slice of sprites considered only at
// sprites where y is on or below the current scanline
const SpriteList = struct {
sprites: [64]Sprite = [_]Sprite{Sprite{}} ** 64,
start_index: usize = 0,
end_index: usize = 0,
const Sprite = struct {
y: u8 = 0xff,
tile_index: u8 = 0xff,
attributes: u8 = 0xff,
x: u8 = 0xff,
is_sprite_0: bool = false,
};
fn reset(self: *SpriteList) void {
self.start_index = 0;
self.end_index = 0;
}
fn addSprite(self: *SpriteList, sprite: Sprite) void {
self.sprites[self.end_index] = sprite;
self.end_index += 1;
}
fn sort(self: *SpriteList) void {
const Context = struct {
fn cmp(_: @This(), lhs: Sprite, rhs: Sprite) bool {
return lhs.y < rhs.y;
}
};
std.sort.sort(Sprite, self.sprites[0..self.end_index], Context{}, Context.cmp);
}
fn setYCutoff(self: *SpriteList, y: i16) void {
var i: usize = 0;
for (self.sprites[self.start_index..self.end_index]) |sprite| {
if (sprite.y >= y) {
break;
}
i += 1;
}
self.start_index += i;
}
fn getScanlineSprites(self: SpriteList, y: u8) []const Sprite {
var i: usize = 0;
for (self.sprites[self.start_index..self.end_index]) |sprite| {
if (sprite.y >= y or i == 8) {
break;
}
i += 1;
}
return self.sprites[self.start_index..(self.start_index + i)];
}
};
const ScanlineSprites = struct {
sprite_pattern_srs1: [8]SpritePatternShiftRegister,
sprite_pattern_srs2: [8]SpritePatternShiftRegister,
sprite_attributes: [8]u8,
sprite_x_positions: [8]u8,
sprite_0_index: ?usize,
sprite_count: usize,
};
fn Registers(comptime config: Config) type {
return packed struct {
const Self = @This();
ppu_ctrl: u8,
ppu_mask: u8,
ppu_status: u8,
oam_addr: u8,
oam_data: u8,
ppu_scroll: u8,
ppu_addr: u8,
ppu_data: u8,
const ff_masks = common.RegisterMasks(Self){};
// flag functions do not have side effects even when they should
fn getFlag(self: Self, comptime flags: FieldFlags) bool {
return ff_masks.getFlag(self, flags);
}
fn getFlags(self: Self, comptime flags: FieldFlags) u8 {
return ff_masks.getFlags(self, flags);
}
fn setFlag(self: *Self, comptime flags: FieldFlags, val: bool) void {
return ff_masks.setFlag(self, flags, val);
}
fn setFlags(self: *Self, comptime flags: FieldFlags, val: u8) void {
return ff_masks.setFlags(self, flags, val);
}
pub fn peek(self: Self, i: u3) u8 {
return @truncate(u8, (@bitCast(u64, self) >> (@as(u6, i) * 8)));
}
pub fn read(self: *Self, i: u3) u8 {
var ppu = @fieldParentPtr(Ppu(config), "reg", self);
const val = self.peek(i);
switch (i) {
2 => {
ppu.reg.setFlag(.{ .field = "ppu_status", .flags = "V" }, false);
ppu.w = false;
},
4 => {
return ppu.mem.oam[self.oam_addr];
},
7 => {
const prev = self.ppu_data;
self.ppu_data = ppu.mem.read(@truncate(u14, ppu.vram_addr.value));
ppu.vram_addr.value +%= if (self.getFlag(.{ .flags = "I" })) @as(u8, 32) else 1;
return prev;
},
else => {},
}
return val;
}
pub fn write(self: *Self, i: u3, val: u8) void {
var ppu = @fieldParentPtr(Ppu(config), "reg", self);
var val_u15 = @as(u15, val);
switch (i) {
0 => {
setMask(u15, &ppu.vram_temp.value, (val_u15 & 3) << 10, 0b000_1100_0000_0000);
},
4 => {
ppu.mem.oam[self.oam_addr] = val;
self.oam_addr +%= 1;
},
5 => if (!ppu.w) {
ppu.vram_temp.value = (ppu.vram_temp.value & ~@as(u15, 0x1f)) | (val >> 3);
ppu.fine_x = @truncate(u3, val);
ppu.w = true;
} else {
const old_t = ppu.vram_temp.value & ~@as(u15, 0b111_0011_1110_0000);
ppu.vram_temp.value = old_t | ((val_u15 & 0xf8) << 5) | ((val_u15 & 7) << 12);
ppu.w = false;
},
6 => if (!ppu.w) {
setMask(u15, &ppu.vram_temp.value, (val_u15 & 0x3f) << 8, 0b0111_1111_0000_0000);
ppu.w = true;
} else {
setMask(u15, &ppu.vram_temp.value, val_u15, 0xff);
ppu.vram_addr.value = ppu.vram_temp.value;
ppu.w = false;
},
7 => {
ppu.mem.write(@truncate(u14, ppu.vram_addr.value), val);
ppu.vram_addr.value +%= if (self.getFlag(.{ .flags = "I" })) @as(u8, 32) else 1;
},
else => {},
}
const bytes = @bitCast(u64, self.*);
const shift = @as(u6, i) * 8;
const mask = @as(u64, 0xff) << shift;
self.* = @bitCast(Self, (bytes & ~mask) | @as(u64, val) << shift);
}
};
}
fn Memory(comptime config: Config) type {
return struct {
const Self = @This();
cart: *Cart(config),
nametables: [0x1000]u8,
palettes: [0x20]u8,
oam: [0x100]u8,
address_bus: u14 = 0,
fn init(cart: *Cart(config)) Self {
return Self{
.cart = cart,
.nametables = std.mem.zeroes([0x1000]u8),
.palettes = std.mem.zeroes([0x20]u8),
.oam = std.mem.zeroes([0x100]u8),
};
}
pub fn peek(self: Self, addr: u14) u8 {
return switch (addr) {
0x0000...0x1fff => self.cart.peekChr(addr),
0x2000...0x3eff => self.nametables[self.cart.mirrorNametable(addr)],
0x3f00...0x3fff => if (addr & 3 == 0) self.palettes[addr & 0x0c] else self.palettes[addr & 0x1f],
};
}
pub fn read(self: *Self, addr: u14) u8 {
self.address_bus = addr;
return switch (addr) {
0x0000...0x1fff => self.cart.readChr(addr),
0x2000...0x3eff => self.nametables[self.cart.mirrorNametable(addr)],
0x3f00...0x3fff => if (addr & 3 == 0) self.palettes[addr & 0x0c] else self.palettes[addr & 0x1f],
};
}
pub fn write(self: *Self, addr: u14, val: u8) void {
self.address_bus = addr;
switch (addr) {
0x0000...0x1fff => self.cart.writeChr(addr, val),
0x2000...0x3eff => self.nametables[self.cart.mirrorNametable(addr)] = val,
0x3f00...0x3fff => if (addr & 3 == 0) {
self.palettes[addr & 0x0c] = val;
} else {
self.palettes[addr & 0x1f] = val;
},
}
}
};
} | src/ppu/fast.zig |
const std = @import("std");
const builtin = @import("builtin");
// Description Found Here
// https://www.cmrr.umn.edu/~strupp/serial.html
const CBAUD = 0o000000010017;
const CS5 = 0o0000000;
const CS6 = 0o0000020;
const CS7 = 0o0000040;
const CS8 = 0o0000060;
const CLOCAL = 0o0004000;
const CRTSCTS = 0o020000000000;
const CSTOPB = 0o0000100;
const CREAD = 0o0000200;
const CMSPAR = 0o010000000000;
const INPCK = 0o0000020;
const IXON = 0o0002000;
const IXANY = 0o0004000;
const IXOFF = 0o0010000;
const PARENB = 0o0000400;
const PARODD = 0o0001000;
const VTIME = 5;
const VMIN = 6;
const VSWTC = 7;
const VSTART = 8;
const VSTOP = 9;
const TCIFLUSH = 0;
const TCOFLUSH = 1;
const TCIOFLUSH = 2;
const TCFLSH = 0x540B;
// Parity Not In STM32 Manuall
pub const Parity = enum {
none, // No Parity
even, // Parity On Even Words
odd, // Parity On Odd Words
mark, // Parity Always On
space, // Parity Always Off
};
// Stop Bit Options On STM32
pub const StopBits = enum {
one, // 1 Stop Bit
two, // 2 Stop Bits
};
// Flow Control Options On STM32
pub const FlowControl = enum {
none, // No Flow Control
software, // Software Flow Control
hardware, // Hardware Flow Control
};
pub const WordLength = enum {
five,
six,
seven,
eight,
};
// Standard STM32 Baud Rates Supported By Linux
pub const BaudRate = enum(u32) {
baud1200 = 1200,
baud1800 = 1800,
baud2400 = 2400,
baud4800 = 4800,
baud9600 = 9600,
baud19200 = 19200,
baud38400 = 38400,
baud57600 = 57600,
baud115200 = 115200,
baud230400 = 230400,
baud460800 = 460800,
baud576000 = 576000,
baud921600 = 921600,
};
pub const SerialPort = struct {
baud_rate: BaudRate = .baud9600,
parity: Parity = .none,
stop_bits: StopBits = .one,
word_length: WordLength = .eight,
flowcontrol: FlowControl = .none,
// Functions
// Init the structure
pub fn init(baud_rate: BaudRate, parity: Parity, stop_bits: StopBits, word_length: WordLength, flowcontrol: FlowControl) SerialPort {
return SerialPort {
.baud_rate = baud_rate,
.parity = parity,
.stop_bits = stop_bits,
.word_length = word_length,
.flowcontrol = flowcontrol,
};
}
// Configure the port on Linux
pub fn configure(self: *SerialPort, port: std.fs.File) !void {
switch(builtin.os.tag) {
.linux => {
var settings = try std.os.tcgetattr(port.handle);
settings.iflag = 0;
settings.oflag = 0;
settings.cflag = CREAD;
settings.lflag = 0;
settings.ispeed = 0;
settings.ospeed = 0;
switch (self.parity) {
.none => {},
.odd => settings.cflag |= PARODD,
.even => {},
.mark => settings.cflag |= PARODD | CMSPAR,
.space => settings.cflag |= CMSPAR,
}
if (self.parity != .none) {
settings.oflag |= INPCK;
settings.cflag |= PARENB;
}
switch (self.flowcontrol) {
.none => settings.cflag |= CLOCAL,
.software => settings.iflag |= IXON | IXOFF,
.hardware => settings.cflag |= CRTSCTS,
}
switch (self.stop_bits) {
.one => {},
.two => settings.cflag |= CSTOPB,
}
switch (self.word_length) {
.five => settings.cflag |= CS5,
.six => settings.cflag |= CS6,
.seven => settings.cflag |= CS7,
.eight => settings.cflag |= CS8,
}
const baudmask = baudToLinux(self.baud_rate);
settings.cflag &= ~@as(u32, CBAUD);
settings.cflag |= baudmask;
settings.ispeed = baudmask;
settings.ospeed = baudmask;
settings.cc[VMIN] = 1;
settings.cc[VSTOP] = 0x13; // XOFF
settings.cc[VSTART] = 0x11; // XON
settings.cc[VTIME] = 0;
try std.os.tcsetattr(port.handle, .NOW, settings);
},
else => {
@compileError("Unsupported OS");
}
}
}
};
/// Flushes the serial port `port`. If `input` is set, all pending data in
/// the receive buffer is flushed, if `output` is set all pending data in
/// the send buffer is flushed.
pub fn flushSerialPort(port: std.fs.File, input: bool, output: bool) !void {
switch (builtin.os.tag) {
.linux => {
if (input and output) {
try tcflush(port.handle, TCIOFLUSH);
}
else if (input) {
try tcflush(port.handle, TCIFLUSH);
}
else if (output) {
try tcflush(port.handle, TCOFLUSH);
}
},
else => {
@compileError("unsupported OS, please implement!");
}
}
}
fn tcflush(fd: std.os.fd_t, mode: usize) !void {
if (std.os.linux.syscall3(.ioctl, @bitCast(usize, @as(isize, fd)), TCFLSH, mode) != 0)
return error.FlushError;
}
// Verify Baud Rate
fn baudToLinux(baud: BaudRate) u32 {
return switch (baud) {
.baud1200 => std.os.linux.B1200,
.baud1800 => std.os.linux.B1800,
.baud2400 => std.os.linux.B2400,
.baud4800 => std.os.linux.B4800,
.baud9600 => std.os.linux.B9600,
.baud19200 => std.os.linux.B19200,
.baud38400 => std.os.linux.B38400,
.baud57600 => std.os.linux.B57600,
.baud115200 => std.os.linux.B115200,
.baud230400 => std.os.linux.B230400,
.baud460800 => std.os.linux.B460800,
.baud576000 => std.os.linux.B576000,
.baud921600 => std.os.linux.B921600,
};
} | src/usart.zig |
const std = @import("std");
const testing = std.testing;
const allocator = std.heap.page_allocator;
pub const Map = struct {
rows: usize,
cols: usize,
cells: [2]std.AutoHashMap(Pos, Tile),
curr: usize,
next: usize,
immediate: bool,
pub const Tile = enum(u8) {
Floor = '.',
Empty = 'L',
Used = '#',
};
pub const Pos = struct {
x: usize,
y: usize,
pub fn init(x: usize, y: usize) Pos {
return Pos{
.x = x,
.y = y,
};
}
};
pub fn init(immediate: bool) Map {
var self = Map{
.rows = 0,
.cols = 0,
.cells = undefined,
.curr = 0,
.next = 1,
.immediate = immediate,
};
self.cells[0] = std.AutoHashMap(Pos, Tile).init(allocator);
self.cells[1] = std.AutoHashMap(Pos, Tile).init(allocator);
return self;
}
pub fn deinit(self: *Map) void {
self.cells[1].deinit();
self.cells[0].deinit();
}
pub fn add_line(self: *Map, line: []const u8) void {
if (self.cols == 0) {
self.cols = line.len;
}
if (self.cols != line.len) {
@panic("jagged map");
}
var x: usize = 0;
while (x < self.cols) : (x += 1) {
const tile = switch (line[x]) {
'.' => Tile.Floor,
'L' => Tile.Empty,
'#' => Tile.Used,
else => @panic("TILE"),
};
if (tile == Tile.Floor) continue;
const pos = Pos.init(x, self.rows);
_ = self.cells[self.curr].put(pos, tile) catch unreachable;
}
self.rows += 1;
}
pub fn show(self: Map) void {
std.debug.warn("MAP: {} x {}\n", .{ self.rows, self.cols });
var y: usize = 0;
while (y < self.rows) : (y += 1) {
std.debug.warn("{:4} | ", .{y});
var x: usize = 0;
while (x < self.cols) : (x += 1) {
var label: u8 = '.';
const pos = Pos.init(x, y);
const found = self.cells[self.curr].get(pos);
if (found) |t| {
label = switch (t) {
Tile.Floor => '.',
Tile.Empty => 'L',
Tile.Used => '#',
};
}
std.debug.warn("{c}", .{label});
}
std.debug.warn("\n", .{});
}
}
pub fn step(self: *Map) bool {
var y: usize = 0;
while (y < self.rows) : (y += 1) {
var x: usize = 0;
while (x < self.cols) : (x += 1) {
const pos = Pos.init(x, y);
if (self.cells[self.next].contains(pos)) {
_ = self.cells[self.next].remove(pos);
}
if (!self.cells[self.curr].contains(pos)) continue;
const tile = self.cells[self.curr].get(pos).?;
if (tile == Tile.Floor) continue;
const occupied = self.countAround(pos);
var future = tile;
if (tile == Tile.Empty and occupied == 0) {
future = Tile.Used;
}
const top: usize = if (self.immediate) 4 else 5;
if (tile == Tile.Used and occupied >= top) {
future = Tile.Empty;
}
_ = self.cells[self.next].put(pos, future) catch unreachable;
}
}
const stable = self.isStable();
if (!stable) {
self.curr = 1 - self.curr;
self.next = 1 - self.next;
}
return stable;
}
pub fn run_until_stable(self: *Map) usize {
while (true) {
const equal = self.step();
if (equal) break;
}
var count: usize = 0;
var y: usize = 0;
while (y < self.rows) : (y += 1) {
var x: usize = 0;
while (x < self.cols) : (x += 1) {
const pos = Pos.init(x, y);
if (self.cells[self.curr].get(pos)) |t| {
if (t == Tile.Used) {
count += 1;
}
}
}
}
return count;
}
fn get_delta(dx: isize, dy: isize) usize {
return @intCast(usize, dy + 1) * 3 + @intCast(usize, dx + 1);
}
fn countAround(self: *Map, pos: Pos) usize {
var count: usize = 0;
var dy: isize = -1;
while (dy <= 1) : (dy += 1) {
var dx: isize = -1;
while (dx <= 1) : (dx += 1) {
if (dy == 0 and dx == 0) continue;
var sy = @intCast(isize, pos.y);
var sx = @intCast(isize, pos.x);
var diff: usize = 0;
while (true) : (diff += 1) {
if (self.immediate and diff >= 1) break;
sy += dy;
sx += dx;
if (sy < 0 or sy >= self.rows) break;
if (sx < 0 or sx >= self.cols) break;
const ny = @intCast(usize, sy);
const nx = @intCast(usize, sx);
const np = Pos.init(nx, ny);
if (!self.cells[self.curr].contains(np)) continue;
const nt = self.cells[self.curr].get(np).?;
if (nt == Tile.Floor) continue;
if (nt == Tile.Used) count += 1;
break;
}
}
}
return count;
}
fn isStable(self: *Map) bool {
var y: usize = 0;
while (y < self.rows) : (y += 1) {
var x: usize = 0;
while (x < self.cols) : (x += 1) {
const pos = Pos.init(x, y);
var tl = Tile.Floor;
if (self.cells[self.curr].get(pos)) |t| {
tl = t;
}
var tr = Tile.Floor;
if (self.cells[self.next].get(pos)) |t| {
tr = t;
}
if (tl != tr) {
return false;
}
}
}
return true;
}
};
test "sample immediate" {
const data: []const u8 =
\\L.LL.LL.LL
\\LLLLLLL.LL
\\L.L.L..L..
\\LLLL.LL.LL
\\L.LL.LL.LL
\\L.LLLLL.LL
\\..L.L.....
\\LLLLLLLLLL
\\L.LLLLLL.L
\\L.LLLLL.LL
;
// #.##.##.##
// #######.##
// #.#.#..#..
// ####.##.##
// #.##.##.##
// #.#####.##
// ..#.#.....
// ##########
// #.######.#
// #.#####.##
// After a second round, the seats with four or more occupied adjacent seats become empty again:
//
// #.LL.L#.##
// #LLLLLL.L#
// L.L.L..L..
// #LLL.LL.L#
// #.LL.LL.LL
// #.LLLL#.##
// ..L.L.....
// #LLLLLLLL#
// #.LLLLLL.L
// #.#LLLL.##
// This process continues for three more rounds:
//
// #.##.L#.##
// #L###LL.L#
// L.#.#..#..
// #L##.##.L#
// #.##.LL.LL
// #.###L#.##
// ..#.#.....
// #L######L#
// #.LL###L.L
// #.#L###.##
// #.#L.L#.##
// #LLL#LL.L#
// L.L.L..#..
// #LLL.##.L#
// #.LL.LL.LL
// #.LL#L#.##
// ..L.L.....
// #L#LLLL#L#
// #.LLLLLL.L
// #.#L#L#.##
// #.#L.L#.##
// #LLL#LL.L#
// L.#.L..#..
// #L##.##.L#
// #.#L.LL.LL
// #.#L#L#.##
// ..L.L.....
// #L#L##L#L#
// #.LLLLLL.L
// #.#L#L#.##
var map = Map.init(true);
defer map.deinit();
var it = std.mem.split(u8, data, "\n");
while (it.next()) |line| {
map.add_line(line);
}
map.show();
// var equal: bool = false;
// equal = map.step();
// map.show();
// try testing.expect(!equal);
// equal = map.step();
// map.show();
// try testing.expect(!equal);
// equal = map.step();
// map.show();
// try testing.expect(!equal);
// equal = map.step();
// map.show();
// try testing.expect(!equal);
// equal = map.step();
// map.show();
// try testing.expect(!equal);
// equal = map.step();
// map.show();
// try testing.expect(equal);
const count = map.run_until_stable();
try testing.expect(count == 37);
}
test "sample ranged" {
const data: []const u8 =
\\L.LL.LL.LL
\\LLLLLLL.LL
\\L.L.L..L..
\\LLLL.LL.LL
\\L.LL.LL.LL
\\L.LLLLL.LL
\\..L.L.....
\\LLLLLLLLLL
\\L.LLLLLL.L
\\L.LLLLL.LL
;
var map = Map.init(false);
defer map.deinit();
var it = std.mem.split(u8, data, "\n");
while (it.next()) |line| {
map.add_line(line);
}
map.show();
// var equal: bool = false;
// equal = map.step();
// map.show();
// try testing.expect(!equal);
// equal = map.step();
// map.show();
// try testing.expect(!equal);
// equal = map.step();
// map.show();
// try testing.expect(!equal);
// equal = map.step();
// map.show();
// try testing.expect(!equal);
// equal = map.step();
// map.show();
// try testing.expect(!equal);
// equal = map.step();
// map.show();
// try testing.expect(!equal);
// equal = map.step();
// map.show();
// try testing.expect(equal);
const count = map.run_until_stable();
try testing.expect(count == 26);
} | 2020/p11/map.zig |
const std = @import("std");
const testing = std.testing;
const expect = testing.expect;
const expectEqual = testing.expectEqual;
const expectApproxEqRel = testing.expectApproxEqRel;
pub const Vector3 = packed struct {
x: f32,
y: f32,
z: f32,
pub fn init(x: f32, y: f32, z: f32) Vector3 {
return .{ .x = x, .y = y, .z = z };
}
pub fn set(value: f32) Vector3 {
return .{ .x = value, .y = value, .z = value };
}
pub fn normalize(v: Vector3) Vector3 {
return multiplyScalar(v, 1.0 / length(v));
}
pub fn length(v: Vector3) f32 {
return std.math.sqrt(dot(v, v));
}
pub fn squaredLength(v: Vector3) f32 {
return dot(v, v);
}
pub fn dot(a: Vector3, b: Vector3) f32 {
return a.x * b.x + a.y * b.y + a.z * b.z;
}
pub fn add(a: Vector3, b: Vector3) Vector3 {
return init(a.x + b.x, a.y + b.y, a.z + b.z);
}
pub fn subtract(a: Vector3, b: Vector3) Vector3 {
return init(a.x - b.x, a.y - b.y, a.z - b.z);
}
pub fn multiply(a: Vector3, b: Vector3) Vector3 {
return init(a.x * b.x, a.y * b.y, a.z * b.z);
}
pub fn divide(a: Vector3, b: Vector3) Vector3 {
return init(a.x / b.x, a.y / b.y, a.z / b.z);
}
pub fn addScalar(a: Vector3, b: f32) Vector3 {
return init(a.x + b, a.y + b, a.z + b);
}
pub fn subtractScalar(a: Vector3, b: f32) Vector3 {
return init(a.x - b, a.y - b, a.z - b);
}
pub fn multiplyScalar(a: Vector3, b: f32) Vector3 {
return init(a.x * b, a.y * b, a.z * b);
}
pub fn divideScalar(a: Vector3, b: f32) Vector3 {
return init(a.x / b, a.y / b, a.z / b);
}
};
test "Vector3" {
var v1 = Vector3.init(1, 2, 3);
var v2 = Vector3.init(5, 6, 7);
var v: Vector3 = undefined;
var s: f32 = undefined;
v = Vector3.init(1, 2, 3);
try expectEqual(@as(f32, 1.0), v.x);
try expectEqual(@as(f32, 2.0), v.y);
try expectEqual(@as(f32, 3.0), v.z);
v = Vector3.set(4);
try expectEqual(@as(f32, 4.0), v.x);
try expectEqual(@as(f32, 4.0), v.y);
try expectEqual(@as(f32, 4.0), v.z);
v = v1.add(v2);
try expectEqual(Vector3.init(6, 8, 10), v);
v = v1.addScalar(14);
try expectEqual(Vector3.init(15, 16, 17), v);
v = v1.subtract(v2);
try expectEqual(Vector3.init(-4, -4, -4), v);
v = v1.subtractScalar(-4);
try expectEqual(Vector3.init(5, 6, 7), v);
v = v1.multiply(v2);
try expectEqual(Vector3.init(5, 12, 21), v);
v = v1.multiplyScalar(-4);
try expectEqual(Vector3.init(-4, -8, -12), v);
v = v1.divide(v2);
try expectApproxEqRel(@as(f32, 1.0/5.0), v.x, 0.0001);
try expectApproxEqRel(@as(f32, 2.0/6.0), v.y, 0.0001);
try expectApproxEqRel(@as(f32, 3.0/7.0), v.z, 0.0001);
v = v1.divideScalar(2);
try expectApproxEqRel(@as(f32, 1.0/2.0), v.x, 0.0001);
try expectApproxEqRel(@as(f32, 2.0/2.0), v.y, 0.0001);
try expectApproxEqRel(@as(f32, 3.0/2.0), v.z, 0.0001);
s = Vector3.dot(v1, v2);
try expectApproxEqRel(@as(f32, 38.0), s, 0.0001);
s = Vector3.squaredLength(v1);
try expectApproxEqRel(@as(f32, 14.0), s, 0.0001);
s = Vector3.length(v1);
try expectApproxEqRel(@as(f32, 3.742), s, 0.0001);
v = Vector3.normalize(v1);
try expectApproxEqRel(@as(f32, 1.0/3.742), v.x, 0.0001);
try expectApproxEqRel(@as(f32, 2.0/3.742), v.y, 0.0001);
try expectApproxEqRel(@as(f32, 3.0/3.742), v.z, 0.0001);
} | src/vector3.zig |
const std = @import("std");
const print = std.debug.print;
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const alloc = &gpa.allocator;
const Range = struct {
min: usize,
max: usize,
};
const Rule = struct {
lower_range: Range,
upper_range: Range,
};
const INVALID_RANGE = Range{.min = 0, .max = 0};
const RuleMap = std.StringHashMap(Rule);
var rules = RuleMap.init(alloc);
fn in_range(v: usize, r: Range) bool {
return v >= r.min and v <= r.max;
}
fn rule_valid(v: usize, r: Rule) bool {
return in_range(v, r.lower_range) or in_range(v, r.upper_range);
}
pub fn main() !void {
defer _ = gpa.deinit();
defer rules.deinit();
const inputData = try std.fs.cwd().readFileAlloc(alloc, "input", std.math.maxInt(u64));
defer alloc.free(inputData);
var sections = std.mem.split(inputData, "\n\n");
var rule_section = sections.next().?;
var rules_it = std.mem.split(rule_section, "\n");
while (rules_it.next()) |rule| {
const colon = std.mem.indexOf(u8, rule, ":").?;
const or_str = std.mem.indexOfPos(u8, rule, colon, "or").?;
const rule_name = rule[0..colon];
const lower_range = rule[colon + 2 .. or_str - 1];
const upper_range = rule[or_str + 3 ..];
var lr_it = std.mem.split(lower_range, "-");
var ur_it = std.mem.split(upper_range, "-");
const lower_min = try std.fmt.parseInt(usize, lr_it.next().?, 10);
const lower_max = try std.fmt.parseInt(usize, lr_it.next().?, 10);
const upper_min = try std.fmt.parseInt(usize, ur_it.next().?, 10);
const upper_max = try std.fmt.parseInt(usize, ur_it.next().?, 10);
try rules.put(
rule_name,
Rule{
.lower_range = Range{ .min = lower_min, .max = lower_max },
.upper_range = Range{ .min = upper_min, .max = upper_max },
},
);
}
var your_ticket = sections.next().?;
var other_tickets = sections.next().?;
const p1 = try solve(your_ticket, other_tickets);
print("P1: {}\nP2: {}\n", .{p1.p1, p1.p2});
}
const Sln = struct {
p1: usize,
p2: usize,
};
fn solve(m_ticket: []const u8, tickets: []const u8) !Sln {
// there are no numbers > 999
var valid_numbers = [_]bool{false} ** 1000;
var rules_it = rules.iterator();
while (rules_it.next()) |r| {
var i = r.value.lower_range.min;
while (i <= r.value.lower_range.max) : (i += 1) {
valid_numbers[i] = true;
}
i = r.value.upper_range.min;
while (i <= r.value.upper_range.max) : (i += 1) {
valid_numbers[i] = true;
}
}
var valid_tickets = std.ArrayList([]const u8).init(alloc);
defer valid_tickets.deinit();
var err_code: usize = 0; // THIS IS RETURNED AS P1 SLN
var t_it = std.mem.split(tickets, "\n");
_ = t_it.next(); // remove "Other tickets:"
while(t_it.next()) |ticket| {
var f_it = std.mem.split(ticket, ",");
var valid: bool = true;
while(f_it.next()) |field| {
const f_value = try std.fmt.parseInt(usize, field, 10);
if (!valid_numbers[f_value]) {
err_code += f_value;
valid = false;
}
}
if (valid) {
try valid_tickets.append(ticket);
}
}
/////////////////
// PART 2 below /
/////////////////
var possible_values = std.ArrayList(std.ArrayList([]const u8)).init(alloc);
defer {
for (possible_values.items) |*item| {
item.deinit();
}
possible_values.deinit();
}
const ticket = valid_tickets.items[0];
var num_fields: usize = 0;
var f_it = std.mem.split(ticket, ",");
while (f_it.next()) |_| {
num_fields += 1;
}
var i: usize = 0;
while (i < num_fields) : (i += 1) {
var possible_fields = std.ArrayList([]const u8).init(alloc);
var it = rules.iterator();
while (it.next()) |rule| {
try possible_fields.append(rule.key);
}
try possible_values.append(possible_fields);
}
for (valid_tickets.items) |v_ticket| {
var it = std.mem.split(v_ticket, ",");
var j: usize = 0;
while (it.next()) |field| : (j += 1) {
const f_value = try std.fmt.parseInt(usize, field, 10);
var k:usize = 0;
while (k < possible_values.items[j].items.len) {
const rule = possible_values.items[j].items[k];
const rule_ranges = rules.get(rule).?;
if (!rule_valid(f_value, rule_ranges)) {
_ = possible_values.items[j].orderedRemove(k);
} else {
k += 1;
}
}
}
}
while (true) {
var single_solution: bool = true;
for (possible_values.items) |*pv, idx| {
if (pv.items.len == 1) {
const field_name = pv.items[0];
var index: usize = 0;
while (index < possible_values.items.len) : (index += 1) {
if (index == idx) { continue; }
for (possible_values.items[index].items) |itm, j_idx| {
if (std.mem.eql(u8, field_name, itm)) {
_ = possible_values.items[index].orderedRemove(j_idx);
single_solution = false;
break;
}
}
}
}
}
if (single_solution) { break; }
}
const DEP = "departure";
i = 0;
var product: usize = 1;
var m_ticket_sec_it = std.mem.split(m_ticket, "\n");
_ = m_ticket_sec_it.next().?;
var my_ticket_it = std.mem.split(m_ticket_sec_it.next().?, ",");
while (i < possible_values.items.len) : (i += 1) {
const f_value = try std.fmt.parseInt(usize, my_ticket_it.next().?, 10);
std.debug.assert(possible_values.items[i].items.len == 1);
const field_name = possible_values.items[i].items[0];
if (std.mem.eql(u8, field_name[0..std.math.min(DEP.len, field_name.len)], DEP[0..])) {
product *= f_value;
}
}
return Sln{.p1 = err_code, .p2 = product};
} | Day16/day16.zig |
pub const windows = @import("std").os.windows;
// General
pub const KEY_EVENT = 0x0001;
pub const MOUSE_EVENT = 0x0002;
pub const WINDOW_BUFFER_SIZE_EVENT = 0x0004;
pub const MENU_EVENT = 0x0008;
pub const FOCUS_EVENT = 0x0010;
pub extern fn GetConsoleOutputCP() c_uint;
pub extern fn SetConsoleOutputCP(wCodePageID: c_uint) windows.BOOL;
pub extern fn SetConsoleMode(hConsoleHandle: windows.HANDLE, dwMode: windows.DWORD) windows.BOOL;
pub extern fn GetConsoleMode(hConsoleHandle: windows.HANDLE, lpMode: *windows.DWORD) windows.BOOL;
pub extern fn WriteConsoleW(
hConsoleOutput: windows.HANDLE,
lpBuffer: [*]const u16,
nNumberOfCharsToWrite: windows.DWORD,
lpNumberOfCharsWritten: ?*windows.DWORD,
lpReserved: ?*c_void,
) windows.BOOL;
// Events
const union_unnamed_248 = extern union {
UnicodeChar: windows.WCHAR,
AsciiChar: windows.CHAR,
};
pub const KEY_EVENT_RECORD = extern struct {
bKeyDown: windows.BOOL,
wRepeatCount: windows.WORD,
wVirtualKeyCode: windows.WORD,
wVirtualScanCode: windows.WORD,
uChar: union_unnamed_248,
dwControlKeyState: windows.DWORD,
};
pub const PKEY_EVENT_RECORD = *KEY_EVENT_RECORD;
pub const MOUSE_EVENT_RECORD = extern struct {
dwMousePosition: windows.COORD,
dwButtonState: windows.DWORD,
dwControlKeyState: windows.DWORD,
dwEventFlags: windows.DWORD,
};
pub const PMOUSE_EVENT_RECORD = *MOUSE_EVENT_RECORD;
pub const WINDOW_BUFFER_SIZE_RECORD = extern struct {
dwSize: windows.COORD,
};
pub const PWINDOW_BUFFER_SIZE_RECORD = *WINDOW_BUFFER_SIZE_RECORD;
pub const MENU_EVENT_RECORD = extern struct {
dwCommandId: windows.UINT,
};
pub const PMENU_EVENT_RECORD = *MENU_EVENT_RECORD;
pub const FOCUS_EVENT_RECORD = extern struct {
bSetFocus: windows.BOOL,
};
pub const PFOCUS_EVENT_RECORD = *FOCUS_EVENT_RECORD;
const union_unnamed_249 = extern union {
KeyEvent: KEY_EVENT_RECORD,
MouseEvent: MOUSE_EVENT_RECORD,
WindowBufferSizeEvent: WINDOW_BUFFER_SIZE_RECORD,
MenuEvent: MENU_EVENT_RECORD,
FocusEvent: FOCUS_EVENT_RECORD,
};
pub const INPUT_RECORD = extern struct {
EventType: windows.WORD,
Event: union_unnamed_249,
};
pub const PINPUT_RECORD = *INPUT_RECORD;
pub extern "kernel32" fn ReadConsoleInputW(
hConsoleInput: windows.HANDLE,
lpBuffer: PINPUT_RECORD,
nLength: windows.DWORD,
lpNumberOfEventsRead: *windows.DWORD,
) windows.BOOL; | src/c/c.zig |
const std = @import("std");
pub var allocator = std.heap.c_allocator; // std.heap.page_allocator;
/// Name and type indices aggregate.
pub const NameAndType = struct {
name: u16,
t: u16,
};
/// Field type.
pub const FieldRef = struct {
class: u16,
name_and_type: u16,
};
/// Table 4.4-A. Constant pool tags (by section)
/// https://docs.oracle.com/javase/specs/jvms/se14/html/jvms-4.html
pub const ConstTag = enum(u8) {
unused = 0x0,
utf8 = 0x1,
class = 0x7,
string = 0x8,
field = 0x9,
method = 0xa,
name_and_type = 0xc,
};
/// Values in const pool
pub const Const = union(ConstTag) {
utf8: []const u8,
unused: bool,
class: u16,
string: u16,
field: FieldRef,
method: FieldRef,
name_and_type: NameAndType,
/// Destroys utf8 string.
pub fn deinit(self: Const) void {
switch (self) {
.utf8 => allocator.destroy(self.utf8.ptr),
else => {},
}
}
};
/// Attributes contain addition information about fields and classes
/// The most useful is "Code" attribute, which contains actual byte code
pub const Attribute = struct {
name: []const u8,
data: []u8,
// TODO: parse code from data
// Code_attribute {
// u2 attribute_name_index;
// u4 attribute_length;
// u2 max_stack;
// u2 max_locals;
// u4 code_length;
// u1 code[code_length];
// u2 exception_table_length;
// { u2 start_pc;
// u2 end_pc;
// u2 handler_pc;
// u2 catch_type;
// } exception_table[exception_table_length];
// u2 attributes_count;
// attribute_info attributes[attributes_count];
// }
};
/// Field type is used for both, fields and methods
pub const Field = struct {
flags: u16,
name: []const u8,
t: []const u8,
attributes: []Attribute,
};
/// Top-level class type.
pub const Class = struct {
major_version: u16,
minor_version: u16,
constant_pool: []Const,
name: []const u8,
super: []const u8,
flags: u16,
interfaces: []([]const u8),
fields: []Field,
methods: []Field,
attributes: []Attribute,
pub fn deinit(self: Class) void {
for (self.constant_pool) |c| {
c.deinit();
}
}
pub fn utf8(self: Class, index: usize) []const u8 {
const c = self.constant_pool[index];
return switch (c) {
.utf8 => c.utf8,
.class => self.utf8(c.class),
else => "",
};
}
}; | src/types.zig |
const std = @import("std");
const Application = @import("gui").Application;
const Image = @import("Image.zig");
var clipboard_image: ?Image = null;
pub fn deinit() void {
if (clipboard_image) |image| {
image.deinit();
}
}
usingnamespace switch (@import("builtin").os.tag) {
.windows => @import("ClipboardWin32.zig"),
else => struct {
pub fn hasImage() bool {
return clipboard_image != null;
}
pub fn getImage(allocator: std.mem.Allocator) !Image {
if (clipboard_image) |image| {
return try image.clone(allocator);
} else {
return error.EmptyClipboard;
}
}
pub fn setImage(allocator: std.mem.Allocator, image: Image) !void {
deinit();
clipboard_image = try image.clone(allocator);
}
},
};
fn isColorString(string: []const u8) bool {
if (string.len != 9) return false;
if (string[0] != '#') return false;
for (string[1..]) |c| {
switch (c) {
'0'...'9', 'A'...'F' => {},
else => return false,
}
}
return true;
}
pub fn hasColor(allocator: std.mem.Allocator) bool {
if (!Application.hasClipboardText()) return false;
const string = (Application.getClipboardText(allocator) catch return false).?;
defer allocator.free(string);
return isColorString(string);
}
pub fn getColor(allocator: std.mem.Allocator) ![4]u8 {
const string = (try Application.getClipboardText(allocator)).?;
defer allocator.free(string);
if (!isColorString(string)) return error.InvalidColorFormat;
return [_]u8{
try std.fmt.parseInt(u8, string[1..3], 16),
try std.fmt.parseInt(u8, string[3..5], 16),
try std.fmt.parseInt(u8, string[5..7], 16),
try std.fmt.parseInt(u8, string[7..9], 16),
};
}
pub fn setColor(allocator: std.mem.Allocator, color: [4]u8) !void {
var string: [9]u8 = undefined;
_ = try std.fmt.bufPrint(&string, "#{X:0>2}{X:0>2}{X:0>2}{X:0>2}", .{ color[0], color[1], color[2], color[3] });
try Application.setClipboardText(allocator, &string);
} | src/Clipboard.zig |
const std = @import("std");
/// Returns an anonymously namespaced interface function for serializers.
pub fn Serializer(
comptime Context: type,
comptime Ok: type,
comptime Error: type,
comptime MapSerialize: type,
comptime SequenceSerialize: type,
comptime StructSerialize: type,
comptime TupleSerialize: type,
comptime serializeBool: fn (Context, bool) Error!Ok,
comptime serializeEnum: fn (Context, anytype) Error!Ok,
comptime serializeFloat: fn (Context, anytype) Error!Ok,
comptime serializeInt: fn (Context, anytype) Error!Ok,
comptime serializeMap: fn (Context, ?usize) Error!MapSerialize,
comptime serializeNull: fn (Context) Error!Ok,
comptime serializeSequence: fn (Context, ?usize) Error!SequenceSerialize,
comptime serializeSome: fn (Context, anytype) Error!Ok,
comptime serializeString: fn (Context, anytype) Error!Ok,
comptime serializeStruct: @TypeOf(struct {
fn f(self: Context, comptime name: []const u8, length: usize) Error!StructSerialize {
_ = self;
_ = name;
_ = length;
unreachable;
}
}.f),
comptime serializeTuple: fn (Context, ?usize) Error!TupleSerialize,
comptime serializeVoid: fn (Context) Error!Ok,
) type {
return struct {
pub const @"getty.Serializer" = struct {
const Self = @This();
context: Context,
/// Successful return type.
pub const Ok = Ok;
/// The error set used upon failure.
pub const Error = Error;
/// Serializes a `bool` value.
pub fn serializeBool(self: Self, value: bool) Error!Ok {
return try serializeBool(self.context, value);
}
// Serializes an enum value.
pub fn serializeEnum(self: Self, value: anytype) Error!Ok {
switch (@typeInfo(@TypeOf(value))) {
.Enum, .EnumLiteral => {},
else => @compileError("expected enum, found `" ++ @typeName(@TypeOf(value)) ++ "`"),
}
return try serializeEnum(self.context, value);
}
/// Serializes a floating-point value.
pub fn serializeFloat(self: Self, value: anytype) Error!Ok {
comptime if (!std.meta.trait.isFloat(@TypeOf(value))) {
@compileError("expected floating-point, found `" ++ @typeName(@TypeOf(value)) ++ "`");
};
return try serializeFloat(self.context, value);
}
/// Serializes an integer value.
pub fn serializeInt(self: Self, value: anytype) Error!Ok {
if (comptime !std.meta.trait.isIntegral(@TypeOf(value))) {
@compileError("expected integer, found `" ++ @typeName(@TypeOf(value)) ++ "`");
}
return try serializeInt(self.context, value);
}
/// Starts the serialization process for a map.
pub fn serializeMap(self: Self, length: ?usize) Error!MapSerialize {
return try serializeMap(self.context, length);
}
/// Serializes a `null` value.
pub fn serializeNull(self: Self) Error!Ok {
return try serializeNull(self.context);
}
/// Starts the serialization process for a sequence.
pub fn serializeSequence(self: Self, length: ?usize) Error!SequenceSerialize {
return try serializeSequence(self.context, length);
}
/// Serializes the payload of an optional.
pub fn serializeSome(self: Self, value: anytype) Error!Ok {
return try serializeSome(self.context, value);
}
/// Serializes a string value.
pub fn serializeString(self: Self, value: anytype) Error!Ok {
if (comptime !std.meta.trait.isZigString(@TypeOf(value))) {
@compileError("expected string, found `" ++ @typeName(@TypeOf(value)) ++ "`");
}
return try serializeString(self.context, value);
}
/// Starts the serialization process for a struct.
pub fn serializeStruct(self: Self, comptime name: []const u8, length: usize) Error!StructSerialize {
return try serializeStruct(self.context, name, length);
}
/// Starts the serialization process for a tuple.
pub fn serializeTuple(self: Self, length: ?usize) Error!TupleSerialize {
return try serializeTuple(self.context, length);
}
/// Serializes a `void` value.
pub fn serializeVoid(self: Self) Error!Ok {
return try serializeVoid(self.context);
}
};
pub fn serializer(self: Context) @"getty.Serializer" {
return .{ .context = self };
}
};
} | src/ser/interface/serializer.zig |
const std = @import("std");
const decoder = @import("decoder.zig");
const opfunc = @import("opfunc.zig");
pub const debug = false;
pub const CPUError = error{
OutOfBoundsAccess,
IllegalOpcode,
};
pub const CPUConfig = struct {
// Abstract pointer to data that the memRead/memWrite functions may use
memCookie: ?*c_void = null,
// Reads buf.length bytes of memory
memRead: ?fn (config: *CPUConfig, addr: CPU.XLEN, buf: []u8) anyerror!void = null,
// Writes buf.length bytes of memory
memWrite: ?fn (config: *CPUConfig, addr: CPU.XLEN, buf: []u8) anyerror!void = null,
};
fn simpleMemRead(config: *CPUConfig, addr: CPU.XLEN, buf: []u8) !void {
const slice = @ptrCast(*[]u8, @alignCast(@alignOf(*[]u8), config.memCookie.?)).*;
const off = @intCast(usize, addr);
const size = buf.len;
if (off + size > slice.len) return CPUError.OutOfBoundsAccess;
std.mem.copy(u8, buf, slice[off .. off + size]);
}
fn simpleMemWrite(config: *CPUConfig, addr: CPU.XLEN, buf: []u8) !void {
const slice = @ptrCast(*[]u8, @alignCast(@alignOf(*[]u8), config.memCookie.?)).*;
const off = @intCast(usize, addr);
const size = buf.len;
if (off + size > slice.len) return CPUError.OutOfBoundsAccess;
std.mem.copy(u8, slice[off .. off + size], buf);
}
/// Enable simple memory I/O functions backed by a []u8
pub fn useSimpleMemIO(config: *CPUConfig, memory: *[]u8) void {
config.memCookie = @ptrCast(*c_void, memory);
config.memRead = simpleMemRead;
config.memWrite = simpleMemWrite;
}
// CPU instruction cache
const CPUCache = struct {
// Opcode function pointers and instruction data
funcs: ?[]opfunc.OpFunc = null,
inst: ?[]decoder.Instruction = null,
// Range of compiled instructions.
base_pc: CPU.XLEN = 0,
max_pc: CPU.XLEN = 0,
// Maximum number of instructions to execute and
// number of instructions executed (per call to execute())
max_exec: usize = 0,
exec_counter: usize = 0,
};
pub const CPU = struct {
pub const XLEN = u64;
pub const SXLEN = i64;
pub const util = struct {
// Before anyone complains about the name, this is the standard abbreviation.
/// Sign extension.
pub inline fn sext(in: anytype) XLEN {
return @bitCast(XLEN, @intCast(SXLEN, @bitCast(std.meta.Int(.signed, @bitSizeOf(@TypeOf(in))), in)));
}
};
allocator: *std.mem.Allocator,
config: CPUConfig,
registers: [32]XLEN = undefined,
pc: XLEN,
cache: CPUCache,
/// Create and configure a CPU object.
pub fn init(allocator: *std.mem.Allocator, config: CPUConfig) CPU {
return .{
.allocator = allocator,
.config = config,
.registers = std.mem.zeroes([32]XLEN),
.pc = 0,
.cache = .{},
};
}
/// Dump the CPU state.
pub fn dump(self: *CPU) void {
std.debug.print("PC={}\n", .{self.pc});
var instr: u32 = self.getMem(self.pc, u32, .fetch_instruction) catch 0;
std.debug.print("> {x:08}\n", .{instr});
for (self.registers[0..]) |val, i| {
std.debug.print("reg: x{} = {}\n", .{ i, val });
}
}
/// Set the value of a register.
pub inline fn setReg(self: *CPU, reg: u5, val: XLEN) void {
if (reg != 0) self.registers[@intCast(usize, reg)] = val;
}
/// Get the value of a register.
/// Per specification, x0 is always 0.
pub inline fn getReg(self: *CPU, reg: u5) XLEN {
if (reg == 0) return 0;
return self.registers[@intCast(usize, reg)];
}
/// Same as getReg(), but returns a signed integer
pub inline fn getRegSigned(self: *CPU, reg: u5) SXLEN {
return @bitCast(SXLEN, self.getReg(reg));
}
/// Store *val*, a *size* integer, in the CPU's configured memory.
/// *size* must be either i8/u8, i16/u16, i32/u32, or i64/u64.
pub inline fn setMem(self: *CPU, addr: XLEN, val: anytype) !void {
// TODO: handle endians
var t: @TypeOf(val) = val;
var b = @ptrCast(*[@sizeOf(@TypeOf(val))]u8, &t);
try self.config.memWrite.?(&self.config, addr, b[0..]);
}
/// Retrieve a *size* integer from the CPU's configured memory.
/// *size* must be either i8/u8, i16/u16, i32/u32, or i64/u64.
pub inline fn getMem(self: *CPU, addr: u64, comptime size: type, flags: anytype) !size {
var b: [@sizeOf(size)]u8 = undefined;
try self.config.memRead.?(&self.config, addr, b[0..]);
return @bitCast(size, switch (size) {
u8, i8 => b[0],
u16, i16 => b,
u32, i32 => b,
u64, i64 => b,
else => unreachable,
});
}
/// Execute up to *max* CPU instructions.
pub fn execute(self: *CPU, max: usize) !usize {
self.cache.funcs = try self.allocator.alloc(opfunc.OpFunc, max);
defer self.allocator.free(self.cache.funcs.?);
self.cache.inst = try self.allocator.alloc(decoder.Instruction, max);
defer self.allocator.free(self.cache.inst.?);
self.cache.base_pc = self.pc;
// Instruction decoding
// We try to decode as many instructions as possible, up to *max*.
// If an instruction can't be decoded, then we stop decoding.
// *i* contains the number of instructions actually decoded.
var i: usize = 0;
var failed: anyerror = undefined;
while (i < max) {
var rawInst = self.getMem(self.pc +% @intCast(XLEN, i) * 4, u32, .fetch_instruction) catch |err| {
failed = err;
break;
};
self.cache.inst.?[i] = decoder.Instruction.decode32(rawInst) catch |err| {
failed = err;
break;
};
//if (debug) std.debug.print("execute: decoded and 'compiled' {}\n", .{self.cache.inst.?[i]});
self.cache.funcs.?[i] = opfunc.fromInstruction(self.cache.inst.?[i]) catch |err| {
failed = err;
break;
};
i += 1;
}
// Couldn't decode any instructions? That's an error
if (i == 0) return failed;
self.cache.max_pc = self.cache.base_pc + @intCast(u64, i) * 4;
self.cache.max_exec = max;
self.cache.exec_counter = 0;
try self.cache.funcs.?[0](self, self.cache.inst.?[0..i], 0);
return self.cache.exec_counter;
}
};
// These tests ensure that sample programs provided produce the correct output
const expect = std.testing.expect;
test "asm.simple" {
var memory = std.mem.zeroes([4096]u8);
var memSlice: []u8 = memory[0..];
std.mem.copy(u8, memSlice, @embedFile("test/asm/simple.bin"));
// Configure CPU to use memory provided by memSlice
var conf: CPUConfig = undefined;
useSimpleMemIO(&conf, &memSlice);
var cpu = CPU.init(std.testing.allocator, conf);
// Execute 32 instructions
_ = try cpu.execute(32);
try expect(cpu.getReg(10) == 1);
}
test "c.test1" {
var memory = std.mem.zeroes([4096]u8);
var memSlice: []u8 = memory[0..];
std.mem.copy(u8, memSlice, @embedFile("test/c/test1.bin"));
var conf: CPUConfig = undefined;
useSimpleMemIO(&conf, &memSlice);
var cpu = CPU.init(std.testing.allocator, conf);
// Set up stack pointer
cpu.setReg(2, 4096);
_ = try cpu.execute(32);
try expect(cpu.getReg(10) == 13);
}
test "c.test2" {
var memory = std.mem.zeroes([4096]u8);
var memSlice: []u8 = memory[0..];
std.mem.copy(u8, memSlice, @embedFile("test/c/test2.bin"));
var conf: CPUConfig = undefined;
useSimpleMemIO(&conf, &memSlice);
var cpu = CPU.init(std.testing.allocator, conf);
cpu.setReg(2, 4096);
_ = try cpu.execute(64);
try expect(cpu.getReg(10) == 54);
} | cpu.zig |
const __fixtfti = @import("fixtfti.zig").__fixtfti;
const std = @import("std");
const math = std.math;
const assert = std.debug.assert;
const warn = std.debug.warn;
fn test__fixtfti(a: f128, expected: i128) void {
const x = __fixtfti(a);
//warn("a={}:{x} x={}:{x} expected={}:{x}:u128({x})\n", a, @bitCast(u128, a), x, x, expected, expected, @bitCast(u128, expected));
assert(x == expected);
}
test "fixtfti" {
//warn("\n");
test__fixtfti(-math.f128_max, math.minInt(i128));
test__fixtfti(-0x1.FFFFFFFFFFFFFp+1023, math.minInt(i128));
test__fixtfti(-0x1.FFFFFFFFFFFFFp+1023, -0x80000000000000000000000000000000);
test__fixtfti(-0x1.0000000000000p+127, -0x80000000000000000000000000000000);
test__fixtfti(-0x1.FFFFFFFFFFFFFp+126, -0x7FFFFFFFFFFFFC000000000000000000);
test__fixtfti(-0x1.FFFFFFFFFFFFEp+126, -0x7FFFFFFFFFFFF8000000000000000000);
test__fixtfti(-0x1.0000000000001p+63, -0x8000000000000800);
test__fixtfti(-0x1.0000000000000p+63, -0x8000000000000000);
test__fixtfti(-0x1.FFFFFFFFFFFFFp+62, -0x7FFFFFFFFFFFFC00);
test__fixtfti(-0x1.FFFFFFFFFFFFEp+62, -0x7FFFFFFFFFFFF800);
test__fixtfti(-0x1.FFFFFEp+62, -0x7fffff8000000000);
test__fixtfti(-0x1.FFFFFCp+62, -0x7fffff0000000000);
test__fixtfti(-2.01, -2);
test__fixtfti(-2.0, -2);
test__fixtfti(-1.99, -1);
test__fixtfti(-1.0, -1);
test__fixtfti(-0.99, 0);
test__fixtfti(-0.5, 0);
test__fixtfti(-math.f128_min, 0);
test__fixtfti(0.0, 0);
test__fixtfti(math.f128_min, 0);
test__fixtfti(0.5, 0);
test__fixtfti(0.99, 0);
test__fixtfti(1.0, 1);
test__fixtfti(1.5, 1);
test__fixtfti(1.99, 1);
test__fixtfti(2.0, 2);
test__fixtfti(2.01, 2);
test__fixtfti(0x1.FFFFFCp+62, 0x7FFFFF0000000000);
test__fixtfti(0x1.FFFFFEp+62, 0x7FFFFF8000000000);
test__fixtfti(0x1.FFFFFFFFFFFFEp+62, 0x7FFFFFFFFFFFF800);
test__fixtfti(0x1.FFFFFFFFFFFFFp+62, 0x7FFFFFFFFFFFFC00);
test__fixtfti(0x1.0000000000000p+63, 0x8000000000000000);
test__fixtfti(0x1.0000000000001p+63, 0x8000000000000800);
test__fixtfti(0x1.FFFFFFFFFFFFEp+126, 0x7FFFFFFFFFFFF8000000000000000000);
test__fixtfti(0x1.FFFFFFFFFFFFFp+126, 0x7FFFFFFFFFFFFC000000000000000000);
test__fixtfti(0x1.0000000000000p+127, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
test__fixtfti(0x1.FFFFFFFFFFFFFp+1023, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
test__fixtfti(0x1.FFFFFFFFFFFFFp+1023, math.maxInt(i128));
test__fixtfti(math.f128_max, math.maxInt(i128));
} | std/special/compiler_rt/fixtfti_test.zig |
const std = @import("std");
const Value = @import("value.zig").Value;
const Type = @import("type.zig").Type;
const Module = @import("Module.zig");
const assert = std.debug.assert;
const Air = @This();
instructions: std.MultiArrayList(Inst).Slice,
/// The meaning of this data is determined by `Inst.Tag` value.
/// The first few indexes are reserved. See `ExtraIndex` for the values.
extra: []const u32,
values: []const Value,
pub const ExtraIndex = enum(u32) {
/// Payload index of the main `Block` in the `extra` array.
main_block,
_,
};
pub const Inst = struct {
tag: Tag,
data: Data,
pub const Tag = enum(u8) {
/// The first N instructions in the main block must be one arg instruction per
/// function parameter. This makes function parameters participate in
/// liveness analysis without any special handling.
/// Uses the `ty_str` field.
/// The string is the parameter name.
arg,
/// Float or integer addition. For integers, wrapping is undefined behavior.
/// Both operands are guaranteed to be the same type, and the result type
/// is the same as both operands.
/// Uses the `bin_op` field.
add,
/// Integer addition. Wrapping is defined to be twos complement wrapping.
/// Both operands are guaranteed to be the same type, and the result type
/// is the same as both operands.
/// Uses the `bin_op` field.
addwrap,
/// Float or integer subtraction. For integers, wrapping is undefined behavior.
/// Both operands are guaranteed to be the same type, and the result type
/// is the same as both operands.
/// Uses the `bin_op` field.
sub,
/// Integer subtraction. Wrapping is defined to be twos complement wrapping.
/// Both operands are guaranteed to be the same type, and the result type
/// is the same as both operands.
/// Uses the `bin_op` field.
subwrap,
/// Float or integer multiplication. For integers, wrapping is undefined behavior.
/// Both operands are guaranteed to be the same type, and the result type
/// is the same as both operands.
/// Uses the `bin_op` field.
mul,
/// Integer multiplication. Wrapping is defined to be twos complement wrapping.
/// Both operands are guaranteed to be the same type, and the result type
/// is the same as both operands.
/// Uses the `bin_op` field.
mulwrap,
/// Integer or float division. For integers, wrapping is undefined behavior.
/// Both operands are guaranteed to be the same type, and the result type
/// is the same as both operands.
/// Uses the `bin_op` field.
div,
/// Allocates stack local memory.
/// Uses the `ty` field.
alloc,
/// Inline assembly. Uses the `ty_pl` field. Payload is `Asm`.
assembly,
/// Bitwise AND. `&`.
/// Result type is the same as both operands.
/// Uses the `bin_op` field.
bit_and,
/// Bitwise OR. `|`.
/// Result type is the same as both operands.
/// Uses the `bin_op` field.
bit_or,
/// Bitwise XOR. `^`
/// Uses the `bin_op` field.
xor,
/// Boolean or binary NOT.
/// Uses the `ty_op` field.
not,
/// Reinterpret the memory representation of a value as a different type.
/// Uses the `ty_op` field.
bitcast,
/// Uses the `ty_pl` field with payload `Block`.
block,
/// A labeled block of code that loops forever. At the end of the body it is implied
/// to repeat; no explicit "repeat" instruction terminates loop bodies.
/// Result type is always noreturn; no instructions in a block follow this one.
/// Uses the `ty_pl` field. Payload is `Block`.
loop,
/// Return from a block with a result.
/// Result type is always noreturn; no instructions in a block follow this one.
/// Uses the `br` field.
br,
/// Lowers to a hardware trap instruction, or the next best thing.
/// Result type is always void.
breakpoint,
/// Function call.
/// Result type is the return type of the function being called.
/// Uses the `pl_op` field with the `Call` payload. operand is the callee.
call,
/// `<`. Result type is always bool.
/// Uses the `bin_op` field.
cmp_lt,
/// `<=`. Result type is always bool.
/// Uses the `bin_op` field.
cmp_lte,
/// `==`. Result type is always bool.
/// Uses the `bin_op` field.
cmp_eq,
/// `>=`. Result type is always bool.
/// Uses the `bin_op` field.
cmp_gte,
/// `>`. Result type is always bool.
/// Uses the `bin_op` field.
cmp_gt,
/// `!=`. Result type is always bool.
/// Uses the `bin_op` field.
cmp_neq,
/// Conditional branch.
/// Result type is always noreturn; no instructions in a block follow this one.
/// Uses the `pl_op` field. Operand is the condition. Payload is `CondBr`.
cond_br,
/// Switch branch.
/// Result type is always noreturn; no instructions in a block follow this one.
/// Uses the `pl_op` field. Operand is the condition. Payload is `SwitchBr`.
switch_br,
/// A comptime-known value. Uses the `ty_pl` field, payload is index of
/// `values` array.
constant,
/// A comptime-known type. Uses the `ty` field.
const_ty,
/// Notes the beginning of a source code statement and marks the line and column.
/// Result type is always void.
/// Uses the `dbg_stmt` field.
dbg_stmt,
/// ?T => bool
/// Result type is always bool.
/// Uses the `un_op` field.
is_null,
/// ?T => bool (inverted logic)
/// Result type is always bool.
/// Uses the `un_op` field.
is_non_null,
/// *?T => bool
/// Result type is always bool.
/// Uses the `un_op` field.
is_null_ptr,
/// *?T => bool (inverted logic)
/// Result type is always bool.
/// Uses the `un_op` field.
is_non_null_ptr,
/// E!T => bool
/// Result type is always bool.
/// Uses the `un_op` field.
is_err,
/// E!T => bool (inverted logic)
/// Result type is always bool.
/// Uses the `un_op` field.
is_non_err,
/// *E!T => bool
/// Result type is always bool.
/// Uses the `un_op` field.
is_err_ptr,
/// *E!T => bool (inverted logic)
/// Result type is always bool.
/// Uses the `un_op` field.
is_non_err_ptr,
/// Result type is always bool.
/// Uses the `bin_op` field.
bool_and,
/// Result type is always bool.
/// Uses the `bin_op` field.
bool_or,
/// Read a value from a pointer.
/// Uses the `ty_op` field.
load,
/// Converts a pointer to its address. Result type is always `usize`.
/// Uses the `un_op` field.
ptrtoint,
/// Given a boolean, returns 0 or 1.
/// Result type is always `u1`.
/// Uses the `un_op` field.
bool_to_int,
/// Return a value from a function.
/// Result type is always noreturn; no instructions in a block follow this one.
/// Uses the `un_op` field.
ret,
/// Write a value to a pointer. LHS is pointer, RHS is value.
/// Result type is always void.
/// Uses the `bin_op` field.
store,
/// Indicates the program counter will never get to this instruction.
/// Result type is always noreturn; no instructions in a block follow this one.
unreach,
/// Convert from one float type to another.
/// Uses the `ty_op` field.
floatcast,
/// Returns an integer with a different type than the operand. The new type may have
/// fewer, the same, or more bits than the operand type. However, the instruction
/// guarantees that the same integer value fits in both types.
/// See `trunc` for integer truncation.
/// Uses the `ty_op` field.
intcast,
/// Truncate higher bits from an integer, resulting in an integer with the same
/// sign but an equal or smaller number of bits.
/// Uses the `ty_op` field.
trunc,
/// ?T => T. If the value is null, undefined behavior.
/// Uses the `ty_op` field.
optional_payload,
/// *?T => *T. If the value is null, undefined behavior.
/// Uses the `ty_op` field.
optional_payload_ptr,
/// Given a payload value, wraps it in an optional type.
/// Uses the `ty_op` field.
wrap_optional,
/// E!T -> T. If the value is an error, undefined behavior.
/// Uses the `ty_op` field.
unwrap_errunion_payload,
/// E!T -> E. If the value is not an error, undefined behavior.
/// Uses the `ty_op` field.
unwrap_errunion_err,
/// *(E!T) -> *T. If the value is an error, undefined behavior.
/// Uses the `ty_op` field.
unwrap_errunion_payload_ptr,
/// *(E!T) -> E. If the value is not an error, undefined behavior.
/// Uses the `ty_op` field.
unwrap_errunion_err_ptr,
/// wrap from T to E!T
/// Uses the `ty_op` field.
wrap_errunion_payload,
/// wrap from E to E!T
/// Uses the `ty_op` field.
wrap_errunion_err,
/// Given a pointer to a struct and a field index, returns a pointer to the field.
/// Uses the `ty_pl` field, payload is `StructField`.
struct_field_ptr,
/// Given a byval struct and a field index, returns the field byval.
/// Uses the `ty_pl` field, payload is `StructField`.
struct_field_val,
/// Given a slice value, return the length.
/// Result type is always usize.
/// Uses the `ty_op` field.
slice_len,
/// Given a slice value, return the pointer.
/// Uses the `ty_op` field.
slice_ptr,
/// Given a slice value, and element index, return the element value at that index.
/// Result type is the element type of the slice operand.
/// Uses the `bin_op` field.
slice_elem_val,
/// Given a pointer to a slice, and element index, return the element value at that index.
/// Result type is the element type of the slice operand (2 element type operations).
/// Uses the `bin_op` field.
ptr_slice_elem_val,
pub fn fromCmpOp(op: std.math.CompareOperator) Tag {
return switch (op) {
.lt => .cmp_lt,
.lte => .cmp_lte,
.eq => .cmp_eq,
.gte => .cmp_gte,
.gt => .cmp_gt,
.neq => .cmp_neq,
};
}
pub fn toCmpOp(tag: Tag) ?std.math.CompareOperator {
return switch (tag) {
.cmp_lt => .lt,
.cmp_lte => .lte,
.cmp_eq => .eq,
.cmp_gte => .gte,
.cmp_gt => .gt,
.cmp_neq => .neq,
else => null,
};
}
};
/// The position of an AIR instruction within the `Air` instructions array.
pub const Index = u32;
pub const Ref = @import("Zir.zig").Inst.Ref;
/// All instructions have an 8-byte payload, which is contained within
/// this union. `Tag` determines which union field is active, as well as
/// how to interpret the data within.
pub const Data = union {
no_op: void,
un_op: Ref,
bin_op: struct {
lhs: Ref,
rhs: Ref,
},
ty: Type,
ty_op: struct {
ty: Ref,
operand: Ref,
},
ty_pl: struct {
ty: Ref,
// Index into a different array.
payload: u32,
},
ty_str: struct {
ty: Ref,
// ZIR string table index.
str: u32,
},
br: struct {
block_inst: Index,
operand: Ref,
},
pl_op: struct {
operand: Ref,
payload: u32,
},
dbg_stmt: struct {
line: u32,
column: u32,
},
// Make sure we don't accidentally add a field to make this union
// bigger than expected. Note that in Debug builds, Zig is allowed
// to insert a secret field for safety checks.
comptime {
if (std.builtin.mode != .Debug) {
assert(@sizeOf(Data) == 8);
}
}
};
};
/// Trailing is a list of instruction indexes for every `body_len`.
pub const Block = struct {
body_len: u32,
};
/// Trailing is a list of `Inst.Ref` for every `args_len`.
pub const Call = struct {
args_len: u32,
};
/// This data is stored inside extra, with two sets of trailing `Inst.Ref`:
/// * 0. the then body, according to `then_body_len`.
/// * 1. the else body, according to `else_body_len`.
pub const CondBr = struct {
then_body_len: u32,
else_body_len: u32,
};
/// Trailing:
/// * 0. `Case` for each `cases_len`
/// * 1. the else body, according to `else_body_len`.
pub const SwitchBr = struct {
cases_len: u32,
else_body_len: u32,
/// Trailing:
/// * item: Inst.Ref // for each `items_len`.
/// * instruction index for each `body_len`.
pub const Case = struct {
items_len: u32,
body_len: u32,
};
};
pub const StructField = struct {
/// Whether this is a pointer or byval is determined by the AIR tag.
struct_operand: Inst.Ref,
field_index: u32,
};
/// Trailing:
/// 0. `Inst.Ref` for every outputs_len
/// 1. `Inst.Ref` for every inputs_len
pub const Asm = struct {
/// Index to the corresponding ZIR instruction.
/// `asm_source`, `outputs_len`, `inputs_len`, `clobbers_len`, `is_volatile`, and
/// clobbers are found via here.
zir_index: u32,
};
pub fn getMainBody(air: Air) []const Air.Inst.Index {
const body_index = air.extra[@enumToInt(ExtraIndex.main_block)];
const extra = air.extraData(Block, body_index);
return air.extra[extra.end..][0..extra.data.body_len];
}
pub fn typeOf(air: Air, inst: Air.Inst.Ref) Type {
const ref_int = @enumToInt(inst);
if (ref_int < Air.Inst.Ref.typed_value_map.len) {
return Air.Inst.Ref.typed_value_map[ref_int].ty;
}
return air.typeOfIndex(@intCast(Air.Inst.Index, ref_int - Air.Inst.Ref.typed_value_map.len));
}
pub fn typeOfIndex(air: Air, inst: Air.Inst.Index) Type {
const datas = air.instructions.items(.data);
switch (air.instructions.items(.tag)[inst]) {
.arg => return air.getRefType(datas[inst].ty_str.ty),
.add,
.addwrap,
.sub,
.subwrap,
.mul,
.mulwrap,
.div,
.bit_and,
.bit_or,
.xor,
=> return air.typeOf(datas[inst].bin_op.lhs),
.cmp_lt,
.cmp_lte,
.cmp_eq,
.cmp_gte,
.cmp_gt,
.cmp_neq,
.is_null,
.is_non_null,
.is_null_ptr,
.is_non_null_ptr,
.is_err,
.is_non_err,
.is_err_ptr,
.is_non_err_ptr,
.bool_and,
.bool_or,
=> return Type.initTag(.bool),
.const_ty => return Type.initTag(.type),
.alloc => return datas[inst].ty,
.assembly,
.block,
.constant,
.struct_field_ptr,
.struct_field_val,
=> return air.getRefType(datas[inst].ty_pl.ty),
.not,
.bitcast,
.load,
.floatcast,
.intcast,
.trunc,
.optional_payload,
.optional_payload_ptr,
.wrap_optional,
.unwrap_errunion_payload,
.unwrap_errunion_err,
.unwrap_errunion_payload_ptr,
.unwrap_errunion_err_ptr,
.wrap_errunion_payload,
.wrap_errunion_err,
.slice_ptr,
=> return air.getRefType(datas[inst].ty_op.ty),
.loop,
.br,
.cond_br,
.switch_br,
.ret,
.unreach,
=> return Type.initTag(.noreturn),
.breakpoint,
.dbg_stmt,
.store,
=> return Type.initTag(.void),
.ptrtoint,
.slice_len,
=> return Type.initTag(.usize),
.bool_to_int => return Type.initTag(.u1),
.call => {
const callee_ty = air.typeOf(datas[inst].pl_op.operand);
return callee_ty.fnReturnType();
},
.slice_elem_val => {
const slice_ty = air.typeOf(datas[inst].bin_op.lhs);
return slice_ty.elemType();
},
.ptr_slice_elem_val => {
const ptr_slice_ty = air.typeOf(datas[inst].bin_op.lhs);
const slice_ty = ptr_slice_ty.elemType();
return slice_ty.elemType();
},
}
}
pub fn getRefType(air: Air, ref: Air.Inst.Ref) Type {
const ref_int = @enumToInt(ref);
if (ref_int < Air.Inst.Ref.typed_value_map.len) {
var buffer: Value.ToTypeBuffer = undefined;
return Air.Inst.Ref.typed_value_map[ref_int].val.toType(&buffer);
}
const inst_index = ref_int - Air.Inst.Ref.typed_value_map.len;
const air_tags = air.instructions.items(.tag);
const air_datas = air.instructions.items(.data);
assert(air_tags[inst_index] == .const_ty);
return air_datas[inst_index].ty;
}
/// Returns the requested data, as well as the new index which is at the start of the
/// trailers for the object.
pub fn extraData(air: Air, comptime T: type, index: usize) struct { data: T, end: usize } {
const fields = std.meta.fields(T);
var i: usize = index;
var result: T = undefined;
inline for (fields) |field| {
@field(result, field.name) = switch (field.field_type) {
u32 => air.extra[i],
Inst.Ref => @intToEnum(Inst.Ref, air.extra[i]),
i32 => @bitCast(i32, air.extra[i]),
else => @compileError("bad field type"),
};
i += 1;
}
return .{
.data = result,
.end = i,
};
}
pub fn deinit(air: *Air, gpa: *std.mem.Allocator) void {
air.instructions.deinit(gpa);
gpa.free(air.extra);
gpa.free(air.values);
air.* = undefined;
}
const ref_start_index: u32 = Air.Inst.Ref.typed_value_map.len;
pub fn indexToRef(inst: Air.Inst.Index) Air.Inst.Ref {
return @intToEnum(Air.Inst.Ref, ref_start_index + inst);
}
pub fn refToIndex(inst: Air.Inst.Ref) ?Air.Inst.Index {
const ref_int = @enumToInt(inst);
if (ref_int >= ref_start_index) {
return ref_int - ref_start_index;
} else {
return null;
}
}
/// Returns `null` if runtime-known.
pub fn value(air: Air, inst: Air.Inst.Ref) ?Value {
const ref_int = @enumToInt(inst);
if (ref_int < Air.Inst.Ref.typed_value_map.len) {
return Air.Inst.Ref.typed_value_map[ref_int].val;
}
const inst_index = @intCast(Air.Inst.Index, ref_int - Air.Inst.Ref.typed_value_map.len);
const air_datas = air.instructions.items(.data);
switch (air.instructions.items(.tag)[inst_index]) {
.constant => return air.values[air_datas[inst_index].ty_pl.payload],
.const_ty => unreachable,
else => return air.typeOfIndex(inst_index).onePossibleValue(),
}
} | src/Air.zig |
const std = @import("std");
const leb = std.leb;
const macho = std.macho;
const mem = std.mem;
const assert = std.debug.assert;
const Allocator = mem.Allocator;
/// Table of binding info entries used to tell the dyld which
/// symbols to bind at loading time.
pub const BindingInfoTable = struct {
/// Id of the dynamic library where the specified entries can be found.
dylib_ordinal: i64 = 0,
/// Binding type; defaults to pointer type.
binding_type: u8 = macho.BIND_TYPE_POINTER,
symbols: std.ArrayListUnmanaged(Symbol) = .{},
pub const Symbol = struct {
/// Symbol name.
name: ?[]u8 = null,
/// Id of the segment where to bind this symbol to.
segment: u8,
/// Offset of this symbol wrt to the segment id encoded in `segment`.
offset: i64,
/// Addend value (if any).
addend: ?i64 = null,
};
pub fn deinit(self: *BindingInfoTable, allocator: *Allocator) void {
for (self.symbols.items) |*symbol| {
if (symbol.name) |name| {
allocator.free(name);
}
}
self.symbols.deinit(allocator);
}
/// Parse the binding info table from byte stream.
pub fn read(self: *BindingInfoTable, reader: anytype, allocator: *Allocator) !void {
var symbol: Symbol = .{
.segment = 0,
.offset = 0,
};
var dylib_ordinal_set = false;
var done = false;
while (true) {
const inst = reader.readByte() catch |err| switch (err) {
error.EndOfStream => break,
else => return err,
};
const imm: u8 = inst & macho.BIND_IMMEDIATE_MASK;
const opcode: u8 = inst & macho.BIND_OPCODE_MASK;
switch (opcode) {
macho.BIND_OPCODE_DO_BIND => {
try self.symbols.append(allocator, symbol);
symbol = .{
.segment = 0,
.offset = 0,
};
},
macho.BIND_OPCODE_DONE => {
done = true;
break;
},
macho.BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM => {
var name = std.ArrayList(u8).init(allocator);
var next = try reader.readByte();
while (next != @as(u8, 0)) {
try name.append(next);
next = try reader.readByte();
}
symbol.name = name.toOwnedSlice();
},
macho.BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB => {
symbol.segment = imm;
symbol.offset = try leb.readILEB128(i64, reader);
},
macho.BIND_OPCODE_SET_DYLIB_SPECIAL_IMM, macho.BIND_OPCODE_SET_DYLIB_ORDINAL_IMM => {
assert(!dylib_ordinal_set);
self.dylib_ordinal = imm;
},
macho.BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB => {
assert(!dylib_ordinal_set);
self.dylib_ordinal = try leb.readILEB128(i64, reader);
},
macho.BIND_OPCODE_SET_TYPE_IMM => {
self.binding_type = imm;
},
macho.BIND_OPCODE_SET_ADDEND_SLEB => {
symbol.addend = try leb.readILEB128(i64, reader);
},
else => {
std.log.warn("unhandled BIND_OPCODE_: 0x{x}", .{opcode});
},
}
}
assert(done);
}
/// Write the binding info table to byte stream.
pub fn write(self: BindingInfoTable, writer: anytype) !void {
if (self.dylib_ordinal > 15) {
try writer.writeByte(macho.BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB);
try leb.writeULEB128(writer, @bitCast(u64, self.dylib_ordinal));
} else if (self.dylib_ordinal > 0) {
try writer.writeByte(macho.BIND_OPCODE_SET_DYLIB_ORDINAL_IMM | @truncate(u4, @bitCast(u64, self.dylib_ordinal)));
} else {
try writer.writeByte(macho.BIND_OPCODE_SET_DYLIB_SPECIAL_IMM | @truncate(u4, @bitCast(u64, self.dylib_ordinal)));
}
try writer.writeByte(macho.BIND_OPCODE_SET_TYPE_IMM | @truncate(u4, self.binding_type));
for (self.symbols.items) |symbol| {
if (symbol.name) |name| {
try writer.writeByte(macho.BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM); // TODO Sometimes we might want to add flags.
try writer.writeAll(name);
try writer.writeByte(0);
}
try writer.writeByte(macho.BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB | @truncate(u4, symbol.segment));
try leb.writeILEB128(writer, symbol.offset);
if (symbol.addend) |addend| {
try writer.writeByte(macho.BIND_OPCODE_SET_ADDEND_SLEB);
try leb.writeILEB128(writer, addend);
}
try writer.writeByte(macho.BIND_OPCODE_DO_BIND);
}
try writer.writeByte(macho.BIND_OPCODE_DONE);
}
/// Calculate size in bytes of this binding info table.
pub fn calcSize(self: *BindingInfoTable) !usize {
var stream = std.io.countingWriter(std.io.null_writer);
var writer = stream.writer();
var size: usize = 1;
if (self.dylib_ordinal > 15) {
try leb.writeULEB128(writer, @bitCast(u64, self.dylib_ordinal));
}
size += 1;
for (self.symbols.items) |symbol| {
if (symbol.name) |name| {
size += 1;
size += name.len;
size += 1;
}
size += 1;
try leb.writeILEB128(writer, symbol.offset);
if (symbol.addend) |addend| {
size += 1;
try leb.writeILEB128(writer, addend);
}
size += 1;
}
size += 1 + stream.bytes_written;
return size;
}
};
/// Table of lazy binding info entries used to tell the dyld which
/// symbols to lazily bind at first load of a dylib.
pub const LazyBindingInfoTable = struct {
symbols: std.ArrayListUnmanaged(Symbol) = .{},
pub const Symbol = struct {
/// Symbol name.
name: ?[]u8 = null,
/// Offset of this symbol wrt to the segment id encoded in `segment`.
offset: i64,
/// Id of the dylib where this symbol is expected to reside.
/// Positive ordinals point at dylibs imported with LC_LOAD_DYLIB,
/// 0 means this binary, -1 the main executable, and -2 flat lookup.
dylib_ordinal: i64,
/// Id of the segment where to bind this symbol to.
segment: u8,
/// Addend value (if any).
addend: ?i64 = null,
};
pub fn deinit(self: *LazyBindingInfoTable, allocator: *Allocator) void {
for (self.symbols.items) |*symbol| {
if (symbol.name) |name| {
allocator.free(name);
}
}
self.symbols.deinit(allocator);
}
/// Parse the binding info table from byte stream.
pub fn read(self: *LazyBindingInfoTable, reader: anytype, allocator: *Allocator) !void {
var symbol: Symbol = .{
.offset = 0,
.segment = 0,
.dylib_ordinal = 0,
};
var done = false;
while (true) {
const inst = reader.readByte() catch |err| switch (err) {
error.EndOfStream => break,
else => return err,
};
const imm: u8 = inst & macho.BIND_IMMEDIATE_MASK;
const opcode: u8 = inst & macho.BIND_OPCODE_MASK;
switch (opcode) {
macho.BIND_OPCODE_DO_BIND => {
try self.symbols.append(allocator, symbol);
},
macho.BIND_OPCODE_DONE => {
done = true;
symbol = .{
.offset = 0,
.segment = 0,
.dylib_ordinal = 0,
};
},
macho.BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM => {
var name = std.ArrayList(u8).init(allocator);
var next = try reader.readByte();
while (next != @as(u8, 0)) {
try name.append(next);
next = try reader.readByte();
}
symbol.name = name.toOwnedSlice();
},
macho.BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB => {
symbol.segment = imm;
symbol.offset = try leb.readILEB128(i64, reader);
},
macho.BIND_OPCODE_SET_DYLIB_SPECIAL_IMM, macho.BIND_OPCODE_SET_DYLIB_ORDINAL_IMM => {
symbol.dylib_ordinal = imm;
},
macho.BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB => {
symbol.dylib_ordinal = try leb.readILEB128(i64, reader);
},
macho.BIND_OPCODE_SET_ADDEND_SLEB => {
symbol.addend = try leb.readILEB128(i64, reader);
},
else => {
std.log.warn("unhandled BIND_OPCODE_: 0x{x}", .{opcode});
},
}
}
assert(done);
}
/// Write the binding info table to byte stream.
pub fn write(self: LazyBindingInfoTable, writer: anytype) !void {
for (self.symbols.items) |symbol| {
try writer.writeByte(macho.BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB | @truncate(u4, symbol.segment));
try leb.writeILEB128(writer, symbol.offset);
if (symbol.addend) |addend| {
try writer.writeByte(macho.BIND_OPCODE_SET_ADDEND_SLEB);
try leb.writeILEB128(writer, addend);
}
if (symbol.dylib_ordinal > 15) {
try writer.writeByte(macho.BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB);
try leb.writeULEB128(writer, @bitCast(u64, symbol.dylib_ordinal));
} else if (symbol.dylib_ordinal > 0) {
try writer.writeByte(macho.BIND_OPCODE_SET_DYLIB_ORDINAL_IMM | @truncate(u4, @bitCast(u64, symbol.dylib_ordinal)));
} else {
try writer.writeByte(macho.BIND_OPCODE_SET_DYLIB_SPECIAL_IMM | @truncate(u4, @bitCast(u64, symbol.dylib_ordinal)));
}
if (symbol.name) |name| {
try writer.writeByte(macho.BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM); // TODO Sometimes we might want to add flags.
try writer.writeAll(name);
try writer.writeByte(0);
}
try writer.writeByte(macho.BIND_OPCODE_DO_BIND);
try writer.writeByte(macho.BIND_OPCODE_DONE);
}
}
/// Calculate size in bytes of this binding info table.
pub fn calcSize(self: *LazyBindingInfoTable) !usize {
var stream = std.io.countingWriter(std.io.null_writer);
var writer = stream.writer();
var size: usize = 0;
for (self.symbols.items) |symbol| {
size += 1;
try leb.writeILEB128(writer, symbol.offset);
if (symbol.addend) |addend| {
size += 1;
try leb.writeILEB128(writer, addend);
}
size += 1;
if (symbol.dylib_ordinal > 15) {
try leb.writeULEB128(writer, @bitCast(u64, symbol.dylib_ordinal));
}
if (symbol.name) |name| {
size += 1;
size += name.len;
size += 1;
}
size += 2;
}
size += stream.bytes_written;
return size;
}
}; | src/link/MachO/imports.zig |
const std = @import("std");
const mem = std.mem;
const testing = std.testing;
const Allocator = mem.Allocator;
const bog = @import("bog.zig");
const Token = bog.Token;
const TokenIndex = Token.Index;
const TokenId = @TagType(Token.Id);
const Tree = bog.Tree;
const Node = bog.Node;
const NodeList = std.ArrayList(*Node);
/// root : (stmt NL)* EOF
pub fn parse(gpa: *Allocator, source: []const u8, errors: *bog.Errors) (Parser.Error || bog.Tokenizer.Error)!*Tree {
const tokens = try bog.tokenize(gpa, source, errors);
errdefer gpa.free(tokens);
var arena = std.heap.ArenaAllocator.init(gpa);
errdefer arena.deinit();
var parser = Parser{
.arena = &arena.allocator,
.gpa = gpa,
.errors = errors,
.tokens = tokens,
};
var nodes = NodeList.init(gpa);
defer nodes.deinit();
while (true) switch (parser.tokens[parser.tok_index].id) {
.Comment, .Nl => parser.tok_index += 1,
else => break,
};
while (true) {
_ = try parser.eatIndent(0);
if (parser.eatToken(.Eof, false)) |_| break;
try nodes.append(try parser.stmt(0));
_ = parser.eatToken(.Nl, false) orelse {
_ = try parser.expectToken(.Eof, false);
break;
};
}
const tree = try parser.arena.create(Tree);
tree.* = .{
.tokens = tokens,
.nodes = try parser.arena.dupe(*Node, nodes.items),
.source = source,
.arena = arena.state,
.gpa = gpa,
};
return tree;
}
pub fn parseRepl(repl: *@import("repl.zig").Repl) Parser.Error!?*Node {
var parser = Parser{
.arena = repl.compiler.arena,
.gpa = repl.compiler.gpa,
.errors = &repl.vm.errors,
.tokens = repl.tokenizer.tokens.items,
.tok_index = repl.tok_index,
};
defer repl.tok_index = @intCast(u32, parser.tokens.len - 1);
if (parser.eatToken(.Eof, true)) |_| return null;
const ret = try parser.stmt(0);
_ = try parser.expectToken(.Nl, true);
_ = try parser.expectToken(.Eof, true);
return ret;
}
pub const Parser = struct {
arena: *Allocator,
gpa: *Allocator,
errors: *bog.Errors,
tokens: []const Token,
tok_index: TokenIndex = 0,
pub const Error = error{ParseError} || Allocator.Error;
/// stmt
/// : decl "=" block_or_expr
/// | expr
fn stmt(parser: *Parser, level: u16) Error!*Node {
if (try parser.decl(level)) |node| return node;
return parser.expr(false, true, level);
}
/// decl : ("let" | "const") bool_expr
fn decl(parser: *Parser, level: u16) Error!?*Node {
const tok = parser.eatToken(.Keyword_let, true) orelse
parser.eatToken(.Keyword_const, true) orelse return null;
const capture = try parser.boolExpr(true, true, level);
const eq_tok = try parser.expectToken(.Equal, false);
const value = try parser.blockOrExpr(false, true, level);
const node = try parser.arena.create(Node.Decl);
node.* = .{
.let_const = tok,
.capture = capture,
.eq_tok = eq_tok,
.value = value,
};
return &node.base;
}
/// expr
/// : fn
/// | jump_expr
/// | bool_expr assign?
fn expr(parser: *Parser, skip_nl: bool, allow_range: bool, level: u16) Error!*Node {
if (try parser.func(skip_nl, allow_range, level)) |node| return node;
if (try parser.jumpExpr(skip_nl, allow_range, level)) |node| return node;
return parser.assign(try parser.boolExpr(skip_nl, allow_range, level), skip_nl, allow_range, level);
}
/// block_or_expr : block | expr
fn blockOrExpr(parser: *Parser, skip_nl: bool, allow_range: bool, level: u16) Error!*Node {
if (!skip_nl) if (try parser.block(level)) |node| return node;
parser.skipNl();
return try parser.expr(skip_nl, allow_range, level);
}
/// fn : "fn" "(" (bool_expr ",")* bool_expr? ")" block_or_expr
fn func(parser: *Parser, skip_nl: bool, allow_range: bool, level: u16) Error!?*Node {
const tok = parser.eatToken(.Keyword_fn, true) orelse return null;
_ = try parser.expectToken(.LParen, true);
const params = try parser.listParser(skip_nl, level, boolExpr, .RParen, null);
const node = try parser.arena.create(Node.Fn);
node.* = .{
.fn_tok = tok,
.params = params.nodes,
.r_paren = params.term,
.body = try parser.blockOrExpr(skip_nl, allow_range, level),
};
return &node.base;
}
/// jump_expr : "return" block_or_expr? | "break" | "continue"
fn jumpExpr(parser: *Parser, skip_nl: bool, allow_range: bool, level: u16) Error!?*Node {
const tok = parser.nextToken(false);
const id = parser.tokens[tok].id;
switch (id) {
.Keyword_return, .Keyword_break, .Keyword_continue => {},
else => {
parser.tok_index = tok;
return null;
},
}
const res = if (id == .Keyword_return and switch (parser.tokens[parser.tok_index].id) {
.Eof, .Nl, .RParen, .RBrace, .RBracket, .Keyword_else, .Comma, .Colon => false,
else => true,
}) try parser.blockOrExpr(skip_nl, allow_range, level) else null;
const node = try parser.arena.create(Node.Jump);
node.* = .{
.tok = tok,
.op = switch (id) {
.Keyword_return => .{ .Return = res },
.Keyword_break => .Break,
.Keyword_continue => .Continue,
else => unreachable,
},
};
return &node.base;
}
/// bool_expr
/// : "not" comparison_expr
/// | comparison_expr ("or" comparison_expr)*
/// | comparison_expr ("and" comparison_expr)*
fn boolExpr(parser: *Parser, skip_nl: bool, allow_range: bool, level: u16) Error!*Node {
if (parser.eatToken(.Keyword_not, skip_nl)) |tok| {
parser.skipNl();
const node = try parser.arena.create(Node.Prefix);
node.* = .{
.op = .bool_not,
.rhs = try parser.comparisonExpr(skip_nl, allow_range, level),
.tok = tok,
};
return &node.base;
}
var lhs = try parser.comparisonExpr(skip_nl, allow_range, level);
if (parser.eatTokenNoNl(.Keyword_or)) |t| {
var tok = t;
while (true) {
parser.skipNl();
const node = try parser.arena.create(Node.Infix);
node.* = .{
.lhs = lhs,
.tok = tok,
.op = .bool_or,
.rhs = try parser.comparisonExpr(skip_nl, allow_range, level),
};
lhs = &node.base;
if (parser.eatTokenNoNl(.Keyword_or)) |tt| tok = tt else break;
}
} else {
while (parser.eatTokenNoNl(.Keyword_and)) |tok| {
parser.skipNl();
const node = try parser.arena.create(Node.Infix);
node.* = .{
.lhs = lhs,
.tok = tok,
.op = .bool_and,
.rhs = try parser.comparisonExpr(skip_nl, allow_range, level),
};
lhs = &node.base;
}
}
return lhs;
}
/// comparison_expr
/// : range_expr (("<" | "<=" | ">" | ">="| "==" | "!=" | "in") range_expr)?
/// | range_expr ("is" type_name)?
fn comparisonExpr(parser: *Parser, skip_nl: bool, allow_range: bool, level: u16) Error!*Node {
const lhs = try parser.rangeExpr(skip_nl, allow_range, level);
// we can safely skip any newlines here
const start = parser.tok_index;
parser.skipNl();
const tok = parser.nextToken(true);
const id = parser.tokens[tok].id;
switch (id) {
.LArr, .LArrEqual, .RArr, .RArrEqual, .EqualEqual, .BangEqual, .Keyword_in => {
parser.skipNl();
const node = try parser.arena.create(Node.Infix);
node.* = .{
.lhs = lhs,
.tok = tok,
.op = switch (id) {
.LArr => .less_than,
.LArrEqual => .less_than_equal,
.RArr => .greater_than,
.RArrEqual => .greater_than_equal,
.EqualEqual => .equal,
.BangEqual => .not_equal,
.Keyword_in => .in,
else => unreachable,
},
.rhs = try parser.rangeExpr(skip_nl, allow_range, level),
};
return &node.base;
},
.Keyword_is => {
parser.skipNl();
const node = try parser.arena.create(Node.TypeInfix);
node.* = .{
.lhs = lhs,
.op = .is,
.tok = tok,
.type_tok = try parser.typeName(skip_nl),
};
return &node.base;
},
else => {
parser.tok_index = start;
return lhs;
},
}
}
/// type_name : "none" | "int" | "num" | "bool" | "str" | "tuple" | "map" | "list" | "error" | "range" | "fn"
fn typeName(parser: *Parser, skip_nl: bool) Error!TokenIndex {
return parser.eatToken(.Keyword_error, skip_nl) orelse
parser.eatToken(.Keyword_fn, skip_nl) orelse
parser.eatToken(.Identifier, skip_nl) orelse
parser.reportErr("expected type name", parser.tokens[parser.tok_index]);
}
/// range_expr : bit_expr? (":" bit_expr? (":" bit_expr?)?)?
fn rangeExpr(parser: *Parser, skip_nl: bool, allow_range: bool, level: u16) Error!*Node {
if (!allow_range) {
return parser.bitExpr(skip_nl, allow_range, level);
}
// This grammar would be much easier to implement with infinite lookahead
// maybe that would be worth doing some time.
var start: ?*Node = null;
var colon_1 = parser.eatToken(.Colon, skip_nl);
if (colon_1 == null) {
start = try parser.bitExpr(skip_nl, false, level);
colon_1 = parser.eatToken(.Colon, skip_nl);
// not a range
if (colon_1 == null) return start.?;
}
var end: ?*Node = null;
var colon_2 = parser.eatToken(.Colon, skip_nl);
if (colon_2 == null) {
switch (parser.tokens[parser.tok_index].id) {
.Eof, .Nl, .RParen, .RBrace, .RBracket, .Keyword_else, .Comma, .Colon => {},
else => end = try parser.bitExpr(skip_nl, false, level),
}
colon_2 = parser.eatToken(.Colon, skip_nl);
}
var step: ?*Node = null;
if (colon_2 != null) {
switch (parser.tokens[parser.tok_index].id) {
.Eof, .Nl, .RParen, .RBrace, .RBracket, .Keyword_else, .Comma, .Colon => {},
else => step = try parser.bitExpr(skip_nl, false, level),
}
}
const node = try parser.arena.create(Node.Range);
node.* = .{
.start = start,
.end = end,
.step = step,
.colon_1 = colon_1.?,
.colon_2 = colon_2,
};
return &node.base;
}
/// bit_expr : shift_expr (("&" shift_expr)* | ("|" shift_expr)* | ("^" shift_expr)*
fn bitExpr(parser: *Parser, skip_nl: bool, allow_range: bool, level: u16) Error!*Node {
var lhs = try parser.shiftExpr(skip_nl, allow_range, level);
if (parser.eatTokenNoNl(.Ampersand)) |t| {
// &
var tok = t;
while (true) {
parser.skipNl();
const node = try parser.arena.create(Node.Infix);
node.* = .{
.lhs = lhs,
.tok = tok,
.op = .bit_and,
.rhs = try parser.shiftExpr(skip_nl, allow_range, level),
};
lhs = &node.base;
if (parser.eatTokenNoNl(.Ampersand)) |tt| tok = tt else break;
}
} else if (parser.eatTokenNoNl(.Pipe)) |t| {
// |
var tok = t;
while (true) {
parser.skipNl();
const node = try parser.arena.create(Node.Infix);
node.* = .{
.lhs = lhs,
.tok = tok,
.op = .bit_or,
.rhs = try parser.shiftExpr(skip_nl, allow_range, level),
};
lhs = &node.base;
if (parser.eatTokenNoNl(.Pipe)) |tt| tok = tt else break;
}
} else if (parser.eatTokenNoNl(.Caret)) |t| {
// ^
var tok = t;
while (true) {
parser.skipNl();
const node = try parser.arena.create(Node.Infix);
node.* = .{
.lhs = lhs,
.tok = tok,
.op = .bit_xor,
.rhs = try parser.shiftExpr(skip_nl, allow_range, level),
};
lhs = &node.base;
if (parser.eatTokenNoNl(.Caret)) |tt| tok = tt else break;
}
}
return lhs;
}
/// shift_expr : add_expr (("<<" | ">>") add_expr)
fn shiftExpr(parser: *Parser, skip_nl: bool, allow_range: bool, level: u16) Error!*Node {
const lhs = try parser.addExpr(skip_nl, allow_range, level);
// we can safely skip any newlines here
const start = parser.tok_index;
parser.skipNl();
const tok = parser.nextToken(true);
const id = parser.tokens[tok].id;
switch (id) {
.LArrArr, .RArrArr => {
parser.skipNl();
const node = try parser.arena.create(Node.Infix);
node.* = .{
.lhs = lhs,
.tok = tok,
.op = if (id == .LArrArr) .l_shift else .r_shift,
.rhs = try parser.addExpr(skip_nl, allow_range, level),
};
return &node.base;
},
else => {
parser.tok_index = start;
return lhs;
},
}
}
/// add_expr : mul_expr (("-" | "+" | "++") mul_expr)*
fn addExpr(parser: *Parser, skip_nl: bool, allow_range: bool, level: u16) Error!*Node {
var lhs = try parser.mulExpr(skip_nl, allow_range, level);
while (true) {
const tok = parser.nextToken(skip_nl);
const id = parser.tokens[tok].id;
switch (id) {
.Minus, .Plus, .PlusPlus => {
parser.skipNl();
const node = try parser.arena.create(Node.Infix);
node.* = .{
.lhs = lhs,
.tok = tok,
.op = switch (id) {
.Minus => .sub,
.Plus => .add,
.PlusPlus => .append,
else => unreachable,
},
.rhs = try parser.mulExpr(skip_nl, allow_range, level),
};
lhs = &node.base;
},
else => {
parser.tok_index = tok;
return lhs;
},
}
}
}
/// mul_expr : cast_expr (("*" | "/" | "//" | "%") cast_expr)*
fn mulExpr(parser: *Parser, skip_nl: bool, allow_range: bool, level: u16) Error!*Node {
var lhs = try parser.castExpr(skip_nl, allow_range, level);
while (true) {
// we can safely skip any newlines here
const start = parser.tok_index;
parser.skipNl();
const tok = parser.nextToken(true);
const id = parser.tokens[tok].id;
switch (id) {
.Asterisk, .Slash, .SlashSlash, .Percent => {
parser.skipNl();
const node = try parser.arena.create(Node.Infix);
node.* = .{
.lhs = lhs,
.tok = tok,
.op = switch (id) {
.Asterisk => .mul,
.Slash => .div,
.SlashSlash => .div_floor,
.Percent => .mod,
else => unreachable,
},
.rhs = try parser.castExpr(skip_nl, allow_range, level),
};
lhs = &node.base;
},
else => {
parser.tok_index = start;
return lhs;
},
}
}
return lhs;
}
/// cast_expr : prefix_expr ("as" type_name)?
fn castExpr(parser: *Parser, skip_nl: bool, allow_range: bool, level: u16) Error!*Node {
var lhs = try parser.prefixExpr(skip_nl, allow_range, level);
if (parser.eatTokenNoNl(.Keyword_as)) |tok| {
parser.skipNl();
const node = try parser.arena.create(Node.TypeInfix);
node.* = .{
.lhs = lhs,
.op = .as,
.tok = tok,
.type_tok = try parser.typeName(skip_nl),
};
lhs = &node.base;
}
return lhs;
}
/// prefix_expr : ("-" | "+" | "~")? power_expr
fn prefixExpr(parser: *Parser, skip_nl: bool, allow_range: bool, level: u16) Error!*Node {
const tok = parser.nextToken(skip_nl);
const id = parser.tokens[tok].id;
switch (id) {
.Minus, .Plus, .Tilde => {
parser.skipNl();
const node = try parser.arena.create(Node.Prefix);
node.* = .{
.op = switch (id) {
.Minus => .minus,
.Plus => .plus,
.Tilde => .bit_not,
else => unreachable,
},
.tok = tok,
.rhs = try parser.powerExpr(skip_nl, allow_range, level),
};
return &node.base;
},
else => {
parser.tok_index = tok;
return try parser.powerExpr(skip_nl, allow_range, level);
},
}
}
/// power_expr : primary_expr suffix_expr* ("**" power_expr)?
fn powerExpr(parser: *Parser, skip_nl: bool, allow_range: bool, level: u16) Error!*Node {
var primary = try parser.primaryExpr(skip_nl, allow_range, level);
primary = try parser.suffixExpr(primary, skip_nl, level);
if (parser.eatTokenNoNl(.AsteriskAsterisk)) |tok| {
parser.skipNl();
const node = try parser.arena.create(Node.Infix);
node.* = .{
.lhs = primary,
.tok = tok,
.op = .pow,
.rhs = try parser.powerExpr(skip_nl, allow_range, level),
};
return &node.base;
}
return primary;
}
/// suffix_expr
/// : "[" expr "]"
/// | "(" (expr ",")* expr? ")"
/// | "." IDENTIFIER
fn suffixExpr(parser: *Parser, primary: *Node, skip_nl: bool, level: u16) Error!*Node {
var lhs = primary;
while (true) {
if (parser.eatToken(.LBracket, skip_nl)) |tok| {
parser.skipNl();
const node = try parser.arena.create(Node.Suffix);
node.* = .{
.lhs = lhs,
.l_tok = tok,
.op = .{ .subscript = try parser.expr(true, true, level) },
.r_tok = try parser.expectToken(.RBracket, false),
};
lhs = &node.base;
} else if (parser.eatToken(.LParen, true)) |tok| {
const args = try parser.listParser(skip_nl, level, expr, .RParen, null);
const node = try parser.arena.create(Node.Suffix);
node.* = .{
.lhs = lhs,
.l_tok = tok,
.op = .{ .call = args.nodes },
.r_tok = args.term,
};
lhs = &node.base;
} else if (parser.eatTokenNoNl(.Period)) |tok| {
parser.skipNl();
const node = try parser.arena.create(Node.Suffix);
node.* = .{
.lhs = lhs,
.l_tok = tok,
.op = .member,
.r_tok = try parser.expectToken(.Identifier, false),
};
lhs = &node.base;
} else {
return lhs;
}
}
}
/// assign : ("=" | "+=" | "-=" | "*=" | "**=" | "/=" | "//=" | "%=" | "<<=" | ">>=" | "&=" | "|=" | "^=") block_or_expr
fn assign(parser: *Parser, lhs: *Node, skip_nl: bool, allow_range: bool, level: u16) Error!*Node {
const tok = parser.nextToken(false);
const id = parser.tokens[tok].id;
switch (id) {
.Equal,
.PlusEqual,
.MinusEqual,
.AsteriskEqual,
.AsteriskAsteriskEqual,
.SlashEqual,
.SlashSlashEqual,
.PercentEqual,
.LArrArrEqual,
.RArrArrEqual,
.AmpersandEqual,
.PipeEqual,
.CaretEqual,
=> {
const node = try parser.arena.create(Node.Infix);
node.* = .{
.lhs = lhs,
.tok = tok,
.op = switch (id) {
.Equal => .assign,
.PlusEqual => .add_assign,
.MinusEqual => .sub_assign,
.AsteriskEqual => .mul_assign,
.AsteriskAsteriskEqual => .pow_assign,
.SlashEqual => .div_assign,
.SlashSlashEqual => .div_floor_assign,
.PercentEqual => .mod_assign,
.LArrArrEqual => .l_shift_assign,
.RArrArrEqual => .r_shift_assign,
.AmpersandEqual => .bit_and_assign,
.PipeEqual => .bit_or_assign,
.CaretEqual => .bit_x_or_assign,
else => unreachable,
},
.rhs = try parser.blockOrExpr(skip_nl, allow_range, level),
};
return &node.base;
},
else => {
parser.tok_index = tok;
return lhs;
},
}
}
/// primary_expr
/// : IDENTIFIER
/// | "_"
/// | STRING
/// | format_string
/// | NUMBER
/// | "true"
/// | "false"
/// | "(" ")"
/// | initializer
/// | "error" initializer?
/// | "@" IDENTIFIER initializer?
/// | "import" "(" STRING ")"
/// | if
/// | while
/// | for
/// | match
/// | try
fn primaryExpr(parser: *Parser, skip_nl: bool, allow_range: bool, level: u16) Error!*Node {
const tok = parser.nextToken(false);
const id = parser.tokens[tok].id;
switch (id) {
.Number, .Integer, .String, .Keyword_true, .Keyword_false => {
if (skip_nl) parser.skipNl();
const node = try parser.arena.create(Node.Literal);
node.* = .{
.tok = tok,
.kind = switch (id) {
.Number => .num,
.Integer => .int,
.String => .str,
.Keyword_true => .True,
.Keyword_false => .False,
else => unreachable,
},
};
return &node.base;
},
.Identifier => {
if (skip_nl) parser.skipNl();
const node = try parser.arena.create(Node.SingleToken);
node.* = .{
.base = .{ .id = .Identifier },
.tok = tok,
};
return &node.base;
},
.Keyword_this => {
if (skip_nl) parser.skipNl();
const node = try parser.arena.create(Node.SingleToken);
node.* = .{
.base = .{ .id = .This },
.tok = tok,
};
return &node.base;
},
.Underscore => {
if (skip_nl) parser.skipNl();
const node = try parser.arena.create(Node.SingleToken);
node.* = .{
.base = .{ .id = .Discard },
.tok = tok,
};
return &node.base;
},
.Keyword_error => {
if (skip_nl) parser.skipNl();
const node = try parser.arena.create(Node.Error);
node.* = .{
.tok = tok,
.capture = try parser.initializer(skip_nl, level),
};
return &node.base;
},
.At => {
parser.skipNl();
const node = try parser.arena.create(Node.Tagged);
node.* = .{
.at = tok,
.name = try parser.expectToken(.Identifier, skip_nl),
.capture = try parser.initializer(skip_nl, level),
};
return &node.base;
},
.Keyword_import => {
_ = try parser.expectToken(.LParen, true);
const node = try parser.arena.create(Node.Import);
node.* = .{
.tok = tok,
.str_tok = try parser.expectToken(.String, true),
.r_paren = try parser.expectToken(.RParen, skip_nl),
};
return &node.base;
},
.LParen => {
parser.skipNl();
if (parser.eatToken(.RParen, skip_nl)) |rparen| {
const node = try parser.arena.create(Node.Literal);
node.* = .{
.tok = rparen,
.kind = .none,
};
return &node.base;
} else {
parser.tok_index = tok;
}
},
else => {
parser.tok_index = tok;
},
}
if (try parser.formatString(skip_nl, level)) |res| return res;
if (try parser.initializer(skip_nl, level)) |res| return res;
if (try parser.ifExpr(skip_nl, allow_range, level)) |res| return res;
if (try parser.whileExpr(skip_nl, allow_range, level)) |res| return res;
if (try parser.forExpr(skip_nl, allow_range, level)) |res| return res;
if (try parser.matchExpr(skip_nl, level)) |res| return res;
if (try parser.tryExpr(skip_nl, allow_range, level)) |res| return res;
return parser.reportErr("expected Identifier, String, Number, true, false, '(', '{{', '[', error, try, import, if, while, for or match", parser.tokens[parser.tok_index]);
}
/// format_string : FORMAT_START expr (FORMAT expr)* FORMAT_END
fn formatString(parser: *Parser, skip_nl: bool, level: u16) Error!?*Node {
const first = parser.eatToken(.FormatStart, true) orelse return null;
var toks = std.ArrayList(TokenIndex).init(parser.gpa);
defer toks.deinit();
try toks.append(first);
var args = NodeList.init(parser.gpa);
defer args.deinit();
while (true) {
try args.append(try parser.expr(true, true, level));
if (parser.eatToken(.Format, true)) |tok| {
try toks.append(tok);
} else break;
}
try toks.append(try parser.expectToken(.FormatEnd, skip_nl));
const node = try parser.arena.create(Node.FormatString);
node.* = .{
.format = try parser.arena.dupe(TokenIndex, toks.items),
.args = try parser.arena.dupe(*Node, args.items),
};
return &node.base;
}
/// initializer
/// : "(" block_or_expr ")"
/// | "(" (expr ",")+ expr? ")"
/// | "{" (expr_no_range ":" expr_no_range ",")* (expr_no_range ":" expr_no_range)? "}"
/// | "[" (expr ",")* expr? "]"
fn initializer(parser: *Parser, skip_nl: bool, level: u16) Error!?*Node {
if (parser.eatToken(.LBrace, true)) |tok| {
const elems = try parser.listParser(skip_nl, level, mapItem, .RBrace, null);
const node = try parser.arena.create(Node.ListTupleMap);
node.* = .{
.base = .{ .id = .Map },
.l_tok = tok,
.values = elems.nodes,
.r_tok = elems.term,
};
return &node.base;
} else if (parser.eatToken(.LBracket, true)) |tok| {
const elems = try parser.listParser(skip_nl, level, expr, .RBracket, null);
const node = try parser.arena.create(Node.ListTupleMap);
node.* = .{
.base = .{ .id = .List },
.l_tok = tok,
.values = elems.nodes,
.r_tok = elems.term,
};
return &node.base;
} else if (parser.eatToken(.LParen, false)) |tok| {
if (try parser.block(level)) |b| {
parser.skipNl();
const node = try parser.arena.create(Node.Grouped);
node.* = .{
.l_tok = tok,
.expr = b,
.r_tok = try parser.expectToken(.RParen, skip_nl),
};
return &node.base;
}
parser.skipNl();
const first = try parser.expr(true, true, level);
if (parser.eatToken(.RParen, skip_nl)) |r_tok| {
const node = try parser.arena.create(Node.Grouped);
node.* = .{
.l_tok = tok,
.expr = first,
.r_tok = r_tok,
};
return &node.base;
}
_ = try parser.expectToken(.Comma, true);
var elems = try parser.listParser(skip_nl, level, expr, .RParen, first);
const node = try parser.arena.create(Node.ListTupleMap);
node.* = .{
.base = .{ .id = .Tuple },
.l_tok = tok,
.values = elems.nodes,
.r_tok = elems.term,
};
return &node.base;
} else return null;
}
/// expr (":" expr)?
fn mapItem(parser: *Parser, skip_nl: bool, _: bool, level: u16) Error!*Node {
var key: ?*Node = null;
var value = try parser.expr(true, false, level);
var colon: ?TokenIndex = null;
if (parser.eatToken(.Colon, true)) |tok| {
colon = tok;
key = value;
value = try parser.expr(true, false, level);
}
const item = try parser.arena.create(Node.MapItem);
item.* = .{
.key = key,
.colon = colon,
.value = value,
};
return &item.base;
}
const ListParserRes = struct {
nodes: []*Node,
term: TokenIndex,
};
/// (PARSE_FN ",")* PARSE_FN? TERM
fn listParser(parser: *Parser, skip_nl: bool, level: u16, parseFn: fn (*Parser, bool, bool, u16) Error!*Node, term_id: TokenId, first: ?*Node) Error!ListParserRes {
var nodes = NodeList.init(parser.gpa);
defer nodes.deinit();
if (first) |some| try nodes.append(some);
var term: TokenIndex = parser.tok_index;
var end = false;
while (true) {
if (parser.eatToken(term_id, skip_nl)) |term_tok| {
term = term_tok;
break;
} else if (end) {
term = try parser.expectToken(term_id, skip_nl);
break;
}
try nodes.append(try parseFn(parser, true, true, level));
if (parser.eatToken(.Comma, true) == null) end = true;
}
return ListParserRes{
.nodes = try parser.arena.dupe(*Node, nodes.items),
.term = term,
};
}
/// block : NL BEGIN (stmt NL)+ END
fn block(parser: *Parser, level: u16) Error!?*Node {
_ = parser.eatToken(.Nl, false) orelse return null;
var stmts = NodeList.init(parser.gpa);
defer stmts.deinit();
const indent = parser.eatToken(.Indent, false);
if (indent == null or parser.tokens[indent.?].id.Indent <= level)
return parser.reportErr("expected indentation", parser.tokens[parser.tok_index]);
const new_level = parser.tokens[indent.?].id.Indent;
var last_nl = parser.tok_index;
while (true) {
try stmts.append(try parser.stmt(new_level));
last_nl = parser.eatToken(.Nl, false) orelse {
last_nl = try parser.expectToken(.Eof, false);
break;
};
if (!try parser.eatIndent(new_level)) break;
}
// reset to previous new line since all statements are expected to end in a newline
parser.tok_index = last_nl;
const node = try parser.arena.create(Node.Block);
node.* = .{
.base = .{ .id = .Block },
.stmts = try parser.arena.dupe(*Node, stmts.items),
};
return &node.base;
}
/// if : "if" "(" (decl "=")? expr ")" block_or_expr ("else" block_or_expr)?
fn ifExpr(parser: *Parser, skip_nl: bool, allow_range: bool, level: u16) Error!?*Node {
const tok = parser.eatToken(.Keyword_if, true) orelse return null;
_ = try parser.expectToken(.LParen, true);
const let_const = parser.eatToken(.Keyword_let, true) orelse
parser.eatToken(.Keyword_const, true);
const node = try parser.arena.create(Node.If);
node.* = .{
.if_tok = tok,
.let_const = let_const,
.capture = if (let_const != null) try parser.primaryExpr(true, true, level) else null,
.eq_tok = if (let_const != null) try parser.expectToken(.Equal, true) else null,
.cond = try parser.expr(true, true, level),
.r_paren = try parser.expectToken(.RParen, false),
.if_body = try parser.blockOrExpr(skip_nl, allow_range, level),
.else_tok = parser.eatTokenNoNl(.Keyword_else),
.else_body = null,
};
if (node.else_tok != null) {
node.else_body = try parser.blockOrExpr(skip_nl, allow_range, level);
}
return &node.base;
}
/// while : "while" "(" (decl "=")? expr ")" block_or_expr
fn whileExpr(parser: *Parser, skip_nl: bool, allow_range: bool, level: u16) Error!?*Node {
const tok = parser.eatToken(.Keyword_while, true) orelse return null;
_ = try parser.expectToken(.LParen, true);
const let_const = parser.eatToken(.Keyword_let, true) orelse
parser.eatToken(.Keyword_const, true);
const node = try parser.arena.create(Node.While);
node.* = .{
.while_tok = tok,
.let_const = let_const,
.capture = if (let_const != null) try parser.primaryExpr(true, true, level) else null,
.eq_tok = if (let_const != null) try parser.expectToken(.Equal, true) else null,
.cond = try parser.expr(true, true, level),
.r_paren = try parser.expectToken(.RParen, false),
.body = try parser.blockOrExpr(skip_nl, allow_range, level),
};
return &node.base;
}
/// for : "for" "(" (decl "in")? expr ")" block_or_expr
fn forExpr(parser: *Parser, skip_nl: bool, allow_range: bool, level: u16) Error!?*Node {
const tok = parser.eatToken(.Keyword_for, true) orelse return null;
_ = try parser.expectToken(.LParen, true);
const let_const = parser.eatToken(.Keyword_let, true) orelse
parser.eatToken(.Keyword_const, true);
const node = try parser.arena.create(Node.For);
node.* = .{
.for_tok = tok,
.let_const = let_const,
.capture = if (let_const != null) try parser.primaryExpr(true, true, level) else null,
.in_tok = if (let_const != null) try parser.expectToken(.Keyword_in, true) else null,
.cond = try parser.expr(true, true, level),
.r_paren = try parser.expectToken(.RParen, false),
.body = try parser.blockOrExpr(skip_nl, allow_range, level),
};
return &node.base;
}
/// match : "match" "(" expr ")" (NL match_case)+ NL
fn matchExpr(parser: *Parser, skip_nl: bool, level: u16) Error!?*Node {
const tok = parser.eatToken(.Keyword_match, true) orelse return null;
_ = try parser.expectToken(.LParen, true);
const cond = try parser.expr(true, true, level);
const r_paren = try parser.expectToken(.RParen, false);
_ = try parser.expectToken(.Nl, false);
var cases = NodeList.init(parser.gpa);
defer cases.deinit();
const indent = parser.eatToken(.Indent, false);
if (indent == null or parser.tokens[indent.?].id.Indent <= level)
return parser.reportErr("expected indentation", parser.tokens[parser.tok_index]);
const new_level = parser.tokens[indent.?].id.Indent;
var last_nl = parser.tok_index;
while (true) {
try cases.append(try parser.matchCase(new_level));
last_nl = parser.eatToken(.Nl, false) orelse {
last_nl = try parser.expectToken(.Eof, false);
break;
};
if (!try parser.eatIndent(new_level)) break;
}
// reset to previous new line since all statements are expected to end in a newline
parser.tok_index = last_nl;
const node = try parser.arena.create(Node.Match);
node.* = .{
.match_tok = tok,
.expr = cond,
.cases = try parser.arena.dupe(*Node, cases.items),
.r_paren = r_paren,
};
return &node.base;
}
/// match_case
/// : decl "=>" block_or_expr
/// | expr ("," expr)* ","? "=>" block_or_expr
fn matchCase(parser: *Parser, level: u16) Error!*Node {
if (parser.eatToken(.Keyword_let, true) orelse
parser.eatToken(.Keyword_const, true)) |let_const|
{
const node = try parser.arena.create(Node.MatchLet);
node.* = .{
.let_const = let_const,
.capture = try parser.primaryExpr(true, true, level),
.eq_arr = try parser.expectToken(.EqualRarr, false),
.expr = try parser.blockOrExpr(false, true, level),
};
return &node.base;
} else if (parser.eatToken(.Underscore, true)) |u| {
const node = try parser.arena.create(Node.MatchCatchAll);
node.* = .{
.tok = u,
.eq_arr = try parser.expectToken(.EqualRarr, false),
.expr = try parser.blockOrExpr(false, true, level),
};
return &node.base;
} else {
const items = try parser.listParser(true, level, expr, .EqualRarr, null);
const node = try parser.arena.create(Node.MatchCase);
node.* = .{
.items = items.nodes,
.eq_arr = items.term,
.expr = try parser.blockOrExpr(false, true, level),
};
return &node.base;
}
}
/// try : "try" block_or_expr ("catch" ("(" decl ")" | expr)? block_or_expr)+
fn tryExpr(parser: *Parser, skip_nl: bool, allow_range: bool, level: u16) Error!?*Node {
const tok = parser.eatToken(.Keyword_try, false) orelse return null;
const body = try parser.blockOrExpr(false, allow_range, level);
var cases = NodeList.init(parser.gpa);
defer cases.deinit();
try cases.append((try parser.catchExpr(skip_nl, allow_range, level)) orelse {
return parser.reportErr("expected at least one catch", parser.tokens[parser.tok_index]);
});
while (try parser.catchExpr(skip_nl, allow_range, level)) |catch_expr| {
try cases.append(catch_expr);
}
const node = try parser.arena.create(Node.Try);
node.* = .{
.tok = tok,
.expr = body,
.catches = try parser.arena.dupe(*Node, cases.items),
};
return &node.base;
}
/// "catch" ("(" decl ")" | expr)? block_or_expr
fn catchExpr(parser: *Parser, skip_nl: bool, allow_range: bool, level: u16) Error!?*Node {
const tok = parser.eatTokenNoNl(.Keyword_catch) orelse return null;
const node = try parser.arena.create(Node.Catch);
node.* = .{
.tok = tok,
.let_const = null,
.capture = null,
.expr = undefined,
};
if (parser.eatTokenNoNl(.LParen)) |_| {
parser.skipNl();
node.let_const = parser.eatToken(.Keyword_let, true) orelse
parser.eatToken(.Keyword_const, true);
node.capture = if (node.let_const) |_|
try parser.primaryExpr(true, true, level)
else
try parser.expr(true, true, level);
_ = try parser.expectToken(.RParen, false);
}
node.expr = try parser.blockOrExpr(skip_nl, allow_range, level);
return &node.base;
}
fn reportErr(parser: *Parser, msg: []const u8, tok: Token) Error {
try parser.errors.add(.{ .data = msg }, tok.start, .err);
return error.ParseError;
}
/// skips nl begins and ends
fn skipNl(parser: *Parser) void {
_ = parser.eatToken(.Nl, true);
}
fn eatIndent(parser: *Parser, level: u16) !bool {
const start_index = parser.tok_index;
const tok = parser.eatToken(.Indent, false) orelse return false;
const indent = parser.tokens[tok].id.Indent;
if (indent > level) return parser.reportErr("unexpected indentation", parser.tokens[parser.tok_index]);
if (indent == level) return true;
parser.tok_index = start_index;
return false;
}
fn nextToken(parser: *Parser, skip_nl: bool) TokenIndex {
const result = parser.tok_index;
parser.tok_index += 1;
std.debug.assert(parser.tokens[result].id != .Comment);
if (parser.tok_index >= parser.tokens.len) return result;
while (true) {
switch (parser.tokens[parser.tok_index].id) {
// skip nl and indent if they are not meaningful
.Indent => if (!skip_nl) break,
.Nl => if (!skip_nl and
(parser.tok_index + 1 <= parser.tokens.len and
parser.tokens[parser.tok_index + 1].id != .Comment)) break,
// always skip comments
.Comment => {},
else => break,
}
parser.tok_index += 1;
}
return result;
}
fn eatToken(parser: *Parser, id: TokenId, skip_nl: bool) ?TokenIndex {
return if (parser.tokens[parser.tok_index].id == id) parser.nextToken(skip_nl) else null;
}
fn eatTokenNoNl(parser: *Parser, id: TokenId) ?TokenIndex {
const start = parser.tok_index;
parser.skipNl();
if (parser.eatToken(id, false)) |tok| return tok else {
parser.tok_index = start;
return null;
}
}
fn expectToken(parser: *Parser, id: TokenId, skip_nl: bool) !TokenIndex {
if (parser.eatToken(id, skip_nl)) |tok| return tok;
const tok = parser.tokens[parser.tok_index];
try parser.errors.add(try bog.Value.String.init(
parser.gpa,
"expected '{}', found '{}'",
.{ Token.string(id), Token.string(tok.id) },
), tok.start, .err);
return error.ParseError;
}
}; | src/parser.zig |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.