code
stringlengths 38
801k
| repo_path
stringlengths 6
263
|
---|---|
pub const HTTP_DEMAND_CBT = @as(u32, 4);
pub const HTTP_MAX_SERVER_QUEUE_LENGTH = @as(u32, 2147483647);
pub const HTTP_MIN_SERVER_QUEUE_LENGTH = @as(u32, 1);
pub const HTTP_AUTH_ENABLE_BASIC = @as(u32, 1);
pub const HTTP_AUTH_ENABLE_DIGEST = @as(u32, 2);
pub const HTTP_AUTH_ENABLE_NTLM = @as(u32, 4);
pub const HTTP_AUTH_ENABLE_NEGOTIATE = @as(u32, 8);
pub const HTTP_AUTH_ENABLE_KERBEROS = @as(u32, 16);
pub const HTTP_AUTH_EX_FLAG_ENABLE_KERBEROS_CREDENTIAL_CACHING = @as(u32, 1);
pub const HTTP_AUTH_EX_FLAG_CAPTURE_CREDENTIAL = @as(u32, 2);
pub const HTTP_CHANNEL_BIND_PROXY = @as(u32, 1);
pub const HTTP_CHANNEL_BIND_PROXY_COHOSTING = @as(u32, 32);
pub const HTTP_CHANNEL_BIND_NO_SERVICE_NAME_CHECK = @as(u32, 2);
pub const HTTP_CHANNEL_BIND_DOTLESS_SERVICE = @as(u32, 4);
pub const HTTP_CHANNEL_BIND_SECURE_CHANNEL_TOKEN = @as(u32, 8);
pub const HTTP_CHANNEL_BIND_CLIENT_SERVICE = @as(u32, 16);
pub const HTTP_LOG_FIELD_DATE = @as(u32, 1);
pub const HTTP_LOG_FIELD_TIME = @as(u32, 2);
pub const HTTP_LOG_FIELD_CLIENT_IP = @as(u32, 4);
pub const HTTP_LOG_FIELD_USER_NAME = @as(u32, 8);
pub const HTTP_LOG_FIELD_SITE_NAME = @as(u32, 16);
pub const HTTP_LOG_FIELD_COMPUTER_NAME = @as(u32, 32);
pub const HTTP_LOG_FIELD_SERVER_IP = @as(u32, 64);
pub const HTTP_LOG_FIELD_METHOD = @as(u32, 128);
pub const HTTP_LOG_FIELD_URI_STEM = @as(u32, 256);
pub const HTTP_LOG_FIELD_URI_QUERY = @as(u32, 512);
pub const HTTP_LOG_FIELD_STATUS = @as(u32, 1024);
pub const HTTP_LOG_FIELD_WIN32_STATUS = @as(u32, 2048);
pub const HTTP_LOG_FIELD_BYTES_SENT = @as(u32, 4096);
pub const HTTP_LOG_FIELD_BYTES_RECV = @as(u32, 8192);
pub const HTTP_LOG_FIELD_TIME_TAKEN = @as(u32, 16384);
pub const HTTP_LOG_FIELD_SERVER_PORT = @as(u32, 32768);
pub const HTTP_LOG_FIELD_USER_AGENT = @as(u32, 65536);
pub const HTTP_LOG_FIELD_COOKIE = @as(u32, 131072);
pub const HTTP_LOG_FIELD_REFERER = @as(u32, 262144);
pub const HTTP_LOG_FIELD_VERSION = @as(u32, 524288);
pub const HTTP_LOG_FIELD_HOST = @as(u32, 1048576);
pub const HTTP_LOG_FIELD_SUB_STATUS = @as(u32, 2097152);
pub const HTTP_LOG_FIELD_STREAM_ID = @as(u32, 134217728);
pub const HTTP_LOG_FIELD_STREAM_ID_EX = @as(u32, 268435456);
pub const HTTP_LOG_FIELD_TRANSPORT_TYPE = @as(u32, 536870912);
pub const HTTP_LOG_FIELD_CLIENT_PORT = @as(u32, 4194304);
pub const HTTP_LOG_FIELD_URI = @as(u32, 8388608);
pub const HTTP_LOG_FIELD_SITE_ID = @as(u32, 16777216);
pub const HTTP_LOG_FIELD_REASON = @as(u32, 33554432);
pub const HTTP_LOG_FIELD_QUEUE_NAME = @as(u32, 67108864);
pub const HTTP_LOG_FIELD_CORRELATION_ID = @as(u32, 1073741824);
pub const HTTP_LOGGING_FLAG_LOCAL_TIME_ROLLOVER = @as(u32, 1);
pub const HTTP_LOGGING_FLAG_USE_UTF8_CONVERSION = @as(u32, 2);
pub const HTTP_LOGGING_FLAG_LOG_ERRORS_ONLY = @as(u32, 4);
pub const HTTP_LOGGING_FLAG_LOG_SUCCESS_ONLY = @as(u32, 8);
pub const HTTP_CREATE_REQUEST_QUEUE_FLAG_OPEN_EXISTING = @as(u32, 1);
pub const HTTP_CREATE_REQUEST_QUEUE_FLAG_CONTROLLER = @as(u32, 2);
pub const HTTP_CREATE_REQUEST_QUEUE_FLAG_DELEGATION = @as(u32, 8);
pub const HTTP_RECEIVE_REQUEST_ENTITY_BODY_FLAG_FILL_BUFFER = @as(u32, 1);
pub const HTTP_SEND_RESPONSE_FLAG_DISCONNECT = @as(u32, 1);
pub const HTTP_SEND_RESPONSE_FLAG_MORE_DATA = @as(u32, 2);
pub const HTTP_SEND_RESPONSE_FLAG_BUFFER_DATA = @as(u32, 4);
pub const HTTP_SEND_RESPONSE_FLAG_ENABLE_NAGLING = @as(u32, 8);
pub const HTTP_SEND_RESPONSE_FLAG_PROCESS_RANGES = @as(u32, 32);
pub const HTTP_SEND_RESPONSE_FLAG_OPAQUE = @as(u32, 64);
pub const HTTP_SEND_RESPONSE_FLAG_GOAWAY = @as(u32, 256);
pub const HTTP_FLUSH_RESPONSE_FLAG_RECURSIVE = @as(u32, 1);
pub const HTTP_URL_FLAG_REMOVE_ALL = @as(u32, 1);
pub const HTTP_RECEIVE_SECURE_CHANNEL_TOKEN = @as(u32, 1);
pub const HTTP_RECEIVE_FULL_CHAIN = @as(u32, 2);
pub const HTTP_REQUEST_SIZING_INFO_FLAG_TCP_FAST_OPEN = @as(u32, 1);
pub const HTTP_REQUEST_SIZING_INFO_FLAG_TLS_SESSION_RESUMPTION = @as(u32, 2);
pub const HTTP_REQUEST_SIZING_INFO_FLAG_TLS_FALSE_START = @as(u32, 4);
pub const HTTP_REQUEST_SIZING_INFO_FLAG_FIRST_REQUEST = @as(u32, 8);
pub const HTTP_REQUEST_AUTH_FLAG_TOKEN_FOR_CACHED_CRED = @as(u32, 1);
pub const HTTP_REQUEST_FLAG_MORE_ENTITY_BODY_EXISTS = @as(u32, 1);
pub const HTTP_REQUEST_FLAG_IP_ROUTED = @as(u32, 2);
pub const HTTP_REQUEST_FLAG_HTTP2 = @as(u32, 4);
pub const HTTP_REQUEST_FLAG_HTTP3 = @as(u32, 8);
pub const HTTP_RESPONSE_FLAG_MULTIPLE_ENCODINGS_AVAILABLE = @as(u32, 1);
pub const HTTP_RESPONSE_FLAG_MORE_ENTITY_BODY_EXISTS = @as(u32, 2);
pub const HTTP_RESPONSE_INFO_FLAGS_PRESERVE_ORDER = @as(u32, 1);
pub const HTTP_SERVICE_CONFIG_SSL_FLAG_USE_DS_MAPPER = @as(u32, 1);
pub const HTTP_SERVICE_CONFIG_SSL_FLAG_NEGOTIATE_CLIENT_CERT = @as(u32, 2);
pub const HTTP_SERVICE_CONFIG_SSL_FLAG_NO_RAW_FILTER = @as(u32, 4);
pub const HTTP_SERVICE_CONFIG_SSL_FLAG_REJECT = @as(u32, 8);
pub const HTTP_SERVICE_CONFIG_SSL_FLAG_DISABLE_HTTP2 = @as(u32, 16);
pub const HTTP_SERVICE_CONFIG_SSL_FLAG_DISABLE_QUIC = @as(u32, 32);
pub const HTTP_SERVICE_CONFIG_SSL_FLAG_DISABLE_TLS13 = @as(u32, 64);
pub const HTTP_SERVICE_CONFIG_SSL_FLAG_DISABLE_OCSP_STAPLING = @as(u32, 128);
pub const HTTP_SERVICE_CONFIG_SSL_FLAG_ENABLE_TOKEN_BINDING = @as(u32, 256);
pub const HTTP_SERVICE_CONFIG_SSL_FLAG_LOG_EXTENDED_EVENTS = @as(u32, 512);
pub const HTTP_SERVICE_CONFIG_SSL_FLAG_DISABLE_LEGACY_TLS = @as(u32, 1024);
pub const HTTP_SERVICE_CONFIG_SSL_FLAG_ENABLE_SESSION_TICKET = @as(u32, 2048);
pub const HTTP_SERVICE_CONFIG_SSL_FLAG_DISABLE_TLS12 = @as(u32, 4096);
pub const HTTP_SERVICE_CONFIG_SSL_FLAG_ENABLE_CLIENT_CORRELATION = @as(u32, 8192);
pub const HTTP_REQUEST_PROPERTY_SNI_HOST_MAX_LENGTH = @as(u32, 255);
pub const HTTP_REQUEST_PROPERTY_SNI_FLAG_SNI_USED = @as(u32, 1);
pub const HTTP_REQUEST_PROPERTY_SNI_FLAG_NO_SNI = @as(u32, 2);
//--------------------------------------------------------------------------------
// Section: Types (123)
//--------------------------------------------------------------------------------
pub const HTTP_RECEIVE_HTTP_REQUEST_FLAGS = enum(u32) {
COPY_BODY = 1,
FLUSH_BODY = 2,
};
pub const HTTP_RECEIVE_REQUEST_FLAG_COPY_BODY = HTTP_RECEIVE_HTTP_REQUEST_FLAGS.COPY_BODY;
pub const HTTP_RECEIVE_REQUEST_FLAG_FLUSH_BODY = HTTP_RECEIVE_HTTP_REQUEST_FLAGS.FLUSH_BODY;
pub const HTTP_INITIALIZE = enum(u32) {
CONFIG = 2,
SERVER = 1,
_,
pub fn initFlags(o: struct {
CONFIG: u1 = 0,
SERVER: u1 = 0,
}) HTTP_INITIALIZE {
return @intToEnum(HTTP_INITIALIZE,
(if (o.CONFIG == 1) @enumToInt(HTTP_INITIALIZE.CONFIG) else 0)
| (if (o.SERVER == 1) @enumToInt(HTTP_INITIALIZE.SERVER) else 0)
);
}
};
pub const HTTP_INITIALIZE_CONFIG = HTTP_INITIALIZE.CONFIG;
pub const HTTP_INITIALIZE_SERVER = HTTP_INITIALIZE.SERVER;
pub const HTTP_SERVER_PROPERTY = enum(i32) {
AuthenticationProperty = 0,
LoggingProperty = 1,
QosProperty = 2,
TimeoutsProperty = 3,
QueueLengthProperty = 4,
StateProperty = 5,
@"503VerbosityProperty" = 6,
BindingProperty = 7,
ExtendedAuthenticationProperty = 8,
ListenEndpointProperty = 9,
ChannelBindProperty = 10,
ProtectionLevelProperty = 11,
DelegationProperty = 16,
};
pub const HttpServerAuthenticationProperty = HTTP_SERVER_PROPERTY.AuthenticationProperty;
pub const HttpServerLoggingProperty = HTTP_SERVER_PROPERTY.LoggingProperty;
pub const HttpServerQosProperty = HTTP_SERVER_PROPERTY.QosProperty;
pub const HttpServerTimeoutsProperty = HTTP_SERVER_PROPERTY.TimeoutsProperty;
pub const HttpServerQueueLengthProperty = HTTP_SERVER_PROPERTY.QueueLengthProperty;
pub const HttpServerStateProperty = HTTP_SERVER_PROPERTY.StateProperty;
pub const HttpServer503VerbosityProperty = HTTP_SERVER_PROPERTY.@"503VerbosityProperty";
pub const HttpServerBindingProperty = HTTP_SERVER_PROPERTY.BindingProperty;
pub const HttpServerExtendedAuthenticationProperty = HTTP_SERVER_PROPERTY.ExtendedAuthenticationProperty;
pub const HttpServerListenEndpointProperty = HTTP_SERVER_PROPERTY.ListenEndpointProperty;
pub const HttpServerChannelBindProperty = HTTP_SERVER_PROPERTY.ChannelBindProperty;
pub const HttpServerProtectionLevelProperty = HTTP_SERVER_PROPERTY.ProtectionLevelProperty;
pub const HttpServerDelegationProperty = HTTP_SERVER_PROPERTY.DelegationProperty;
pub const HTTP_PROPERTY_FLAGS = extern struct {
_bitfield: u32,
};
pub const HTTP_ENABLED_STATE = enum(i32) {
Active = 0,
Inactive = 1,
};
pub const HttpEnabledStateActive = HTTP_ENABLED_STATE.Active;
pub const HttpEnabledStateInactive = HTTP_ENABLED_STATE.Inactive;
pub const HTTP_STATE_INFO = extern struct {
Flags: HTTP_PROPERTY_FLAGS,
State: HTTP_ENABLED_STATE,
};
pub const HTTP_503_RESPONSE_VERBOSITY = enum(i32) {
Basic = 0,
Limited = 1,
Full = 2,
};
pub const Http503ResponseVerbosityBasic = HTTP_503_RESPONSE_VERBOSITY.Basic;
pub const Http503ResponseVerbosityLimited = HTTP_503_RESPONSE_VERBOSITY.Limited;
pub const Http503ResponseVerbosityFull = HTTP_503_RESPONSE_VERBOSITY.Full;
pub const HTTP_QOS_SETTING_TYPE = enum(i32) {
Bandwidth = 0,
ConnectionLimit = 1,
FlowRate = 2,
};
pub const HttpQosSettingTypeBandwidth = HTTP_QOS_SETTING_TYPE.Bandwidth;
pub const HttpQosSettingTypeConnectionLimit = HTTP_QOS_SETTING_TYPE.ConnectionLimit;
pub const HttpQosSettingTypeFlowRate = HTTP_QOS_SETTING_TYPE.FlowRate;
pub const HTTP_QOS_SETTING_INFO = extern struct {
QosType: HTTP_QOS_SETTING_TYPE,
QosSetting: ?*anyopaque,
};
pub const HTTP_CONNECTION_LIMIT_INFO = extern struct {
Flags: HTTP_PROPERTY_FLAGS,
MaxConnections: u32,
};
pub const HTTP_BANDWIDTH_LIMIT_INFO = extern struct {
Flags: HTTP_PROPERTY_FLAGS,
MaxBandwidth: u32,
};
pub const HTTP_FLOWRATE_INFO = extern struct {
Flags: HTTP_PROPERTY_FLAGS,
MaxBandwidth: u32,
MaxPeakBandwidth: u32,
BurstSize: u32,
};
pub const HTTP_SERVICE_CONFIG_TIMEOUT_KEY = enum(i32) {
IdleConnectionTimeout = 0,
HeaderWaitTimeout = 1,
};
pub const IdleConnectionTimeout = HTTP_SERVICE_CONFIG_TIMEOUT_KEY.IdleConnectionTimeout;
pub const HeaderWaitTimeout = HTTP_SERVICE_CONFIG_TIMEOUT_KEY.HeaderWaitTimeout;
pub const HTTP_SERVICE_CONFIG_TIMEOUT_SET = extern struct {
KeyDesc: HTTP_SERVICE_CONFIG_TIMEOUT_KEY,
ParamDesc: u16,
};
pub const HTTP_TIMEOUT_LIMIT_INFO = extern struct {
Flags: HTTP_PROPERTY_FLAGS,
EntityBody: u16,
DrainEntityBody: u16,
RequestQueue: u16,
IdleConnection: u16,
HeaderWait: u16,
MinSendRate: u32,
};
pub const HTTP_SERVICE_CONFIG_SETTING_KEY = enum(i32) {
None = 0,
TlsThrottle = 1,
};
pub const HttpNone = HTTP_SERVICE_CONFIG_SETTING_KEY.None;
pub const HttpTlsThrottle = HTTP_SERVICE_CONFIG_SETTING_KEY.TlsThrottle;
pub const HTTP_SERVICE_CONFIG_SETTING_SET = extern struct {
KeyDesc: HTTP_SERVICE_CONFIG_SETTING_KEY,
ParamDesc: u32,
};
pub const HTTP_LISTEN_ENDPOINT_INFO = extern struct {
Flags: HTTP_PROPERTY_FLAGS,
EnableSharing: BOOLEAN,
};
pub const HTTP_SERVER_AUTHENTICATION_DIGEST_PARAMS = extern struct {
DomainNameLength: u16,
DomainName: ?PWSTR,
RealmLength: u16,
Realm: ?PWSTR,
};
pub const HTTP_SERVER_AUTHENTICATION_BASIC_PARAMS = extern struct {
RealmLength: u16,
Realm: ?PWSTR,
};
pub const HTTP_SERVER_AUTHENTICATION_INFO = extern struct {
Flags: HTTP_PROPERTY_FLAGS,
AuthSchemes: u32,
ReceiveMutualAuth: BOOLEAN,
ReceiveContextHandle: BOOLEAN,
DisableNTLMCredentialCaching: BOOLEAN,
ExFlags: u8,
DigestParams: HTTP_SERVER_AUTHENTICATION_DIGEST_PARAMS,
BasicParams: HTTP_SERVER_AUTHENTICATION_BASIC_PARAMS,
};
pub const HTTP_SERVICE_BINDING_TYPE = enum(i32) {
None = 0,
W = 1,
A = 2,
};
pub const HttpServiceBindingTypeNone = HTTP_SERVICE_BINDING_TYPE.None;
pub const HttpServiceBindingTypeW = HTTP_SERVICE_BINDING_TYPE.W;
pub const HttpServiceBindingTypeA = HTTP_SERVICE_BINDING_TYPE.A;
pub const HTTP_SERVICE_BINDING_BASE = extern struct {
Type: HTTP_SERVICE_BINDING_TYPE,
};
pub const HTTP_SERVICE_BINDING_A = extern struct {
Base: HTTP_SERVICE_BINDING_BASE,
Buffer: ?[*]u8,
BufferSize: u32,
};
pub const HTTP_SERVICE_BINDING_W = extern struct {
Base: HTTP_SERVICE_BINDING_BASE,
Buffer: ?[*]u16,
BufferSize: u32,
};
pub const HTTP_AUTHENTICATION_HARDENING_LEVELS = enum(i32) {
Legacy = 0,
Medium = 1,
Strict = 2,
};
pub const HttpAuthenticationHardeningLegacy = HTTP_AUTHENTICATION_HARDENING_LEVELS.Legacy;
pub const HttpAuthenticationHardeningMedium = HTTP_AUTHENTICATION_HARDENING_LEVELS.Medium;
pub const HttpAuthenticationHardeningStrict = HTTP_AUTHENTICATION_HARDENING_LEVELS.Strict;
pub const HTTP_CHANNEL_BIND_INFO = extern struct {
Hardening: HTTP_AUTHENTICATION_HARDENING_LEVELS,
Flags: u32,
ServiceNames: ?*?*HTTP_SERVICE_BINDING_BASE,
NumberOfServiceNames: u32,
};
pub const HTTP_REQUEST_CHANNEL_BIND_STATUS = extern struct {
ServiceName: ?*HTTP_SERVICE_BINDING_BASE,
ChannelToken: ?*u8,
ChannelTokenSize: u32,
Flags: u32,
};
pub const HTTP_REQUEST_TOKEN_BINDING_INFO = extern struct {
TokenBinding: ?*u8,
TokenBindingSize: u32,
EKM: ?*u8,
EKMSize: u32,
KeyType: u8,
};
pub const HTTP_LOGGING_TYPE = enum(i32) {
W3C = 0,
IIS = 1,
NCSA = 2,
Raw = 3,
};
pub const HttpLoggingTypeW3C = HTTP_LOGGING_TYPE.W3C;
pub const HttpLoggingTypeIIS = HTTP_LOGGING_TYPE.IIS;
pub const HttpLoggingTypeNCSA = HTTP_LOGGING_TYPE.NCSA;
pub const HttpLoggingTypeRaw = HTTP_LOGGING_TYPE.Raw;
pub const HTTP_LOGGING_ROLLOVER_TYPE = enum(i32) {
Size = 0,
Daily = 1,
Weekly = 2,
Monthly = 3,
Hourly = 4,
};
pub const HttpLoggingRolloverSize = HTTP_LOGGING_ROLLOVER_TYPE.Size;
pub const HttpLoggingRolloverDaily = HTTP_LOGGING_ROLLOVER_TYPE.Daily;
pub const HttpLoggingRolloverWeekly = HTTP_LOGGING_ROLLOVER_TYPE.Weekly;
pub const HttpLoggingRolloverMonthly = HTTP_LOGGING_ROLLOVER_TYPE.Monthly;
pub const HttpLoggingRolloverHourly = HTTP_LOGGING_ROLLOVER_TYPE.Hourly;
pub const HTTP_LOGGING_INFO = extern struct {
Flags: HTTP_PROPERTY_FLAGS,
LoggingFlags: u32,
SoftwareName: ?[*:0]const u16,
SoftwareNameLength: u16,
DirectoryNameLength: u16,
DirectoryName: ?[*:0]const u16,
Format: HTTP_LOGGING_TYPE,
Fields: u32,
pExtFields: ?*anyopaque,
NumOfExtFields: u16,
MaxRecordSize: u16,
RolloverType: HTTP_LOGGING_ROLLOVER_TYPE,
RolloverSize: u32,
pSecurityDescriptor: ?*SECURITY_DESCRIPTOR,
};
pub const HTTP_BINDING_INFO = extern struct {
Flags: HTTP_PROPERTY_FLAGS,
RequestQueueHandle: ?HANDLE,
};
pub const HTTP_PROTECTION_LEVEL_TYPE = enum(i32) {
Unrestricted = 0,
EdgeRestricted = 1,
Restricted = 2,
};
pub const HttpProtectionLevelUnrestricted = HTTP_PROTECTION_LEVEL_TYPE.Unrestricted;
pub const HttpProtectionLevelEdgeRestricted = HTTP_PROTECTION_LEVEL_TYPE.EdgeRestricted;
pub const HttpProtectionLevelRestricted = HTTP_PROTECTION_LEVEL_TYPE.Restricted;
pub const HTTP_PROTECTION_LEVEL_INFO = extern struct {
Flags: HTTP_PROPERTY_FLAGS,
Level: HTTP_PROTECTION_LEVEL_TYPE,
};
pub const HTTP_BYTE_RANGE = extern struct {
StartingOffset: ULARGE_INTEGER,
Length: ULARGE_INTEGER,
};
pub const HTTP_VERSION = extern struct {
MajorVersion: u16,
MinorVersion: u16,
};
pub const HTTP_SCHEME = enum(i32) {
Http = 0,
Https = 1,
Maximum = 2,
};
pub const HttpSchemeHttp = HTTP_SCHEME.Http;
pub const HttpSchemeHttps = HTTP_SCHEME.Https;
pub const HttpSchemeMaximum = HTTP_SCHEME.Maximum;
pub const HTTP_VERB = enum(i32) {
Unparsed = 0,
Unknown = 1,
Invalid = 2,
OPTIONS = 3,
GET = 4,
HEAD = 5,
POST = 6,
PUT = 7,
DELETE = 8,
TRACE = 9,
CONNECT = 10,
TRACK = 11,
MOVE = 12,
COPY = 13,
PROPFIND = 14,
PROPPATCH = 15,
MKCOL = 16,
LOCK = 17,
UNLOCK = 18,
SEARCH = 19,
Maximum = 20,
};
pub const HttpVerbUnparsed = HTTP_VERB.Unparsed;
pub const HttpVerbUnknown = HTTP_VERB.Unknown;
pub const HttpVerbInvalid = HTTP_VERB.Invalid;
pub const HttpVerbOPTIONS = HTTP_VERB.OPTIONS;
pub const HttpVerbGET = HTTP_VERB.GET;
pub const HttpVerbHEAD = HTTP_VERB.HEAD;
pub const HttpVerbPOST = HTTP_VERB.POST;
pub const HttpVerbPUT = HTTP_VERB.PUT;
pub const HttpVerbDELETE = HTTP_VERB.DELETE;
pub const HttpVerbTRACE = HTTP_VERB.TRACE;
pub const HttpVerbCONNECT = HTTP_VERB.CONNECT;
pub const HttpVerbTRACK = HTTP_VERB.TRACK;
pub const HttpVerbMOVE = HTTP_VERB.MOVE;
pub const HttpVerbCOPY = HTTP_VERB.COPY;
pub const HttpVerbPROPFIND = HTTP_VERB.PROPFIND;
pub const HttpVerbPROPPATCH = HTTP_VERB.PROPPATCH;
pub const HttpVerbMKCOL = HTTP_VERB.MKCOL;
pub const HttpVerbLOCK = HTTP_VERB.LOCK;
pub const HttpVerbUNLOCK = HTTP_VERB.UNLOCK;
pub const HttpVerbSEARCH = HTTP_VERB.SEARCH;
pub const HttpVerbMaximum = HTTP_VERB.Maximum;
pub const HTTP_HEADER_ID = enum(i32) {
CacheControl = 0,
Connection = 1,
Date = 2,
KeepAlive = 3,
Pragma = 4,
Trailer = 5,
TransferEncoding = 6,
Upgrade = 7,
Via = 8,
Warning = 9,
Allow = 10,
ContentLength = 11,
ContentType = 12,
ContentEncoding = 13,
ContentLanguage = 14,
ContentLocation = 15,
ContentMd5 = 16,
ContentRange = 17,
Expires = 18,
LastModified = 19,
Accept = 20,
AcceptCharset = 21,
AcceptEncoding = 22,
AcceptLanguage = 23,
Authorization = 24,
Cookie = 25,
Expect = 26,
From = 27,
Host = 28,
IfMatch = 29,
IfModifiedSince = 30,
IfNoneMatch = 31,
IfRange = 32,
IfUnmodifiedSince = 33,
MaxForwards = 34,
ProxyAuthorization = 35,
Referer = 36,
Range = 37,
Te = 38,
Translate = 39,
UserAgent = 40,
RequestMaximum = 41,
// AcceptRanges = 20, this enum value conflicts with Accept
// Age = 21, this enum value conflicts with AcceptCharset
// Etag = 22, this enum value conflicts with AcceptEncoding
// Location = 23, this enum value conflicts with AcceptLanguage
// ProxyAuthenticate = 24, this enum value conflicts with Authorization
// RetryAfter = 25, this enum value conflicts with Cookie
// Server = 26, this enum value conflicts with Expect
// SetCookie = 27, this enum value conflicts with From
// Vary = 28, this enum value conflicts with Host
// WwwAuthenticate = 29, this enum value conflicts with IfMatch
// ResponseMaximum = 30, this enum value conflicts with IfModifiedSince
// Maximum = 41, this enum value conflicts with RequestMaximum
};
pub const HttpHeaderCacheControl = HTTP_HEADER_ID.CacheControl;
pub const HttpHeaderConnection = HTTP_HEADER_ID.Connection;
pub const HttpHeaderDate = HTTP_HEADER_ID.Date;
pub const HttpHeaderKeepAlive = HTTP_HEADER_ID.KeepAlive;
pub const HttpHeaderPragma = HTTP_HEADER_ID.Pragma;
pub const HttpHeaderTrailer = HTTP_HEADER_ID.Trailer;
pub const HttpHeaderTransferEncoding = HTTP_HEADER_ID.TransferEncoding;
pub const HttpHeaderUpgrade = HTTP_HEADER_ID.Upgrade;
pub const HttpHeaderVia = HTTP_HEADER_ID.Via;
pub const HttpHeaderWarning = HTTP_HEADER_ID.Warning;
pub const HttpHeaderAllow = HTTP_HEADER_ID.Allow;
pub const HttpHeaderContentLength = HTTP_HEADER_ID.ContentLength;
pub const HttpHeaderContentType = HTTP_HEADER_ID.ContentType;
pub const HttpHeaderContentEncoding = HTTP_HEADER_ID.ContentEncoding;
pub const HttpHeaderContentLanguage = HTTP_HEADER_ID.ContentLanguage;
pub const HttpHeaderContentLocation = HTTP_HEADER_ID.ContentLocation;
pub const HttpHeaderContentMd5 = HTTP_HEADER_ID.ContentMd5;
pub const HttpHeaderContentRange = HTTP_HEADER_ID.ContentRange;
pub const HttpHeaderExpires = HTTP_HEADER_ID.Expires;
pub const HttpHeaderLastModified = HTTP_HEADER_ID.LastModified;
pub const HttpHeaderAccept = HTTP_HEADER_ID.Accept;
pub const HttpHeaderAcceptCharset = HTTP_HEADER_ID.AcceptCharset;
pub const HttpHeaderAcceptEncoding = HTTP_HEADER_ID.AcceptEncoding;
pub const HttpHeaderAcceptLanguage = HTTP_HEADER_ID.AcceptLanguage;
pub const HttpHeaderAuthorization = HTTP_HEADER_ID.Authorization;
pub const HttpHeaderCookie = HTTP_HEADER_ID.Cookie;
pub const HttpHeaderExpect = HTTP_HEADER_ID.Expect;
pub const HttpHeaderFrom = HTTP_HEADER_ID.From;
pub const HttpHeaderHost = HTTP_HEADER_ID.Host;
pub const HttpHeaderIfMatch = HTTP_HEADER_ID.IfMatch;
pub const HttpHeaderIfModifiedSince = HTTP_HEADER_ID.IfModifiedSince;
pub const HttpHeaderIfNoneMatch = HTTP_HEADER_ID.IfNoneMatch;
pub const HttpHeaderIfRange = HTTP_HEADER_ID.IfRange;
pub const HttpHeaderIfUnmodifiedSince = HTTP_HEADER_ID.IfUnmodifiedSince;
pub const HttpHeaderMaxForwards = HTTP_HEADER_ID.MaxForwards;
pub const HttpHeaderProxyAuthorization = HTTP_HEADER_ID.ProxyAuthorization;
pub const HttpHeaderReferer = HTTP_HEADER_ID.Referer;
pub const HttpHeaderRange = HTTP_HEADER_ID.Range;
pub const HttpHeaderTe = HTTP_HEADER_ID.Te;
pub const HttpHeaderTranslate = HTTP_HEADER_ID.Translate;
pub const HttpHeaderUserAgent = HTTP_HEADER_ID.UserAgent;
pub const HttpHeaderRequestMaximum = HTTP_HEADER_ID.RequestMaximum;
pub const HttpHeaderAcceptRanges = HTTP_HEADER_ID.Accept;
pub const HttpHeaderAge = HTTP_HEADER_ID.AcceptCharset;
pub const HttpHeaderEtag = HTTP_HEADER_ID.AcceptEncoding;
pub const HttpHeaderLocation = HTTP_HEADER_ID.AcceptLanguage;
pub const HttpHeaderProxyAuthenticate = HTTP_HEADER_ID.Authorization;
pub const HttpHeaderRetryAfter = HTTP_HEADER_ID.Cookie;
pub const HttpHeaderServer = HTTP_HEADER_ID.Expect;
pub const HttpHeaderSetCookie = HTTP_HEADER_ID.From;
pub const HttpHeaderVary = HTTP_HEADER_ID.Host;
pub const HttpHeaderWwwAuthenticate = HTTP_HEADER_ID.IfMatch;
pub const HttpHeaderResponseMaximum = HTTP_HEADER_ID.IfModifiedSince;
pub const HttpHeaderMaximum = HTTP_HEADER_ID.RequestMaximum;
pub const HTTP_KNOWN_HEADER = extern struct {
RawValueLength: u16,
pRawValue: ?[*:0]const u8,
};
pub const HTTP_UNKNOWN_HEADER = extern struct {
NameLength: u16,
RawValueLength: u16,
pName: ?[*:0]const u8,
pRawValue: ?[*:0]const u8,
};
pub const HTTP_LOG_DATA_TYPE = enum(i32) {
s = 0,
};
pub const HttpLogDataTypeFields = HTTP_LOG_DATA_TYPE.s;
pub const HTTP_LOG_DATA = extern struct {
Type: HTTP_LOG_DATA_TYPE,
};
pub const HTTP_LOG_FIELDS_DATA = extern struct {
Base: HTTP_LOG_DATA,
UserNameLength: u16,
UriStemLength: u16,
ClientIpLength: u16,
ServerNameLength: u16,
ServiceNameLength: u16,
ServerIpLength: u16,
MethodLength: u16,
UriQueryLength: u16,
HostLength: u16,
UserAgentLength: u16,
CookieLength: u16,
ReferrerLength: u16,
UserName: ?[*]u16,
UriStem: ?[*]u16,
ClientIp: ?[*]u8,
ServerName: ?[*]u8,
ServiceName: ?[*]u8,
ServerIp: ?[*]u8,
Method: ?[*]u8,
UriQuery: ?[*]u8,
Host: ?[*]u8,
UserAgent: ?[*]u8,
Cookie: ?[*]u8,
Referrer: ?[*]u8,
ServerPort: u16,
ProtocolStatus: u16,
Win32Status: u32,
MethodNum: HTTP_VERB,
SubStatus: u16,
};
pub const HTTP_DATA_CHUNK_TYPE = enum(i32) {
FromMemory = 0,
FromFileHandle = 1,
FromFragmentCache = 2,
FromFragmentCacheEx = 3,
Trailers = 4,
Maximum = 5,
};
pub const HttpDataChunkFromMemory = HTTP_DATA_CHUNK_TYPE.FromMemory;
pub const HttpDataChunkFromFileHandle = HTTP_DATA_CHUNK_TYPE.FromFileHandle;
pub const HttpDataChunkFromFragmentCache = HTTP_DATA_CHUNK_TYPE.FromFragmentCache;
pub const HttpDataChunkFromFragmentCacheEx = HTTP_DATA_CHUNK_TYPE.FromFragmentCacheEx;
pub const HttpDataChunkTrailers = HTTP_DATA_CHUNK_TYPE.Trailers;
pub const HttpDataChunkMaximum = HTTP_DATA_CHUNK_TYPE.Maximum;
pub const HTTP_DATA_CHUNK = extern struct {
DataChunkType: HTTP_DATA_CHUNK_TYPE,
Anonymous: extern union {
FromMemory: extern struct {
pBuffer: ?*anyopaque,
BufferLength: u32,
},
FromFileHandle: extern struct {
ByteRange: HTTP_BYTE_RANGE,
FileHandle: ?HANDLE,
},
FromFragmentCache: extern struct {
FragmentNameLength: u16,
pFragmentName: ?[*:0]const u16,
},
FromFragmentCacheEx: extern struct {
ByteRange: HTTP_BYTE_RANGE,
pFragmentName: ?[*:0]const u16,
},
Trailers: extern struct {
TrailerCount: u16,
pTrailers: ?*HTTP_UNKNOWN_HEADER,
},
},
};
pub const HTTP_REQUEST_HEADERS = extern struct {
UnknownHeaderCount: u16,
pUnknownHeaders: ?*HTTP_UNKNOWN_HEADER,
TrailerCount: u16,
pTrailers: ?*HTTP_UNKNOWN_HEADER,
KnownHeaders: [41]HTTP_KNOWN_HEADER,
};
pub const HTTP_RESPONSE_HEADERS = extern struct {
UnknownHeaderCount: u16,
pUnknownHeaders: ?*HTTP_UNKNOWN_HEADER,
TrailerCount: u16,
pTrailers: ?*HTTP_UNKNOWN_HEADER,
KnownHeaders: [30]HTTP_KNOWN_HEADER,
};
pub const HTTP_DELEGATE_REQUEST_PROPERTY_ID = enum(i32) {
ReservedProperty = 0,
DelegateUrlProperty = 1,
};
pub const DelegateRequestReservedProperty = HTTP_DELEGATE_REQUEST_PROPERTY_ID.ReservedProperty;
pub const DelegateRequestDelegateUrlProperty = HTTP_DELEGATE_REQUEST_PROPERTY_ID.DelegateUrlProperty;
pub const HTTP_DELEGATE_REQUEST_PROPERTY_INFO = extern struct {
PropertyId: HTTP_DELEGATE_REQUEST_PROPERTY_ID,
PropertyInfoLength: u32,
PropertyInfo: ?*anyopaque,
};
pub const HTTP_CREATE_REQUEST_QUEUE_PROPERTY_ID = enum(i32) {
ExternalIdProperty = 1,
Max = 2,
};
pub const CreateRequestQueueExternalIdProperty = HTTP_CREATE_REQUEST_QUEUE_PROPERTY_ID.ExternalIdProperty;
pub const CreateRequestQueueMax = HTTP_CREATE_REQUEST_QUEUE_PROPERTY_ID.Max;
pub const HTTP_CREATE_REQUEST_QUEUE_PROPERTY_INFO = extern struct {
PropertyId: HTTP_CREATE_REQUEST_QUEUE_PROPERTY_ID,
PropertyInfoLength: u32,
PropertyInfo: ?*anyopaque,
};
pub const HTTP_TRANSPORT_ADDRESS = extern struct {
pRemoteAddress: ?*SOCKADDR,
pLocalAddress: ?*SOCKADDR,
};
pub const HTTP_COOKED_URL = extern struct {
FullUrlLength: u16,
HostLength: u16,
AbsPathLength: u16,
QueryStringLength: u16,
pFullUrl: ?[*:0]const u16,
pHost: ?[*:0]const u16,
pAbsPath: ?[*:0]const u16,
pQueryString: ?[*:0]const u16,
};
pub const HTTP_AUTH_STATUS = enum(i32) {
Success = 0,
NotAuthenticated = 1,
Failure = 2,
};
pub const HttpAuthStatusSuccess = HTTP_AUTH_STATUS.Success;
pub const HttpAuthStatusNotAuthenticated = HTTP_AUTH_STATUS.NotAuthenticated;
pub const HttpAuthStatusFailure = HTTP_AUTH_STATUS.Failure;
pub const HTTP_REQUEST_AUTH_TYPE = enum(i32) {
None = 0,
Basic = 1,
Digest = 2,
NTLM = 3,
Negotiate = 4,
Kerberos = 5,
};
pub const HttpRequestAuthTypeNone = HTTP_REQUEST_AUTH_TYPE.None;
pub const HttpRequestAuthTypeBasic = HTTP_REQUEST_AUTH_TYPE.Basic;
pub const HttpRequestAuthTypeDigest = HTTP_REQUEST_AUTH_TYPE.Digest;
pub const HttpRequestAuthTypeNTLM = HTTP_REQUEST_AUTH_TYPE.NTLM;
pub const HttpRequestAuthTypeNegotiate = HTTP_REQUEST_AUTH_TYPE.Negotiate;
pub const HttpRequestAuthTypeKerberos = HTTP_REQUEST_AUTH_TYPE.Kerberos;
pub const HTTP_SSL_CLIENT_CERT_INFO = extern struct {
CertFlags: u32,
CertEncodedSize: u32,
pCertEncoded: ?*u8,
Token: ?HANDLE,
CertDeniedByMapper: BOOLEAN,
};
pub const HTTP_SSL_INFO = extern struct {
ServerCertKeySize: u16,
ConnectionKeySize: u16,
ServerCertIssuerSize: u32,
ServerCertSubjectSize: u32,
pServerCertIssuer: ?[*:0]const u8,
pServerCertSubject: ?[*:0]const u8,
pClientCertInfo: ?*HTTP_SSL_CLIENT_CERT_INFO,
SslClientCertNegotiated: u32,
};
pub const HTTP_SSL_PROTOCOL_INFO = extern struct {
Protocol: u32,
CipherType: u32,
CipherStrength: u32,
HashType: u32,
HashStrength: u32,
KeyExchangeType: u32,
KeyExchangeStrength: u32,
};
pub const HTTP_REQUEST_SIZING_TYPE = enum(i32) {
TlsHandshakeLeg1ClientData = 0,
TlsHandshakeLeg1ServerData = 1,
TlsHandshakeLeg2ClientData = 2,
TlsHandshakeLeg2ServerData = 3,
Headers = 4,
Max = 5,
};
pub const HttpRequestSizingTypeTlsHandshakeLeg1ClientData = HTTP_REQUEST_SIZING_TYPE.TlsHandshakeLeg1ClientData;
pub const HttpRequestSizingTypeTlsHandshakeLeg1ServerData = HTTP_REQUEST_SIZING_TYPE.TlsHandshakeLeg1ServerData;
pub const HttpRequestSizingTypeTlsHandshakeLeg2ClientData = HTTP_REQUEST_SIZING_TYPE.TlsHandshakeLeg2ClientData;
pub const HttpRequestSizingTypeTlsHandshakeLeg2ServerData = HTTP_REQUEST_SIZING_TYPE.TlsHandshakeLeg2ServerData;
pub const HttpRequestSizingTypeHeaders = HTTP_REQUEST_SIZING_TYPE.Headers;
pub const HttpRequestSizingTypeMax = HTTP_REQUEST_SIZING_TYPE.Max;
pub const HTTP_REQUEST_SIZING_INFO = extern struct {
Flags: u64,
RequestIndex: u32,
RequestSizingCount: u32,
RequestSizing: [5]u64,
};
pub const HTTP_REQUEST_TIMING_TYPE = enum(i32) {
ConnectionStart = 0,
DataStart = 1,
TlsCertificateLoadStart = 2,
TlsCertificateLoadEnd = 3,
TlsHandshakeLeg1Start = 4,
TlsHandshakeLeg1End = 5,
TlsHandshakeLeg2Start = 6,
TlsHandshakeLeg2End = 7,
TlsAttributesQueryStart = 8,
TlsAttributesQueryEnd = 9,
TlsClientCertQueryStart = 10,
TlsClientCertQueryEnd = 11,
Http2StreamStart = 12,
Http2HeaderDecodeStart = 13,
Http2HeaderDecodeEnd = 14,
RequestHeaderParseStart = 15,
RequestHeaderParseEnd = 16,
RequestRoutingStart = 17,
RequestRoutingEnd = 18,
RequestQueuedForInspection = 19,
RequestDeliveredForInspection = 20,
RequestReturnedAfterInspection = 21,
RequestQueuedForDelegation = 22,
RequestDeliveredForDelegation = 23,
RequestReturnedAfterDelegation = 24,
RequestQueuedForIO = 25,
RequestDeliveredForIO = 26,
Http3StreamStart = 27,
Http3HeaderDecodeStart = 28,
Http3HeaderDecodeEnd = 29,
Max = 30,
};
pub const HttpRequestTimingTypeConnectionStart = HTTP_REQUEST_TIMING_TYPE.ConnectionStart;
pub const HttpRequestTimingTypeDataStart = HTTP_REQUEST_TIMING_TYPE.DataStart;
pub const HttpRequestTimingTypeTlsCertificateLoadStart = HTTP_REQUEST_TIMING_TYPE.TlsCertificateLoadStart;
pub const HttpRequestTimingTypeTlsCertificateLoadEnd = HTTP_REQUEST_TIMING_TYPE.TlsCertificateLoadEnd;
pub const HttpRequestTimingTypeTlsHandshakeLeg1Start = HTTP_REQUEST_TIMING_TYPE.TlsHandshakeLeg1Start;
pub const HttpRequestTimingTypeTlsHandshakeLeg1End = HTTP_REQUEST_TIMING_TYPE.TlsHandshakeLeg1End;
pub const HttpRequestTimingTypeTlsHandshakeLeg2Start = HTTP_REQUEST_TIMING_TYPE.TlsHandshakeLeg2Start;
pub const HttpRequestTimingTypeTlsHandshakeLeg2End = HTTP_REQUEST_TIMING_TYPE.TlsHandshakeLeg2End;
pub const HttpRequestTimingTypeTlsAttributesQueryStart = HTTP_REQUEST_TIMING_TYPE.TlsAttributesQueryStart;
pub const HttpRequestTimingTypeTlsAttributesQueryEnd = HTTP_REQUEST_TIMING_TYPE.TlsAttributesQueryEnd;
pub const HttpRequestTimingTypeTlsClientCertQueryStart = HTTP_REQUEST_TIMING_TYPE.TlsClientCertQueryStart;
pub const HttpRequestTimingTypeTlsClientCertQueryEnd = HTTP_REQUEST_TIMING_TYPE.TlsClientCertQueryEnd;
pub const HttpRequestTimingTypeHttp2StreamStart = HTTP_REQUEST_TIMING_TYPE.Http2StreamStart;
pub const HttpRequestTimingTypeHttp2HeaderDecodeStart = HTTP_REQUEST_TIMING_TYPE.Http2HeaderDecodeStart;
pub const HttpRequestTimingTypeHttp2HeaderDecodeEnd = HTTP_REQUEST_TIMING_TYPE.Http2HeaderDecodeEnd;
pub const HttpRequestTimingTypeRequestHeaderParseStart = HTTP_REQUEST_TIMING_TYPE.RequestHeaderParseStart;
pub const HttpRequestTimingTypeRequestHeaderParseEnd = HTTP_REQUEST_TIMING_TYPE.RequestHeaderParseEnd;
pub const HttpRequestTimingTypeRequestRoutingStart = HTTP_REQUEST_TIMING_TYPE.RequestRoutingStart;
pub const HttpRequestTimingTypeRequestRoutingEnd = HTTP_REQUEST_TIMING_TYPE.RequestRoutingEnd;
pub const HttpRequestTimingTypeRequestQueuedForInspection = HTTP_REQUEST_TIMING_TYPE.RequestQueuedForInspection;
pub const HttpRequestTimingTypeRequestDeliveredForInspection = HTTP_REQUEST_TIMING_TYPE.RequestDeliveredForInspection;
pub const HttpRequestTimingTypeRequestReturnedAfterInspection = HTTP_REQUEST_TIMING_TYPE.RequestReturnedAfterInspection;
pub const HttpRequestTimingTypeRequestQueuedForDelegation = HTTP_REQUEST_TIMING_TYPE.RequestQueuedForDelegation;
pub const HttpRequestTimingTypeRequestDeliveredForDelegation = HTTP_REQUEST_TIMING_TYPE.RequestDeliveredForDelegation;
pub const HttpRequestTimingTypeRequestReturnedAfterDelegation = HTTP_REQUEST_TIMING_TYPE.RequestReturnedAfterDelegation;
pub const HttpRequestTimingTypeRequestQueuedForIO = HTTP_REQUEST_TIMING_TYPE.RequestQueuedForIO;
pub const HttpRequestTimingTypeRequestDeliveredForIO = HTTP_REQUEST_TIMING_TYPE.RequestDeliveredForIO;
pub const HttpRequestTimingTypeHttp3StreamStart = HTTP_REQUEST_TIMING_TYPE.Http3StreamStart;
pub const HttpRequestTimingTypeHttp3HeaderDecodeStart = HTTP_REQUEST_TIMING_TYPE.Http3HeaderDecodeStart;
pub const HttpRequestTimingTypeHttp3HeaderDecodeEnd = HTTP_REQUEST_TIMING_TYPE.Http3HeaderDecodeEnd;
pub const HttpRequestTimingTypeMax = HTTP_REQUEST_TIMING_TYPE.Max;
pub const HTTP_REQUEST_TIMING_INFO = extern struct {
RequestTimingCount: u32,
RequestTiming: [30]u64,
};
pub const HTTP_REQUEST_INFO_TYPE = enum(i32) {
Auth = 0,
ChannelBind = 1,
SslProtocol = 2,
SslTokenBindingDraft = 3,
SslTokenBinding = 4,
RequestTiming = 5,
TcpInfoV0 = 6,
RequestSizing = 7,
QuicStats = 8,
TcpInfoV1 = 9,
};
pub const HttpRequestInfoTypeAuth = HTTP_REQUEST_INFO_TYPE.Auth;
pub const HttpRequestInfoTypeChannelBind = HTTP_REQUEST_INFO_TYPE.ChannelBind;
pub const HttpRequestInfoTypeSslProtocol = HTTP_REQUEST_INFO_TYPE.SslProtocol;
pub const HttpRequestInfoTypeSslTokenBindingDraft = HTTP_REQUEST_INFO_TYPE.SslTokenBindingDraft;
pub const HttpRequestInfoTypeSslTokenBinding = HTTP_REQUEST_INFO_TYPE.SslTokenBinding;
pub const HttpRequestInfoTypeRequestTiming = HTTP_REQUEST_INFO_TYPE.RequestTiming;
pub const HttpRequestInfoTypeTcpInfoV0 = HTTP_REQUEST_INFO_TYPE.TcpInfoV0;
pub const HttpRequestInfoTypeRequestSizing = HTTP_REQUEST_INFO_TYPE.RequestSizing;
pub const HttpRequestInfoTypeQuicStats = HTTP_REQUEST_INFO_TYPE.QuicStats;
pub const HttpRequestInfoTypeTcpInfoV1 = HTTP_REQUEST_INFO_TYPE.TcpInfoV1;
pub const HTTP_REQUEST_INFO = extern struct {
InfoType: HTTP_REQUEST_INFO_TYPE,
InfoLength: u32,
pInfo: ?*anyopaque,
};
pub const HTTP_REQUEST_AUTH_INFO = extern struct {
AuthStatus: HTTP_AUTH_STATUS,
SecStatus: i32,
Flags: u32,
AuthType: HTTP_REQUEST_AUTH_TYPE,
AccessToken: ?HANDLE,
ContextAttributes: u32,
PackedContextLength: u32,
PackedContextType: u32,
PackedContext: ?*anyopaque,
MutualAuthDataLength: u32,
pMutualAuthData: ?[*]u8,
PackageNameLength: u16,
pPackageName: ?PWSTR,
};
pub const HTTP_REQUEST_V1 = extern struct {
Flags: u32,
ConnectionId: u64,
RequestId: u64,
UrlContext: u64,
Version: HTTP_VERSION,
Verb: HTTP_VERB,
UnknownVerbLength: u16,
RawUrlLength: u16,
pUnknownVerb: ?[*:0]const u8,
pRawUrl: ?[*:0]const u8,
CookedUrl: HTTP_COOKED_URL,
Address: HTTP_TRANSPORT_ADDRESS,
Headers: HTTP_REQUEST_HEADERS,
BytesReceived: u64,
EntityChunkCount: u16,
pEntityChunks: ?*HTTP_DATA_CHUNK,
RawConnectionId: u64,
pSslInfo: ?*HTTP_SSL_INFO,
};
pub const HTTP_REQUEST_V2 = extern struct {
__AnonymousBase_http_L1861_C35: HTTP_REQUEST_V1,
RequestInfoCount: u16,
pRequestInfo: ?*HTTP_REQUEST_INFO,
};
pub const HTTP_RESPONSE_V1 = extern struct {
Flags: u32,
Version: HTTP_VERSION,
StatusCode: u16,
ReasonLength: u16,
pReason: ?[*:0]const u8,
Headers: HTTP_RESPONSE_HEADERS,
EntityChunkCount: u16,
pEntityChunks: ?*HTTP_DATA_CHUNK,
};
pub const HTTP_RESPONSE_INFO_TYPE = enum(i32) {
MultipleKnownHeaders = 0,
AuthenticationProperty = 1,
QoSProperty = 2,
ChannelBind = 3,
};
pub const HttpResponseInfoTypeMultipleKnownHeaders = HTTP_RESPONSE_INFO_TYPE.MultipleKnownHeaders;
pub const HttpResponseInfoTypeAuthenticationProperty = HTTP_RESPONSE_INFO_TYPE.AuthenticationProperty;
pub const HttpResponseInfoTypeQoSProperty = HTTP_RESPONSE_INFO_TYPE.QoSProperty;
pub const HttpResponseInfoTypeChannelBind = HTTP_RESPONSE_INFO_TYPE.ChannelBind;
pub const HTTP_RESPONSE_INFO = extern struct {
Type: HTTP_RESPONSE_INFO_TYPE,
Length: u32,
pInfo: ?*anyopaque,
};
pub const HTTP_MULTIPLE_KNOWN_HEADERS = extern struct {
HeaderId: HTTP_HEADER_ID,
Flags: u32,
KnownHeaderCount: u16,
KnownHeaders: ?*HTTP_KNOWN_HEADER,
};
pub const HTTP_RESPONSE_V2 = extern struct {
__AnonymousBase_http_L2050_C36: HTTP_RESPONSE_V1,
ResponseInfoCount: u16,
pResponseInfo: ?*HTTP_RESPONSE_INFO,
};
pub const HTTPAPI_VERSION = extern struct {
HttpApiMajorVersion: u16,
HttpApiMinorVersion: u16,
};
pub const HTTP_CACHE_POLICY_TYPE = enum(i32) {
Nocache = 0,
UserInvalidates = 1,
TimeToLive = 2,
Maximum = 3,
};
pub const HttpCachePolicyNocache = HTTP_CACHE_POLICY_TYPE.Nocache;
pub const HttpCachePolicyUserInvalidates = HTTP_CACHE_POLICY_TYPE.UserInvalidates;
pub const HttpCachePolicyTimeToLive = HTTP_CACHE_POLICY_TYPE.TimeToLive;
pub const HttpCachePolicyMaximum = HTTP_CACHE_POLICY_TYPE.Maximum;
pub const HTTP_CACHE_POLICY = extern struct {
Policy: HTTP_CACHE_POLICY_TYPE,
SecondsToLive: u32,
};
pub const HTTP_SERVICE_CONFIG_ID = enum(i32) {
IPListenList = 0,
SSLCertInfo = 1,
UrlAclInfo = 2,
Timeout = 3,
Cache = 4,
SslSniCertInfo = 5,
SslCcsCertInfo = 6,
Setting = 7,
SslCertInfoEx = 8,
SslSniCertInfoEx = 9,
SslCcsCertInfoEx = 10,
SslScopedCcsCertInfo = 11,
SslScopedCcsCertInfoEx = 12,
Max = 13,
};
pub const HttpServiceConfigIPListenList = HTTP_SERVICE_CONFIG_ID.IPListenList;
pub const HttpServiceConfigSSLCertInfo = HTTP_SERVICE_CONFIG_ID.SSLCertInfo;
pub const HttpServiceConfigUrlAclInfo = HTTP_SERVICE_CONFIG_ID.UrlAclInfo;
pub const HttpServiceConfigTimeout = HTTP_SERVICE_CONFIG_ID.Timeout;
pub const HttpServiceConfigCache = HTTP_SERVICE_CONFIG_ID.Cache;
pub const HttpServiceConfigSslSniCertInfo = HTTP_SERVICE_CONFIG_ID.SslSniCertInfo;
pub const HttpServiceConfigSslCcsCertInfo = HTTP_SERVICE_CONFIG_ID.SslCcsCertInfo;
pub const HttpServiceConfigSetting = HTTP_SERVICE_CONFIG_ID.Setting;
pub const HttpServiceConfigSslCertInfoEx = HTTP_SERVICE_CONFIG_ID.SslCertInfoEx;
pub const HttpServiceConfigSslSniCertInfoEx = HTTP_SERVICE_CONFIG_ID.SslSniCertInfoEx;
pub const HttpServiceConfigSslCcsCertInfoEx = HTTP_SERVICE_CONFIG_ID.SslCcsCertInfoEx;
pub const HttpServiceConfigSslScopedCcsCertInfo = HTTP_SERVICE_CONFIG_ID.SslScopedCcsCertInfo;
pub const HttpServiceConfigSslScopedCcsCertInfoEx = HTTP_SERVICE_CONFIG_ID.SslScopedCcsCertInfoEx;
pub const HttpServiceConfigMax = HTTP_SERVICE_CONFIG_ID.Max;
pub const HTTP_SERVICE_CONFIG_QUERY_TYPE = enum(i32) {
Exact = 0,
Next = 1,
Max = 2,
};
pub const HttpServiceConfigQueryExact = HTTP_SERVICE_CONFIG_QUERY_TYPE.Exact;
pub const HttpServiceConfigQueryNext = HTTP_SERVICE_CONFIG_QUERY_TYPE.Next;
pub const HttpServiceConfigQueryMax = HTTP_SERVICE_CONFIG_QUERY_TYPE.Max;
pub const HTTP_SERVICE_CONFIG_SSL_KEY = extern struct {
pIpPort: ?*SOCKADDR,
};
pub const HTTP_SERVICE_CONFIG_SSL_KEY_EX = extern struct {
IpPort: SOCKADDR_STORAGE,
};
pub const HTTP_SERVICE_CONFIG_SSL_SNI_KEY = extern struct {
IpPort: SOCKADDR_STORAGE,
Host: ?PWSTR,
};
pub const HTTP_SERVICE_CONFIG_SSL_CCS_KEY = extern struct {
LocalAddress: SOCKADDR_STORAGE,
};
pub const HTTP_SERVICE_CONFIG_SSL_PARAM = extern struct {
SslHashLength: u32,
pSslHash: ?*anyopaque,
AppId: Guid,
pSslCertStoreName: ?PWSTR,
DefaultCertCheckMode: u32,
DefaultRevocationFreshnessTime: u32,
DefaultRevocationUrlRetrievalTimeout: u32,
pDefaultSslCtlIdentifier: ?PWSTR,
pDefaultSslCtlStoreName: ?PWSTR,
DefaultFlags: u32,
};
pub const HTTP_SSL_SERVICE_CONFIG_EX_PARAM_TYPE = enum(i32) {
Http2Window = 0,
Http2SettingsLimits = 1,
HttpPerformance = 2,
TlsRestrictions = 3,
ErrorHeaders = 4,
TlsSessionTicketKeys = 5,
Max = 6,
};
pub const ExParamTypeHttp2Window = HTTP_SSL_SERVICE_CONFIG_EX_PARAM_TYPE.Http2Window;
pub const ExParamTypeHttp2SettingsLimits = HTTP_SSL_SERVICE_CONFIG_EX_PARAM_TYPE.Http2SettingsLimits;
pub const ExParamTypeHttpPerformance = HTTP_SSL_SERVICE_CONFIG_EX_PARAM_TYPE.HttpPerformance;
pub const ExParamTypeTlsRestrictions = HTTP_SSL_SERVICE_CONFIG_EX_PARAM_TYPE.TlsRestrictions;
pub const ExParamTypeErrorHeaders = HTTP_SSL_SERVICE_CONFIG_EX_PARAM_TYPE.ErrorHeaders;
pub const ExParamTypeTlsSessionTicketKeys = HTTP_SSL_SERVICE_CONFIG_EX_PARAM_TYPE.TlsSessionTicketKeys;
pub const ExParamTypeMax = HTTP_SSL_SERVICE_CONFIG_EX_PARAM_TYPE.Max;
pub const HTTP2_WINDOW_SIZE_PARAM = extern struct {
Http2ReceiveWindowSize: u32,
};
pub const HTTP2_SETTINGS_LIMITS_PARAM = extern struct {
Http2MaxSettingsPerFrame: u32,
Http2MaxSettingsPerMinute: u32,
};
pub const HTTP_PERFORMANCE_PARAM_TYPE = enum(i32) {
SendBufferingFlags = 0,
AggressiveICW = 1,
MaxSendBufferSize = 2,
MaxConcurrentClientStreams = 3,
MaxReceiveBufferSize = 4,
DecryptOnSspiThread = 5,
Max = 6,
};
pub const PerformanceParamSendBufferingFlags = HTTP_PERFORMANCE_PARAM_TYPE.SendBufferingFlags;
pub const PerformanceParamAggressiveICW = HTTP_PERFORMANCE_PARAM_TYPE.AggressiveICW;
pub const PerformanceParamMaxSendBufferSize = HTTP_PERFORMANCE_PARAM_TYPE.MaxSendBufferSize;
pub const PerformanceParamMaxConcurrentClientStreams = HTTP_PERFORMANCE_PARAM_TYPE.MaxConcurrentClientStreams;
pub const PerformanceParamMaxReceiveBufferSize = HTTP_PERFORMANCE_PARAM_TYPE.MaxReceiveBufferSize;
pub const PerformanceParamDecryptOnSspiThread = HTTP_PERFORMANCE_PARAM_TYPE.DecryptOnSspiThread;
pub const PerformanceParamMax = HTTP_PERFORMANCE_PARAM_TYPE.Max;
pub const HTTP_PERFORMANCE_PARAM = extern struct {
Type: HTTP_PERFORMANCE_PARAM_TYPE,
BufferSize: u32,
Buffer: ?*anyopaque,
};
pub const HTTP_TLS_RESTRICTIONS_PARAM = extern struct {
RestrictionCount: u32,
TlsRestrictions: ?*anyopaque,
};
pub const HTTP_ERROR_HEADERS_PARAM = extern struct {
StatusCode: u16,
HeaderCount: u16,
Headers: ?*HTTP_UNKNOWN_HEADER,
};
pub const HTTP_TLS_SESSION_TICKET_KEYS_PARAM = extern struct {
SessionTicketKeyCount: u32,
SessionTicketKeys: ?*anyopaque,
};
pub const HTTP_SERVICE_CONFIG_SSL_PARAM_EX = extern struct {
ParamType: HTTP_SSL_SERVICE_CONFIG_EX_PARAM_TYPE,
Flags: u64,
Anonymous: extern union {
Http2WindowSizeParam: HTTP2_WINDOW_SIZE_PARAM,
Http2SettingsLimitsParam: HTTP2_SETTINGS_LIMITS_PARAM,
HttpPerformanceParam: HTTP_PERFORMANCE_PARAM,
HttpTlsRestrictionsParam: HTTP_TLS_RESTRICTIONS_PARAM,
HttpErrorHeadersParam: HTTP_ERROR_HEADERS_PARAM,
HttpTlsSessionTicketKeysParam: HTTP_TLS_SESSION_TICKET_KEYS_PARAM,
},
};
pub const HTTP_SERVICE_CONFIG_SSL_SET = extern struct {
KeyDesc: HTTP_SERVICE_CONFIG_SSL_KEY,
ParamDesc: HTTP_SERVICE_CONFIG_SSL_PARAM,
};
pub const HTTP_SERVICE_CONFIG_SSL_SNI_SET = extern struct {
KeyDesc: HTTP_SERVICE_CONFIG_SSL_SNI_KEY,
ParamDesc: HTTP_SERVICE_CONFIG_SSL_PARAM,
};
pub const HTTP_SERVICE_CONFIG_SSL_CCS_SET = extern struct {
KeyDesc: HTTP_SERVICE_CONFIG_SSL_CCS_KEY,
ParamDesc: HTTP_SERVICE_CONFIG_SSL_PARAM,
};
pub const HTTP_SERVICE_CONFIG_SSL_SET_EX = extern struct {
KeyDesc: HTTP_SERVICE_CONFIG_SSL_KEY_EX,
ParamDesc: HTTP_SERVICE_CONFIG_SSL_PARAM_EX,
};
pub const HTTP_SERVICE_CONFIG_SSL_SNI_SET_EX = extern struct {
KeyDesc: HTTP_SERVICE_CONFIG_SSL_SNI_KEY,
ParamDesc: HTTP_SERVICE_CONFIG_SSL_PARAM_EX,
};
pub const HTTP_SERVICE_CONFIG_SSL_CCS_SET_EX = extern struct {
KeyDesc: HTTP_SERVICE_CONFIG_SSL_CCS_KEY,
ParamDesc: HTTP_SERVICE_CONFIG_SSL_PARAM_EX,
};
pub const HTTP_SERVICE_CONFIG_SSL_QUERY = extern struct {
QueryDesc: HTTP_SERVICE_CONFIG_QUERY_TYPE,
KeyDesc: HTTP_SERVICE_CONFIG_SSL_KEY,
dwToken: u32,
};
pub const HTTP_SERVICE_CONFIG_SSL_SNI_QUERY = extern struct {
QueryDesc: HTTP_SERVICE_CONFIG_QUERY_TYPE,
KeyDesc: HTTP_SERVICE_CONFIG_SSL_SNI_KEY,
dwToken: u32,
};
pub const HTTP_SERVICE_CONFIG_SSL_CCS_QUERY = extern struct {
QueryDesc: HTTP_SERVICE_CONFIG_QUERY_TYPE,
KeyDesc: HTTP_SERVICE_CONFIG_SSL_CCS_KEY,
dwToken: u32,
};
pub const HTTP_SERVICE_CONFIG_SSL_QUERY_EX = extern struct {
QueryDesc: HTTP_SERVICE_CONFIG_QUERY_TYPE,
KeyDesc: HTTP_SERVICE_CONFIG_SSL_KEY_EX,
dwToken: u32,
ParamType: HTTP_SSL_SERVICE_CONFIG_EX_PARAM_TYPE,
};
pub const HTTP_SERVICE_CONFIG_SSL_SNI_QUERY_EX = extern struct {
QueryDesc: HTTP_SERVICE_CONFIG_QUERY_TYPE,
KeyDesc: HTTP_SERVICE_CONFIG_SSL_SNI_KEY,
dwToken: u32,
ParamType: HTTP_SSL_SERVICE_CONFIG_EX_PARAM_TYPE,
};
pub const HTTP_SERVICE_CONFIG_SSL_CCS_QUERY_EX = extern struct {
QueryDesc: HTTP_SERVICE_CONFIG_QUERY_TYPE,
KeyDesc: HTTP_SERVICE_CONFIG_SSL_CCS_KEY,
dwToken: u32,
ParamType: HTTP_SSL_SERVICE_CONFIG_EX_PARAM_TYPE,
};
pub const HTTP_SERVICE_CONFIG_IP_LISTEN_PARAM = extern struct {
AddrLength: u16,
pAddress: ?*SOCKADDR,
};
pub const HTTP_SERVICE_CONFIG_IP_LISTEN_QUERY = extern struct {
AddrCount: u32,
AddrList: [1]SOCKADDR_STORAGE,
};
pub const HTTP_SERVICE_CONFIG_URLACL_KEY = extern struct {
pUrlPrefix: ?PWSTR,
};
pub const HTTP_SERVICE_CONFIG_URLACL_PARAM = extern struct {
pStringSecurityDescriptor: ?PWSTR,
};
pub const HTTP_SERVICE_CONFIG_URLACL_SET = extern struct {
KeyDesc: HTTP_SERVICE_CONFIG_URLACL_KEY,
ParamDesc: HTTP_SERVICE_CONFIG_URLACL_PARAM,
};
pub const HTTP_SERVICE_CONFIG_URLACL_QUERY = extern struct {
QueryDesc: HTTP_SERVICE_CONFIG_QUERY_TYPE,
KeyDesc: HTTP_SERVICE_CONFIG_URLACL_KEY,
dwToken: u32,
};
pub const HTTP_SERVICE_CONFIG_CACHE_KEY = enum(i32) {
MaxCacheResponseSize = 0,
CacheRangeChunkSize = 1,
};
pub const MaxCacheResponseSize = HTTP_SERVICE_CONFIG_CACHE_KEY.MaxCacheResponseSize;
pub const CacheRangeChunkSize = HTTP_SERVICE_CONFIG_CACHE_KEY.CacheRangeChunkSize;
pub const HTTP_SERVICE_CONFIG_CACHE_SET = extern struct {
KeyDesc: HTTP_SERVICE_CONFIG_CACHE_KEY,
ParamDesc: u32,
};
pub const HTTP_REQUEST_PROPERTY = enum(i32) {
Isb = 0,
TcpInfoV0 = 1,
QuicStats = 2,
TcpInfoV1 = 3,
Sni = 4,
StreamError = 5,
WskApiTimings = 6,
QuicApiTimings = 7,
};
pub const HttpRequestPropertyIsb = HTTP_REQUEST_PROPERTY.Isb;
pub const HttpRequestPropertyTcpInfoV0 = HTTP_REQUEST_PROPERTY.TcpInfoV0;
pub const HttpRequestPropertyQuicStats = HTTP_REQUEST_PROPERTY.QuicStats;
pub const HttpRequestPropertyTcpInfoV1 = HTTP_REQUEST_PROPERTY.TcpInfoV1;
pub const HttpRequestPropertySni = HTTP_REQUEST_PROPERTY.Sni;
pub const HttpRequestPropertyStreamError = HTTP_REQUEST_PROPERTY.StreamError;
pub const HttpRequestPropertyWskApiTimings = HTTP_REQUEST_PROPERTY.WskApiTimings;
pub const HttpRequestPropertyQuicApiTimings = HTTP_REQUEST_PROPERTY.QuicApiTimings;
pub const HTTP_QUERY_REQUEST_QUALIFIER_TCP = extern struct {
Freshness: u64,
};
pub const HTTP_QUERY_REQUEST_QUALIFIER_QUIC = extern struct {
Freshness: u64,
};
pub const HTTP_REQUEST_PROPERTY_SNI = extern struct {
Hostname: [256]u16,
Flags: u32,
};
pub const HTTP_REQUEST_PROPERTY_STREAM_ERROR = extern struct {
ErrorCode: u32,
};
pub const HTTP_WSK_API_TIMINGS = extern struct {
ConnectCount: u64,
ConnectSum: u64,
DisconnectCount: u64,
DisconnectSum: u64,
SendCount: u64,
SendSum: u64,
ReceiveCount: u64,
ReceiveSum: u64,
ReleaseCount: u64,
ReleaseSum: u64,
ControlSocketCount: u64,
ControlSocketSum: u64,
};
pub const HTTP_QUIC_STREAM_API_TIMINGS = extern struct {
OpenCount: u64,
OpenSum: u64,
CloseCount: u64,
CloseSum: u64,
StartCount: u64,
StartSum: u64,
ShutdownCount: u64,
ShutdownSum: u64,
SendCount: u64,
SendSum: u64,
ReceiveSetEnabledCount: u64,
ReceiveSetEnabledSum: u64,
GetParamCount: u64,
GetParamSum: u64,
SetParamCount: u64,
SetParamSum: u64,
SetCallbackHandlerCount: u64,
SetCallbackHandlerSum: u64,
};
pub const HTTP_QUIC_CONNECTION_API_TIMINGS = extern struct {
OpenTime: u64,
CloseTime: u64,
StartTime: u64,
ShutdownTime: u64,
SecConfigCreateTime: u64,
SecConfigDeleteTime: u64,
GetParamCount: u64,
GetParamSum: u64,
SetParamCount: u64,
SetParamSum: u64,
SetCallbackHandlerCount: u64,
SetCallbackHandlerSum: u64,
ControlStreamTimings: HTTP_QUIC_STREAM_API_TIMINGS,
};
pub const HTTP_QUIC_API_TIMINGS = extern struct {
ConnectionTimings: HTTP_QUIC_CONNECTION_API_TIMINGS,
StreamTimings: HTTP_QUIC_STREAM_API_TIMINGS,
};
pub const HTTP_FEATURE_ID = enum(i32) {
Unknown = 0,
ResponseTrailers = 1,
ApiTimings = 2,
DelegateEx = 3,
Http3 = 4,
max = -1,
};
pub const HttpFeatureUnknown = HTTP_FEATURE_ID.Unknown;
pub const HttpFeatureResponseTrailers = HTTP_FEATURE_ID.ResponseTrailers;
pub const HttpFeatureApiTimings = HTTP_FEATURE_ID.ApiTimings;
pub const HttpFeatureDelegateEx = HTTP_FEATURE_ID.DelegateEx;
pub const HttpFeatureHttp3 = HTTP_FEATURE_ID.Http3;
pub const HttpFeaturemax = HTTP_FEATURE_ID.max;
//--------------------------------------------------------------------------------
// Section: Functions (43)
//--------------------------------------------------------------------------------
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "HTTPAPI" fn HttpInitialize(
Version: HTTPAPI_VERSION,
Flags: HTTP_INITIALIZE,
pReserved: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "HTTPAPI" fn HttpTerminate(
Flags: HTTP_INITIALIZE,
pReserved: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "HTTPAPI" fn HttpCreateHttpHandle(
RequestQueueHandle: ?*?HANDLE,
Reserved: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "HTTPAPI" fn HttpCreateRequestQueue(
Version: HTTPAPI_VERSION,
Name: ?[*:0]const u16,
SecurityAttributes: ?*SECURITY_ATTRIBUTES,
Flags: u32,
RequestQueueHandle: ?*?HANDLE,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "HTTPAPI" fn HttpCloseRequestQueue(
RequestQueueHandle: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "HTTPAPI" fn HttpSetRequestQueueProperty(
RequestQueueHandle: ?HANDLE,
Property: HTTP_SERVER_PROPERTY,
// TODO: what to do with BytesParamIndex 3?
PropertyInformation: ?*anyopaque,
PropertyInformationLength: u32,
Reserved1: u32,
Reserved2: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "HTTPAPI" fn HttpQueryRequestQueueProperty(
RequestQueueHandle: ?HANDLE,
Property: HTTP_SERVER_PROPERTY,
// TODO: what to do with BytesParamIndex 3?
PropertyInformation: ?*anyopaque,
PropertyInformationLength: u32,
Reserved1: u32,
ReturnLength: ?*u32,
Reserved2: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "HTTPAPI" fn HttpSetRequestProperty(
RequestQueueHandle: ?HANDLE,
Id: u64,
PropertyId: HTTP_REQUEST_PROPERTY,
// TODO: what to do with BytesParamIndex 4?
Input: ?*anyopaque,
InputPropertySize: u32,
Overlapped: ?*OVERLAPPED,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "HTTPAPI" fn HttpShutdownRequestQueue(
RequestQueueHandle: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "HTTPAPI" fn HttpReceiveClientCertificate(
RequestQueueHandle: ?HANDLE,
ConnectionId: u64,
Flags: u32,
// TODO: what to do with BytesParamIndex 4?
SslClientCertInfo: ?*HTTP_SSL_CLIENT_CERT_INFO,
SslClientCertInfoSize: u32,
BytesReceived: ?*u32,
Overlapped: ?*OVERLAPPED,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "HTTPAPI" fn HttpCreateServerSession(
Version: HTTPAPI_VERSION,
ServerSessionId: ?*u64,
Reserved: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "HTTPAPI" fn HttpCloseServerSession(
ServerSessionId: u64,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "HTTPAPI" fn HttpQueryServerSessionProperty(
ServerSessionId: u64,
Property: HTTP_SERVER_PROPERTY,
// TODO: what to do with BytesParamIndex 3?
PropertyInformation: ?*anyopaque,
PropertyInformationLength: u32,
ReturnLength: ?*u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "HTTPAPI" fn HttpSetServerSessionProperty(
ServerSessionId: u64,
Property: HTTP_SERVER_PROPERTY,
// TODO: what to do with BytesParamIndex 3?
PropertyInformation: ?*anyopaque,
PropertyInformationLength: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "HTTPAPI" fn HttpAddUrl(
RequestQueueHandle: ?HANDLE,
FullyQualifiedUrl: ?[*:0]const u16,
Reserved: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "HTTPAPI" fn HttpRemoveUrl(
RequestQueueHandle: ?HANDLE,
FullyQualifiedUrl: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "HTTPAPI" fn HttpCreateUrlGroup(
ServerSessionId: u64,
pUrlGroupId: ?*u64,
Reserved: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "HTTPAPI" fn HttpCloseUrlGroup(
UrlGroupId: u64,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "HTTPAPI" fn HttpAddUrlToUrlGroup(
UrlGroupId: u64,
pFullyQualifiedUrl: ?[*:0]const u16,
UrlContext: u64,
Reserved: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "HTTPAPI" fn HttpRemoveUrlFromUrlGroup(
UrlGroupId: u64,
pFullyQualifiedUrl: ?[*:0]const u16,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "HTTPAPI" fn HttpSetUrlGroupProperty(
UrlGroupId: u64,
Property: HTTP_SERVER_PROPERTY,
// TODO: what to do with BytesParamIndex 3?
PropertyInformation: ?*anyopaque,
PropertyInformationLength: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "HTTPAPI" fn HttpQueryUrlGroupProperty(
UrlGroupId: u64,
Property: HTTP_SERVER_PROPERTY,
// TODO: what to do with BytesParamIndex 3?
PropertyInformation: ?*anyopaque,
PropertyInformationLength: u32,
ReturnLength: ?*u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows8.0'
pub extern "HTTPAPI" fn HttpPrepareUrl(
Reserved: ?*anyopaque,
Flags: u32,
Url: ?[*:0]const u16,
PreparedUrl: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "HTTPAPI" fn HttpReceiveHttpRequest(
RequestQueueHandle: ?HANDLE,
RequestId: u64,
Flags: HTTP_RECEIVE_HTTP_REQUEST_FLAGS,
// TODO: what to do with BytesParamIndex 4?
RequestBuffer: ?*HTTP_REQUEST_V2,
RequestBufferLength: u32,
BytesReturned: ?*u32,
Overlapped: ?*OVERLAPPED,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "HTTPAPI" fn HttpReceiveRequestEntityBody(
RequestQueueHandle: ?HANDLE,
RequestId: u64,
Flags: u32,
// TODO: what to do with BytesParamIndex 4?
EntityBuffer: ?*anyopaque,
EntityBufferLength: u32,
BytesReturned: ?*u32,
Overlapped: ?*OVERLAPPED,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "HTTPAPI" fn HttpSendHttpResponse(
RequestQueueHandle: ?HANDLE,
RequestId: u64,
Flags: u32,
HttpResponse: ?*HTTP_RESPONSE_V2,
CachePolicy: ?*HTTP_CACHE_POLICY,
BytesSent: ?*u32,
Reserved1: ?*anyopaque,
Reserved2: u32,
Overlapped: ?*OVERLAPPED,
LogData: ?*HTTP_LOG_DATA,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "HTTPAPI" fn HttpSendResponseEntityBody(
RequestQueueHandle: ?HANDLE,
RequestId: u64,
Flags: u32,
EntityChunkCount: u16,
EntityChunks: ?[*]HTTP_DATA_CHUNK,
BytesSent: ?*u32,
Reserved1: ?*anyopaque,
Reserved2: u32,
Overlapped: ?*OVERLAPPED,
LogData: ?*HTTP_LOG_DATA,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows10.0.10240'
pub extern "HTTPAPI" fn HttpDeclarePush(
RequestQueueHandle: ?HANDLE,
RequestId: u64,
Verb: HTTP_VERB,
Path: ?[*:0]const u16,
Query: ?[*:0]const u8,
Headers: ?*HTTP_REQUEST_HEADERS,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "HTTPAPI" fn HttpWaitForDisconnect(
RequestQueueHandle: ?HANDLE,
ConnectionId: u64,
Overlapped: ?*OVERLAPPED,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "HTTPAPI" fn HttpWaitForDisconnectEx(
RequestQueueHandle: ?HANDLE,
ConnectionId: u64,
Reserved: u32,
Overlapped: ?*OVERLAPPED,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "HTTPAPI" fn HttpCancelHttpRequest(
RequestQueueHandle: ?HANDLE,
RequestId: u64,
Overlapped: ?*OVERLAPPED,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "HTTPAPI" fn HttpWaitForDemandStart(
RequestQueueHandle: ?HANDLE,
Overlapped: ?*OVERLAPPED,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "HTTPAPI" fn HttpIsFeatureSupported(
FeatureId: HTTP_FEATURE_ID,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "HTTPAPI" fn HttpDelegateRequestEx(
RequestQueueHandle: ?HANDLE,
DelegateQueueHandle: ?HANDLE,
RequestId: u64,
DelegateUrlGroupId: u64,
PropertyInfoSetSize: u32,
PropertyInfoSet: ?*HTTP_DELEGATE_REQUEST_PROPERTY_INFO,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "HTTPAPI" fn HttpFindUrlGroupId(
FullyQualifiedUrl: ?[*:0]const u16,
RequestQueueHandle: ?HANDLE,
UrlGroupId: ?*u64,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "HTTPAPI" fn HttpFlushResponseCache(
RequestQueueHandle: ?HANDLE,
UrlPrefix: ?[*:0]const u16,
Flags: u32,
Overlapped: ?*OVERLAPPED,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "HTTPAPI" fn HttpAddFragmentToCache(
RequestQueueHandle: ?HANDLE,
UrlPrefix: ?[*:0]const u16,
DataChunk: ?*HTTP_DATA_CHUNK,
CachePolicy: ?*HTTP_CACHE_POLICY,
Overlapped: ?*OVERLAPPED,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "HTTPAPI" fn HttpReadFragmentFromCache(
RequestQueueHandle: ?HANDLE,
UrlPrefix: ?[*:0]const u16,
ByteRange: ?*HTTP_BYTE_RANGE,
// TODO: what to do with BytesParamIndex 4?
Buffer: ?*anyopaque,
BufferLength: u32,
BytesRead: ?*u32,
Overlapped: ?*OVERLAPPED,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "HTTPAPI" fn HttpSetServiceConfiguration(
ServiceHandle: ?HANDLE,
ConfigId: HTTP_SERVICE_CONFIG_ID,
// TODO: what to do with BytesParamIndex 3?
pConfigInformation: ?*anyopaque,
ConfigInformationLength: u32,
pOverlapped: ?*OVERLAPPED,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows10.0.15063'
pub extern "HTTPAPI" fn HttpUpdateServiceConfiguration(
Handle: ?HANDLE,
ConfigId: HTTP_SERVICE_CONFIG_ID,
// TODO: what to do with BytesParamIndex 3?
ConfigInfo: ?*anyopaque,
ConfigInfoLength: u32,
Overlapped: ?*OVERLAPPED,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "HTTPAPI" fn HttpDeleteServiceConfiguration(
ServiceHandle: ?HANDLE,
ConfigId: HTTP_SERVICE_CONFIG_ID,
// TODO: what to do with BytesParamIndex 3?
pConfigInformation: ?*anyopaque,
ConfigInformationLength: u32,
pOverlapped: ?*OVERLAPPED,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "HTTPAPI" fn HttpQueryServiceConfiguration(
ServiceHandle: ?HANDLE,
ConfigId: HTTP_SERVICE_CONFIG_ID,
// TODO: what to do with BytesParamIndex 3?
pInput: ?*anyopaque,
InputLength: u32,
// TODO: what to do with BytesParamIndex 5?
pOutput: ?*anyopaque,
OutputLength: u32,
pReturnLength: ?*u32,
pOverlapped: ?*OVERLAPPED,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "HTTPAPI" fn HttpGetExtension(
Version: HTTPAPI_VERSION,
Extension: u32,
Buffer: ?*anyopaque,
BufferSize: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (1)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../zig.zig").unicode_mode) {
.ansi => struct {
pub const HTTP_SERVICE_BINDING_ = thismodule.HTTP_SERVICE_BINDING_A;
},
.wide => struct {
pub const HTTP_SERVICE_BINDING_ = thismodule.HTTP_SERVICE_BINDING_W;
},
.unspecified => if (@import("builtin").is_test) struct {
pub const HTTP_SERVICE_BINDING_ = *opaque{};
} else struct {
pub const HTTP_SERVICE_BINDING_ = @compileError("'HTTP_SERVICE_BINDING_' requires that UNICODE be set to true or false in the root module");
},
};
//--------------------------------------------------------------------------------
// Section: Imports (12)
//--------------------------------------------------------------------------------
const Guid = @import("../zig.zig").Guid;
const BOOL = @import("../foundation.zig").BOOL;
const BOOLEAN = @import("../foundation.zig").BOOLEAN;
const HANDLE = @import("../foundation.zig").HANDLE;
const OVERLAPPED = @import("../system/io.zig").OVERLAPPED;
const PSTR = @import("../foundation.zig").PSTR;
const PWSTR = @import("../foundation.zig").PWSTR;
const SECURITY_ATTRIBUTES = @import("../security.zig").SECURITY_ATTRIBUTES;
const SECURITY_DESCRIPTOR = @import("../security.zig").SECURITY_DESCRIPTOR;
const SOCKADDR = @import("../networking/win_sock.zig").SOCKADDR;
const SOCKADDR_STORAGE = @import("../networking/win_sock.zig").SOCKADDR_STORAGE;
const ULARGE_INTEGER = @import("../foundation.zig").ULARGE_INTEGER;
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/networking/http_server.zig |
const std = @import("std");
const file = std.os.File;
const assert = std.debug.assert;
pub fn main() anyerror!void {
var doubles_count: u64 = 0;
var triples_count: u64 = 0;
var direct_allocator = std.heap.DirectAllocator.init();
defer direct_allocator.deinit();
const allocator = &direct_allocator.allocator;
const input_file = try file.openRead("day2input.txt");
defer input_file.close();
const buf = try allocator.alloc(u8,try input_file.getEndPos());
defer allocator.free(buf);
_ = input_file.inStream().stream.readFull(buf);
var iter = std.mem.split(buf, "\n");
while (iter.next()) |box_id| {
const packed_result = try countDoubleAndTriple(allocator, box_id);
doubles_count += packed_result.double;
triples_count += packed_result.triple;
}
const out = try std.io.getStdOut();
defer out.close();
try out.outStream().stream.print("\nThe checksum is {} * {} = {}",
doubles_count,
triples_count,
doubles_count * triples_count);
}
pub const CountDandT = struct {
double: u8,
triple: u8,
};
fn countDoubleAndTriple(allocator: *std.mem.Allocator, box_id: []const u8) !CountDandT {
var retVal = CountDandT {
.double = 0,
.triple = 0,
};
var countMap = std.AutoHashMap(u8, u8).init(allocator);
defer countMap.deinit();
for (std.mem.trim(u8,box_id," ")) |char| {
if (countMap.get(char)) |item| {
_ = try countMap.put(item.key, item.value + 1);
} else {
_ = try countMap.put(char, 1);
}
}
var iter = countMap.iterator();
while (iter.next()) |kv_pair| {
if (kv_pair.value == 2) {
retVal.double = 1;
} else if (kv_pair.value == 3) {
retVal.triple = 1;
}
}
return retVal;
}
test "count" {
var answer1 = try countDoubleAndTriple(std.debug.global_allocator, "aaabcb");
assert(answer1.double == 1);
assert(answer1.triple == 1);
} | src/day2.zig |
const std = @import("std");
const assert = std.debug.assert;
const heap = @import("../heap.zig");
const virt = @import("./vm.zig");
const notification = @import("./notification.zig");
pub const List = std.SinglyLinkedList(@This());
/// The VM's accumulator register
acc: u8 = 0,
/// The VM's instruction pointer
ip: usize = 0,
/// The program stack
stack: [2048]u8 = [_]u8{0} ** 2048,
/// The Stack Pointer points to the highest currently unused value on the stack
sp: u11 = 0,
/// The task's ID.
id: u32,
/// A list of instructions to execute
program: []const Instruction,
/// Pending Notifications
notifs: std.ArrayList(notification.VMNotif) = std.ArrayList(notification.VMNotif).init(&heap.kpagealloc),
/// Handler addresses for notifications
handlers: [@typeInfo(notification.VMNotifKind).Enum.fields.len]?usize = [_]?usize{null} ** @typeInfo(notification.VMNotifKind).Enum.fields.len,
/// Whether or not the task is doing nothing but waiting for a notification to happen
waiting: bool = false,
pub const Instruction = union(enum) {
/// Don't.
noop: void,
/// Pop an index from the stack and unconditionally jump there.
jump: void,
/// Die.
exit: void,
/// Push the argument onto the stack.
push_const_vec: []const u8,
/// Push the argument onto the stack.
push_const: u8,
/// Push the accumulator onto the stack.
push_acc: void,
/// Pop a value from the stack into the accumulator.
pop: void,
/// Pop an index from the stack and jump there if accumulator is 0,
/// otherwise no-op.
jez: void,
/// Subtract the last value on the stack from the second-to-last value
/// and put it into the accumulator.
sub: void,
/// Add the last and second-to-last value on the stack and put it into
/// the accumulator.
add: void,
/// Let the scheduler know that there's nothing to do right now.
/// Execution will resume after an indeterminate amount of time.
yield: void,
/// Call a non-trivial kernel-provided function. See individual
/// enum members for details.
exec: union(enum) {
/// Pop <arg> bytes from the stack and write them to UART. Do not
/// assume any particular formatting.
log: u11,
/// Set up a specific address in the program to be jumped to in
/// case a specific notification is issued to the VM. The current
/// instruction pointer will be pushed onto the stack. Return using
/// jump.
subscribe: struct { address: usize, kind: notification.VMNotifKind },
/// Set the task's waiting status. Waiting tasks will only be
/// resumed when a notification they have subscribed to
/// is generated, after which set_waiting has to be issued again.
set_waiting: bool,
},
};
pub fn format(t: @This(), comptime fmt: []const u8, options: std.fmt.FormatOptions, out_stream: var) !void {
const val = if (t.sp == 0) -1 else @as(i16, t.stack[t.sp - 1]);
try std.fmt.format(out_stream, "Task(id = {}, ip = {}, sp = {}, acc = {}, [sp-1] = {})", .{ t.id, t.ip, t.sp, t.acc, val });
}
pub fn deinit(self: *@This()) void {
self.notifs.deinit();
self.* = undefined;
}
comptime {
assert(@sizeOf(List.Node) <= heap.page_size); // come on it didn't have to be that big
} | src/interpreter/Frame.zig |
const std = @import("std");
const c = @cImport({
@cInclude("SDL2/SDL.h");
@cInclude("SDL_FontCache.h");
});
const zs = @import("zstack.zig");
const Piece = zs.Piece;
const BitSet = zs.BitSet;
const VirtualKey = zs.input.VirtualKey;
const Key = zs.input.Key;
const Measure = enum {
BlockSide,
WellX,
WellY,
WellH,
WellW,
HoldX,
HoldY,
HoldW,
HoldH,
PreviewX,
PreviewY,
PreviewW,
PreviewH,
StatsX,
StatsY,
StatsW,
StatsH,
};
const stack_color = zs.piece.Color{
.r = 140,
.g = 140,
.b = 140,
.a = 255,
};
fn len(w: Window, e: zs.Engine, comptime measure: Measure) usize {
return switch (measure) {
.BlockSide => @floatToInt(usize, @intToFloat(f64, w.width) * 0.02625),
.WellX => @floatToInt(usize, @intToFloat(f64, w.width) * 0.13125),
.WellY => @floatToInt(usize, @intToFloat(f64, w.height) * 0.15),
.WellW => e.options.well_width * len(w, e, .BlockSide),
.WellH => (e.options.well_height - e.options.well_hidden) * len(w, e, .BlockSide),
.HoldX => len(w, e, .WellX) - @floatToInt(usize, (5 * @intToFloat(f64, len(w, e, .BlockSide)))),
.HoldY => len(w, e, .WellY),
.HoldW => 4 * len(w, e, .BlockSide),
.HoldH => 4 * len(w, e, .BlockSide),
.PreviewX => len(w, e, .WellX) + len(w, e, .WellW) + 10,
.PreviewY => len(w, e, .WellY),
.PreviewW => 4 * len(w, e, .BlockSide),
.PreviewH => len(w, e, .WellH),
.StatsX => len(w, e, .PreviewX) + len(w, e, .previewW) + 20,
.StatsY => len(w, e, .WellY),
.StatsW => @floatToInt(usize, @intToFloat(f64, w.width) * 0.125),
.StatsH => len(w, e, .WellH),
};
}
fn SDL_Check(result: c_int) !void {
if (result < 0) {
std.debug.warn("SDL error: {c}\n", c.SDL_GetError());
return error.SDLError;
}
}
fn calcFontSize(w: c_int) c_int {
return @divTrunc(w, 40);
}
pub const Options = struct {
width: c_int = 640,
height: c_int = 480,
debug: bool = true,
};
pub const Window = struct {
window: ?*c.SDL_Window,
renderer: ?*c.SDL_Renderer,
font: ?*c.FC_Font,
keymap: zs.input.KeyBindings,
width: c_int,
height: c_int,
debug: bool,
pub fn init(options: Options, keymap: zs.input.KeyBindings) !Window {
var w = Window{
.window = null,
.renderer = null,
.font = null,
.keymap = keymap,
.width = options.width,
.height = options.height,
.debug = options.debug,
};
try SDL_Check(c.SDL_Init(c.SDL_INIT_VIDEO | c.SDL_INIT_AUDIO));
errdefer c.SDL_Quit();
try SDL_Check(c.SDL_CreateWindowAndRenderer(
w.width,
w.height,
c.SDL_WINDOW_SHOWN | c.SDL_WINDOW_ALLOW_HIGHDPI,
&w.window,
&w.renderer,
));
errdefer c.SDL_DestroyWindow(w.window);
w.font = c.FC_CreateFont();
errdefer c.FC_FreeFont(w.font);
// http://pelulamu.net/unscii/, Public Domain.
// The stripped variant uses pyftsubset to omit all but the ascii range `--gids=0-128`.
// TODO: Not the font, tried with open sans. Not embedFile, happens with raw data used in
// c version.
const ttf_font = @embedFile("unscii-16.subset.ttf");
const rwops = c.SDL_RWFromConstMem(&ttf_font[0], ttf_font.len);
if (c.FC_LoadFont_RW(
w.font,
w.renderer,
rwops,
1,
@intCast(c_uint, calcFontSize(w.width)),
c.FC_MakeColor(200, 200, 200, 255),
c.TTF_STYLE_NORMAL,
) == 0) {
return error.SDLFontCacheError;
}
c.SDL_SetWindowResizable(w.window, c.SDL_bool.SDL_FALSE);
c.SDL_SetWindowTitle(w.window, c"zstack");
try SDL_Check(c.SDL_SetRenderDrawColor(w.renderer, 0, 0, 0, 255));
try SDL_Check(c.SDL_RenderClear(w.renderer));
c.SDL_RenderPresent(w.renderer);
return w;
}
pub fn deinit(w: Window) void {
c.FC_FreeFont(w.font);
c.SDL_DestroyWindow(w.window);
c.SDL_Quit();
}
fn mapKeyToSDLKey(key: Key) c_int {
return switch (key) {
.space => c_int(c.SDLK_SPACE),
.enter => c.SDLK_RETURN,
.tab => c.SDLK_TAB,
.right => c.SDLK_RIGHT,
.left => c.SDLK_LEFT,
.down => c.SDLK_DOWN,
.up => c.SDLK_UP,
.rshift => c.SDLK_RSHIFT,
.lshift => c.SDLK_LSHIFT,
.capslock => c.SDLK_CAPSLOCK,
.comma => c.SDLK_COMMA,
.period => c.SDLK_PERIOD,
.slash => c.SDLK_SLASH,
.semicolon => c.SDLK_SEMICOLON,
.apostrophe => c.SDLK_QUOTE,
.lbracket => c.SDLK_LEFTBRACKET,
.rbracket => c.SDLK_RIGHTBRACKET,
.backslash => c.SDLK_BACKSLASH,
.a => c.SDLK_a,
.b => c.SDLK_b,
.c => c.SDLK_c,
.d => c.SDLK_d,
.e => c.SDLK_e,
.f => c.SDLK_f,
.g => c.SDLK_g,
.h => c.SDLK_h,
.i => c.SDLK_i,
.j => c.SDLK_j,
.k => c.SDLK_k,
.l => c.SDLK_l,
.m => c.SDLK_m,
.n => c.SDLK_n,
.o => c.SDLK_o,
.p => c.SDLK_p,
.q => c.SDLK_q,
.r => c.SDLK_r,
.s => c.SDLK_s,
.t => c.SDLK_t,
.u => c.SDLK_u,
.v => c.SDLK_v,
.w => c.SDLK_w,
.x => c.SDLK_x,
.y => c.SDLK_y,
.z => c.SDLK_z,
};
}
pub fn readKeys(w: *Window) BitSet(VirtualKey) {
c.SDL_PumpEvents();
const keystate = c.SDL_GetKeyboardState(null);
var keys = BitSet(VirtualKey).init();
for (w.keymap.entries()) |km, i| {
const from = mapKeyToSDLKey(km);
if (keystate[@intCast(usize, @enumToInt(c.SDL_GetScancodeFromKey(from)))] != 0) {
keys.set(VirtualKey.fromIndex(i));
}
}
// Handle window exit request
if (c.SDL_PeepEvents(null, 0, @intToEnum(c.SDL_eventaction, c.SDL_PEEKEVENT), c.SDL_QUIT, c.SDL_QUIT) > 0) {
keys.set(.Quit);
}
return keys;
}
fn renderWell(w: Window, e: zs.Engine) !void {
const border = c.SDL_Rect{
.x = @intCast(c_int, len(w, e, .WellX)) - 1,
.y = @intCast(c_int, len(w, e, .WellY)) - 1,
.w = @intCast(c_int, len(w, e, .WellW)) + 2,
.h = @intCast(c_int, len(w, e, .WellH)) + 2,
};
try SDL_Check(c.SDL_SetRenderDrawColor(w.renderer, 255, 255, 255, 255));
try SDL_Check(c.SDL_RenderDrawRect(w.renderer, &border));
var block = c.SDL_Rect{
.x = undefined,
.y = undefined,
.w = @intCast(c_int, len(w, e, .BlockSide)) + 1,
.h = @intCast(c_int, len(w, e, .BlockSide)) + 1,
};
var y = e.options.well_hidden;
while (y < e.options.well_height) : (y += 1) {
block.y = @intCast(c_int, len(w, e, .WellY) + (y - e.options.well_hidden) * len(w, e, .BlockSide));
var x: usize = 0;
while (x < e.options.well_width) : (x += 1) {
block.x = @intCast(c_int, len(w, e, .WellX) + x * len(w, e, .BlockSide));
if (e.well[y][x] != null) {
try SDL_Check(c.SDL_SetRenderDrawColor(w.renderer, stack_color.r, stack_color.g, stack_color.b, stack_color.a));
try SDL_Check(c.SDL_RenderFillRect(w.renderer, &block));
}
}
}
}
fn renderHoldPiece(w: Window, e: zs.Engine) !void {
var block = c.SDL_Rect{
.x = undefined,
.y = undefined,
.w = @intCast(c_int, len(w, e, .BlockSide)) + 1,
.h = @intCast(c_int, len(w, e, .BlockSide)) + 1,
};
const id = e.hold_piece orelse return;
const color = id.color();
try SDL_Check(c.SDL_SetRenderDrawColor(w.renderer, color.r, color.g, color.b, color.a));
const bx_off = if (id != .O) len(w, e, .BlockSide) / 2 else 0;
const by_off = if (id == .I) len(w, e, .BlockSide) / 2 else 0;
const blocks = e.rotation_system.blocks(id, .R0);
for (blocks) |b| {
block.x = @intCast(c_int, bx_off + len(w, e, .HoldX) + b.x * len(w, e, .BlockSide));
block.y = @intCast(c_int, by_off + len(w, e, .HoldY) + b.y * len(w, e, .BlockSide));
try SDL_Check(c.SDL_RenderFillRect(w.renderer, &block));
}
}
fn renderCurrentPieceAndShadow(w: Window, e: zs.Engine) !void {
var block = c.SDL_Rect{
.x = undefined,
.y = undefined,
.w = @intCast(c_int, len(w, e, .BlockSide)) + 1,
.h = @intCast(c_int, len(w, e, .BlockSide)) + 1,
};
const p = e.piece orelse return;
const color = p.id.color();
const blocks = e.rotation_system.blocks(p.id, p.theta);
// Ghost
if (e.options.show_ghost) {
for (blocks) |b| {
const x = @intCast(u8, p.x + @intCast(i8, b.x));
const y = @intCast(u8, p.y_hard_drop) + b.y - e.options.well_hidden;
// Filter blocks greater than visible field height
if (b.y < 0) {
continue;
}
block.x = @intCast(c_int, len(w, e, .WellX) + x * len(w, e, .BlockSide));
block.y = @intCast(c_int, len(w, e, .WellY) + y * len(w, e, .BlockSide));
// Dim ghost color
try SDL_Check(c.SDL_SetRenderDrawColor(w.renderer, color.r / 2, color.g / 2, color.b / 2, color.a / 2));
try SDL_Check(c.SDL_RenderFillRect(w.renderer, &block));
}
}
// Piece
for (blocks) |b| {
const x = @intCast(u8, p.x + @intCast(i8, b.x));
// TODO: fix non-zero well_hidden
const y = p.uy() + b.y - e.options.well_hidden;
if (y < 0) {
continue;
}
block.x = @intCast(c_int, len(w, e, .WellX) + x * len(w, e, .BlockSide));
block.y = @intCast(c_int, len(w, e, .WellY) + y * len(w, e, .BlockSide));
// Slowly dim block to stack color if locking.
var nc = color;
if (e.options.lock_delay_ms != 0) {
const lock_ratio = @intToFloat(f32, p.lock_timer) / @intToFloat(f32, zs.ticks(e.options.lock_delay_ms));
if (lock_ratio != 0) {
inline for (([_][]const u8{ "r", "g", "b" })[0..]) |entry| {
if (@field(nc, entry) < @field(stack_color, entry)) {
@field(nc, entry) += @floatToInt(u8, @intToFloat(f32, @field(stack_color, entry) - @field(nc, entry)) * lock_ratio);
} else {
@field(nc, entry) -= @floatToInt(u8, @intToFloat(f32, @field(nc, entry) - @field(stack_color, entry)) * lock_ratio);
}
}
}
}
if (e.state == .Are and e.options.are_delay_ms != 0) {
const lock_ratio = @intToFloat(f32, e.are_counter) / @intToFloat(f32, zs.ticks(e.options.are_delay_ms));
if (lock_ratio != 0) {
inline for (([_][]const u8{ "r", "g", "b" })[0..]) |entry| {
if (@field(nc, entry) < @field(stack_color, entry)) {
@field(nc, entry) += @floatToInt(u8, @intToFloat(f32, @field(stack_color, entry) - @field(nc, entry)) * lock_ratio);
} else {
@field(nc, entry) -= @floatToInt(u8, @intToFloat(f32, @field(nc, entry) - @field(stack_color, entry)) * lock_ratio);
}
}
}
}
try SDL_Check(c.SDL_SetRenderDrawColor(w.renderer, nc.r, nc.g, nc.b, nc.a));
try SDL_Check(c.SDL_RenderFillRect(w.renderer, &block));
}
}
fn renderPreviewPieces(w: Window, e: zs.Engine) !void {
var block = c.SDL_Rect{
.x = undefined,
.y = undefined,
.w = @intCast(c_int, len(w, e, .BlockSide) + 1),
.h = @intCast(c_int, len(w, e, .BlockSide) + 1),
};
var i: usize = 0;
while (i < e.options.preview_piece_count) : (i += 1) {
const id = e.preview_pieces.peek(i);
const color = id.color();
const blocks = e.rotation_system.blocks(id, .R0);
try SDL_Check(c.SDL_SetRenderDrawColor(w.renderer, color.r, color.g, color.b, color.a));
const by = len(w, e, .PreviewY) + (4 * i) * len(w, e, .BlockSide);
for (blocks) |b| {
block.y = @intCast(c_int, by + len(w, e, .BlockSide) * b.y);
block.x = @intCast(c_int, len(w, e, .PreviewX) + len(w, e, .BlockSide) * b.x);
switch (id) {
.I => block.y -= @intCast(c_int, len(w, e, .BlockSide) / 2),
.O => block.x += @intCast(c_int, len(w, e, .BlockSide) / 2),
else => {},
}
try SDL_Check(c.SDL_RenderFillRect(w.renderer, &block));
}
}
}
fn renderStatistics(w: Window, e: zs.Engine) !void {
try renderString(w, 10, 10, "Here is a string: {}", usize(54));
}
fn renderString(w: Window, x: usize, y: usize, comptime fmt: []const u8, args: ...) !void {
var buffer: [128]u8 = undefined;
const line = try std.fmt.bufPrint(buffer[0..], fmt ++ "\x00", args);
// TODO: Error here, check line is null terminated?
const rect = c.FC_Draw(w.font, w.renderer, 10, 50, c"hello"); //line[0..].ptr);
if (rect.x == 0 and rect.y == 0 and rect.w == 0 and rect.h == 0) {
return error.SDLFontCacheDrawError;
}
}
fn renderFieldString(w: Window, comptime fmt: []const u8, args: ...) void {
var buffer: [128]u8 = undefined;
const line = std.fmt.bufPrint(buffer[0..], fmt ++ "\x00", args);
const width = c.FC_GetWidth(w.font, line);
const x = len(w, e, .WellX) + len(w, e, .WellW) / 2 - width / 2;
const y = len(w, e, .WellY) + len(w, e, .WellH) / 2;
c.FC_Draw(w.font, w.renderer, x, y, line[0..]);
}
fn renderDebug(w: Window, e: zs.Engine) void {
const ux = w.width * 0.7;
const uy = 1;
const elapsed_time = SDL_Ticks();
const render_fps = elapsed_time / (1000 * e.total_ticks / zs.ticks_per_draw);
const logic_fps = elapsed_time / (1000 * e.total_ticks);
const line_skip_y = c.FC_GetLineHeight(w.font);
const pos_y = 0;
w.renderString(ux, uy + pos_y * line_skip.uy(), "Render FPS: {.5}", render_fps);
pos_y += 1;
w.renderString(ux, uy + pos_y * line_skip.uy(), "Logic GPS: {.5}", logic_fps);
pos_y += 1;
w.renderString(ux, uy + pos_y * line_skip.uy(), "Block:");
pos_y += 1;
w.renderString(ux, uy + pos_y * line_skip.uy(), " x: {}", engine.piece_x);
pos_y += 1;
w.renderString(ux, uy + pos_y * line_skip.uy(), " y: {}", engine.piece_y);
pos_y += 1;
w.renderString(ux, uy + pos_y * line_skip.uy(), " theta: {}", engine.piece_theta);
pos_y += 1;
w.renderString(ux, uy + pos_y * line_skip.uy(), " low-y: {}", engine.y_hard_drop);
pos_y += 1;
w.renderString(ux, uy + pos_y * line_skip.uy(), "Field:");
pos_y += 1;
w.renderString(ux, uy + pos_y * line_skip.uy(), " gravity: {.3}", engine.gravity);
pos_y += 1;
}
pub fn render(w: Window, e: zs.Engine) !void {
try SDL_Check(c.SDL_SetRenderDrawColor(w.renderer, 0, 0, 0, 255));
try SDL_Check(c.SDL_RenderClear(w.renderer));
try w.renderWell(e);
try w.renderHoldPiece(e);
try w.renderCurrentPieceAndShadow(e);
try w.renderPreviewPieces(e);
//try w.renderStatistics(e);
//const rect = c.FC_Draw(w.font, w.renderer, 10, 10, c"hello");
//switch (e.State) {
// .Excellent => w.renderFieldString("EXCELLENT"),
// .Ready => w.renderFieldString("READY"),
// .Go => w.renderFieldString("GO"),
// else => {},
//}
//if (w.debug) {
// w.renderDebug();
//}
c.SDL_RenderPresent(w.renderer);
}
}; | src/window_sdl.zig |
const xcb = @import("../xcb.zig");
pub const id = xcb.Extension{ .name = "XInputExtension", .global_id = 0 };
pub const EventClass = u32;
pub const KeyCode = u8;
pub const DeviceId = u16;
pub const FP1616 = i32;
/// @brief FP3232
pub const FP3232 = struct {
@"integral": i32,
@"frac": u32,
};
/// @brief GetExtensionVersioncookie
pub const GetExtensionVersioncookie = struct {
sequence: c_uint,
};
/// @brief GetExtensionVersionRequest
pub const GetExtensionVersionRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 1,
@"length": u16,
@"name_len": u16,
@"pad0": [2]u8,
@"name": []const u8,
};
/// @brief GetExtensionVersionReply
pub const GetExtensionVersionReply = struct {
@"response_type": u8,
@"xi_reply_type": u8,
@"sequence": u16,
@"length": u32,
@"server_major": u16,
@"server_minor": u16,
@"present": u8,
@"pad0": [19]u8,
};
pub const DeviceUse = extern enum(c_uint) {
@"IsXPointer" = 0,
@"IsXKeyboard" = 1,
@"IsXExtensionDevice" = 2,
@"IsXExtensionKeyboard" = 3,
@"IsXExtensionPointer" = 4,
};
pub const InputClass = extern enum(c_uint) {
@"Key" = 0,
@"Button" = 1,
@"Valuator" = 2,
@"Feedback" = 3,
@"Proximity" = 4,
@"Focus" = 5,
@"Other" = 6,
};
pub const ValuatorMode = extern enum(c_uint) {
@"Relative" = 0,
@"Absolute" = 1,
};
/// @brief DeviceInfo
pub const DeviceInfo = struct {
@"device_type": xcb.ATOM,
@"device_id": u8,
@"num_class_info": u8,
@"device_use": u8,
@"pad0": u8,
};
/// @brief KeyInfo
pub const KeyInfo = struct {
@"class_id": u8,
@"len": u8,
@"min_keycode": xcb.input.KeyCode,
@"max_keycode": xcb.input.KeyCode,
@"num_keys": u16,
@"pad0": [2]u8,
};
/// @brief ButtonInfo
pub const ButtonInfo = struct {
@"class_id": u8,
@"len": u8,
@"num_buttons": u16,
};
/// @brief AxisInfo
pub const AxisInfo = struct {
@"resolution": u32,
@"minimum": i32,
@"maximum": i32,
};
/// @brief ValuatorInfo
pub const ValuatorInfo = struct {
@"class_id": u8,
@"len": u8,
@"axes_len": u8,
@"mode": u8,
@"motion_size": u32,
@"axes": []xcb.input.AxisInfo,
};
/// @brief InputInfo
pub const InputInfo = struct {
@"class_id": u8,
@"len": u8,
};
/// @brief DeviceName
pub const DeviceName = struct {
@"len": u8,
@"string": []u8,
};
/// @brief ListInputDevicescookie
pub const ListInputDevicescookie = struct {
sequence: c_uint,
};
/// @brief ListInputDevicesRequest
pub const ListInputDevicesRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 2,
@"length": u16,
};
/// @brief ListInputDevicesReply
pub const ListInputDevicesReply = struct {
@"response_type": u8,
@"xi_reply_type": u8,
@"sequence": u16,
@"length": u32,
@"devices_len": u8,
@"pad0": [23]u8,
@"devices": []xcb.input.DeviceInfo,
@"infos": []xcb.input.InputInfo,
@"names": []xcb.STR,
};
/// @brief InputClassInfo
pub const InputClassInfo = struct {
@"class_id": u8,
@"event_type_base": u8,
};
/// @brief OpenDevicecookie
pub const OpenDevicecookie = struct {
sequence: c_uint,
};
/// @brief OpenDeviceRequest
pub const OpenDeviceRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 3,
@"length": u16,
@"device_id": u8,
@"pad0": [3]u8,
};
/// @brief OpenDeviceReply
pub const OpenDeviceReply = struct {
@"response_type": u8,
@"xi_reply_type": u8,
@"sequence": u16,
@"length": u32,
@"num_classes": u8,
@"pad0": [23]u8,
@"class_info": []xcb.input.InputClassInfo,
};
/// @brief CloseDeviceRequest
pub const CloseDeviceRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 4,
@"length": u16,
@"device_id": u8,
@"pad0": [3]u8,
};
/// @brief SetDeviceModecookie
pub const SetDeviceModecookie = struct {
sequence: c_uint,
};
/// @brief SetDeviceModeRequest
pub const SetDeviceModeRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 5,
@"length": u16,
@"device_id": u8,
@"mode": u8,
@"pad0": [2]u8,
};
/// @brief SetDeviceModeReply
pub const SetDeviceModeReply = struct {
@"response_type": u8,
@"xi_reply_type": u8,
@"sequence": u16,
@"length": u32,
@"status": u8,
@"pad0": [23]u8,
};
/// @brief SelectExtensionEventRequest
pub const SelectExtensionEventRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 6,
@"length": u16,
@"window": xcb.WINDOW,
@"num_classes": u16,
@"pad0": [2]u8,
@"classes": []const xcb.input.EventClass,
};
/// @brief GetSelectedExtensionEventscookie
pub const GetSelectedExtensionEventscookie = struct {
sequence: c_uint,
};
/// @brief GetSelectedExtensionEventsRequest
pub const GetSelectedExtensionEventsRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 7,
@"length": u16,
@"window": xcb.WINDOW,
};
/// @brief GetSelectedExtensionEventsReply
pub const GetSelectedExtensionEventsReply = struct {
@"response_type": u8,
@"xi_reply_type": u8,
@"sequence": u16,
@"length": u32,
@"num_this_classes": u16,
@"num_all_classes": u16,
@"pad0": [20]u8,
@"this_classes": []xcb.input.EventClass,
@"all_classes": []xcb.input.EventClass,
};
pub const PropagateMode = extern enum(c_uint) {
@"AddToList" = 0,
@"DeleteFromList" = 1,
};
/// @brief ChangeDeviceDontPropagateListRequest
pub const ChangeDeviceDontPropagateListRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 8,
@"length": u16,
@"window": xcb.WINDOW,
@"num_classes": u16,
@"mode": u8,
@"pad0": u8,
@"classes": []const xcb.input.EventClass,
};
/// @brief GetDeviceDontPropagateListcookie
pub const GetDeviceDontPropagateListcookie = struct {
sequence: c_uint,
};
/// @brief GetDeviceDontPropagateListRequest
pub const GetDeviceDontPropagateListRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 9,
@"length": u16,
@"window": xcb.WINDOW,
};
/// @brief GetDeviceDontPropagateListReply
pub const GetDeviceDontPropagateListReply = struct {
@"response_type": u8,
@"xi_reply_type": u8,
@"sequence": u16,
@"length": u32,
@"num_classes": u16,
@"pad0": [22]u8,
@"classes": []xcb.input.EventClass,
};
/// @brief DeviceTimeCoord
pub const DeviceTimeCoord = struct {
@"time": xcb.TIMESTAMP,
@"axisvalues": []i32,
};
/// @brief GetDeviceMotionEventscookie
pub const GetDeviceMotionEventscookie = struct {
sequence: c_uint,
};
/// @brief GetDeviceMotionEventsRequest
pub const GetDeviceMotionEventsRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 10,
@"length": u16,
@"start": xcb.TIMESTAMP,
@"stop": xcb.TIMESTAMP,
@"device_id": u8,
@"pad0": [3]u8,
};
/// @brief GetDeviceMotionEventsReply
pub const GetDeviceMotionEventsReply = struct {
@"response_type": u8,
@"xi_reply_type": u8,
@"sequence": u16,
@"length": u32,
@"num_events": u32,
@"num_axes": u8,
@"device_mode": u8,
@"pad0": [18]u8,
@"events": []xcb.input.DeviceTimeCoord,
};
/// @brief ChangeKeyboardDevicecookie
pub const ChangeKeyboardDevicecookie = struct {
sequence: c_uint,
};
/// @brief ChangeKeyboardDeviceRequest
pub const ChangeKeyboardDeviceRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 11,
@"length": u16,
@"device_id": u8,
@"pad0": [3]u8,
};
/// @brief ChangeKeyboardDeviceReply
pub const ChangeKeyboardDeviceReply = struct {
@"response_type": u8,
@"xi_reply_type": u8,
@"sequence": u16,
@"length": u32,
@"status": u8,
@"pad0": [23]u8,
};
/// @brief ChangePointerDevicecookie
pub const ChangePointerDevicecookie = struct {
sequence: c_uint,
};
/// @brief ChangePointerDeviceRequest
pub const ChangePointerDeviceRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 12,
@"length": u16,
@"x_axis": u8,
@"y_axis": u8,
@"device_id": u8,
@"pad0": u8,
};
/// @brief ChangePointerDeviceReply
pub const ChangePointerDeviceReply = struct {
@"response_type": u8,
@"xi_reply_type": u8,
@"sequence": u16,
@"length": u32,
@"status": u8,
@"pad0": [23]u8,
};
/// @brief GrabDevicecookie
pub const GrabDevicecookie = struct {
sequence: c_uint,
};
/// @brief GrabDeviceRequest
pub const GrabDeviceRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 13,
@"length": u16,
@"grab_window": xcb.WINDOW,
@"time": xcb.TIMESTAMP,
@"num_classes": u16,
@"this_device_mode": u8,
@"other_device_mode": u8,
@"owner_events": u8,
@"device_id": u8,
@"pad0": [2]u8,
@"classes": []const xcb.input.EventClass,
};
/// @brief GrabDeviceReply
pub const GrabDeviceReply = struct {
@"response_type": u8,
@"xi_reply_type": u8,
@"sequence": u16,
@"length": u32,
@"status": u8,
@"pad0": [23]u8,
};
/// @brief UngrabDeviceRequest
pub const UngrabDeviceRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 14,
@"length": u16,
@"time": xcb.TIMESTAMP,
@"device_id": u8,
@"pad0": [3]u8,
};
pub const ModifierDevice = extern enum(c_uint) {
@"UseXKeyboard" = 255,
};
/// @brief GrabDeviceKeyRequest
pub const GrabDeviceKeyRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 15,
@"length": u16,
@"grab_window": xcb.WINDOW,
@"num_classes": u16,
@"modifiers": u16,
@"modifier_device": u8,
@"grabbed_device": u8,
@"key": u8,
@"this_device_mode": u8,
@"other_device_mode": u8,
@"owner_events": u8,
@"pad0": [2]u8,
@"classes": []const xcb.input.EventClass,
};
/// @brief UngrabDeviceKeyRequest
pub const UngrabDeviceKeyRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 16,
@"length": u16,
@"grabWindow": xcb.WINDOW,
@"modifiers": u16,
@"modifier_device": u8,
@"key": u8,
@"grabbed_device": u8,
};
/// @brief GrabDeviceButtonRequest
pub const GrabDeviceButtonRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 17,
@"length": u16,
@"grab_window": xcb.WINDOW,
@"grabbed_device": u8,
@"modifier_device": u8,
@"num_classes": u16,
@"modifiers": u16,
@"this_device_mode": u8,
@"other_device_mode": u8,
@"button": u8,
@"owner_events": u8,
@"pad0": [2]u8,
@"classes": []const xcb.input.EventClass,
};
/// @brief UngrabDeviceButtonRequest
pub const UngrabDeviceButtonRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 18,
@"length": u16,
@"grab_window": xcb.WINDOW,
@"modifiers": u16,
@"modifier_device": u8,
@"button": u8,
@"grabbed_device": u8,
@"pad0": [3]u8,
};
pub const DeviceInputMode = extern enum(c_uint) {
@"AsyncThisDevice" = 0,
@"SyncThisDevice" = 1,
@"ReplayThisDevice" = 2,
@"AsyncOtherDevices" = 3,
@"AsyncAll" = 4,
@"SyncAll" = 5,
};
/// @brief AllowDeviceEventsRequest
pub const AllowDeviceEventsRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 19,
@"length": u16,
@"time": xcb.TIMESTAMP,
@"mode": u8,
@"device_id": u8,
@"pad0": [2]u8,
};
/// @brief GetDeviceFocuscookie
pub const GetDeviceFocuscookie = struct {
sequence: c_uint,
};
/// @brief GetDeviceFocusRequest
pub const GetDeviceFocusRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 20,
@"length": u16,
@"device_id": u8,
@"pad0": [3]u8,
};
/// @brief GetDeviceFocusReply
pub const GetDeviceFocusReply = struct {
@"response_type": u8,
@"xi_reply_type": u8,
@"sequence": u16,
@"length": u32,
@"focus": xcb.WINDOW,
@"time": xcb.TIMESTAMP,
@"revert_to": u8,
@"pad0": [15]u8,
};
/// @brief SetDeviceFocusRequest
pub const SetDeviceFocusRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 21,
@"length": u16,
@"focus": xcb.WINDOW,
@"time": xcb.TIMESTAMP,
@"revert_to": u8,
@"device_id": u8,
@"pad0": [2]u8,
};
pub const FeedbackClass = extern enum(c_uint) {
@"Keyboard" = 0,
@"Pointer" = 1,
@"String" = 2,
@"Integer" = 3,
@"Led" = 4,
@"Bell" = 5,
};
/// @brief KbdFeedbackState
pub const KbdFeedbackState = struct {
@"class_id": u8,
@"feedback_id": u8,
@"len": u16,
@"pitch": u16,
@"duration": u16,
@"led_mask": u32,
@"led_values": u32,
@"global_auto_repeat": u8,
@"click": u8,
@"percent": u8,
@"pad0": u8,
@"auto_repeats": [32]u8,
};
/// @brief PtrFeedbackState
pub const PtrFeedbackState = struct {
@"class_id": u8,
@"feedback_id": u8,
@"len": u16,
@"pad0": [2]u8,
@"accel_num": u16,
@"accel_denom": u16,
@"threshold": u16,
};
/// @brief IntegerFeedbackState
pub const IntegerFeedbackState = struct {
@"class_id": u8,
@"feedback_id": u8,
@"len": u16,
@"resolution": u32,
@"min_value": i32,
@"max_value": i32,
};
/// @brief StringFeedbackState
pub const StringFeedbackState = struct {
@"class_id": u8,
@"feedback_id": u8,
@"len": u16,
@"max_symbols": u16,
@"num_keysyms": u16,
@"keysyms": []xcb.KEYSYM,
};
/// @brief BellFeedbackState
pub const BellFeedbackState = struct {
@"class_id": u8,
@"feedback_id": u8,
@"len": u16,
@"percent": u8,
@"pad0": [3]u8,
@"pitch": u16,
@"duration": u16,
};
/// @brief LedFeedbackState
pub const LedFeedbackState = struct {
@"class_id": u8,
@"feedback_id": u8,
@"len": u16,
@"led_mask": u32,
@"led_values": u32,
};
/// @brief FeedbackState
pub const FeedbackState = struct {
@"class_id": u8,
@"feedback_id": u8,
@"len": u16,
};
/// @brief GetFeedbackControlcookie
pub const GetFeedbackControlcookie = struct {
sequence: c_uint,
};
/// @brief GetFeedbackControlRequest
pub const GetFeedbackControlRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 22,
@"length": u16,
@"device_id": u8,
@"pad0": [3]u8,
};
/// @brief GetFeedbackControlReply
pub const GetFeedbackControlReply = struct {
@"response_type": u8,
@"xi_reply_type": u8,
@"sequence": u16,
@"length": u32,
@"num_feedbacks": u16,
@"pad0": [22]u8,
@"feedbacks": []xcb.input.FeedbackState,
};
/// @brief KbdFeedbackCtl
pub const KbdFeedbackCtl = struct {
@"class_id": u8,
@"feedback_id": u8,
@"len": u16,
@"key": xcb.input.KeyCode,
@"auto_repeat_mode": u8,
@"key_click_percent": i8,
@"bell_percent": i8,
@"bell_pitch": i16,
@"bell_duration": i16,
@"led_mask": u32,
@"led_values": u32,
};
/// @brief PtrFeedbackCtl
pub const PtrFeedbackCtl = struct {
@"class_id": u8,
@"feedback_id": u8,
@"len": u16,
@"pad0": [2]u8,
@"num": i16,
@"denom": i16,
@"threshold": i16,
};
/// @brief IntegerFeedbackCtl
pub const IntegerFeedbackCtl = struct {
@"class_id": u8,
@"feedback_id": u8,
@"len": u16,
@"int_to_display": i32,
};
/// @brief StringFeedbackCtl
pub const StringFeedbackCtl = struct {
@"class_id": u8,
@"feedback_id": u8,
@"len": u16,
@"pad0": [2]u8,
@"num_keysyms": u16,
@"keysyms": []xcb.KEYSYM,
};
/// @brief BellFeedbackCtl
pub const BellFeedbackCtl = struct {
@"class_id": u8,
@"feedback_id": u8,
@"len": u16,
@"percent": i8,
@"pad0": [3]u8,
@"pitch": i16,
@"duration": i16,
};
/// @brief LedFeedbackCtl
pub const LedFeedbackCtl = struct {
@"class_id": u8,
@"feedback_id": u8,
@"len": u16,
@"led_mask": u32,
@"led_values": u32,
};
/// @brief FeedbackCtl
pub const FeedbackCtl = struct {
@"class_id": u8,
@"feedback_id": u8,
@"len": u16,
};
pub const ChangeFeedbackControlMask = extern enum(c_uint) {
@"KeyClickPercent" = 1,
@"Percent" = 2,
@"Pitch" = 4,
@"Duration" = 8,
@"Led" = 16,
@"LedMode" = 32,
@"Key" = 64,
@"AutoRepeatMode" = 128,
@"String" = 1,
@"Integer" = 1,
@"AccelNum" = 1,
@"AccelDenom" = 2,
@"Threshold" = 4,
};
/// @brief ChangeFeedbackControlRequest
pub const ChangeFeedbackControlRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 23,
@"length": u16,
@"mask": u32,
@"device_id": u8,
@"feedback_id": u8,
@"pad0": [2]u8,
};
/// @brief GetDeviceKeyMappingcookie
pub const GetDeviceKeyMappingcookie = struct {
sequence: c_uint,
};
/// @brief GetDeviceKeyMappingRequest
pub const GetDeviceKeyMappingRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 24,
@"length": u16,
@"device_id": u8,
@"first_keycode": xcb.input.KeyCode,
@"count": u8,
@"pad0": u8,
};
/// @brief GetDeviceKeyMappingReply
pub const GetDeviceKeyMappingReply = struct {
@"response_type": u8,
@"xi_reply_type": u8,
@"sequence": u16,
@"length": u32,
@"keysyms_per_keycode": u8,
@"pad0": [23]u8,
@"keysyms": []xcb.KEYSYM,
};
/// @brief ChangeDeviceKeyMappingRequest
pub const ChangeDeviceKeyMappingRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 25,
@"length": u16,
@"device_id": u8,
@"first_keycode": xcb.input.KeyCode,
@"keysyms_per_keycode": u8,
@"keycode_count": u8,
@"keysyms": []const xcb.KEYSYM,
};
/// @brief GetDeviceModifierMappingcookie
pub const GetDeviceModifierMappingcookie = struct {
sequence: c_uint,
};
/// @brief GetDeviceModifierMappingRequest
pub const GetDeviceModifierMappingRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 26,
@"length": u16,
@"device_id": u8,
@"pad0": [3]u8,
};
/// @brief GetDeviceModifierMappingReply
pub const GetDeviceModifierMappingReply = struct {
@"response_type": u8,
@"xi_reply_type": u8,
@"sequence": u16,
@"length": u32,
@"keycodes_per_modifier": u8,
@"pad0": [23]u8,
@"keymaps": []u8,
};
/// @brief SetDeviceModifierMappingcookie
pub const SetDeviceModifierMappingcookie = struct {
sequence: c_uint,
};
/// @brief SetDeviceModifierMappingRequest
pub const SetDeviceModifierMappingRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 27,
@"length": u16,
@"device_id": u8,
@"keycodes_per_modifier": u8,
@"pad0": [2]u8,
@"keymaps": []const u8,
};
/// @brief SetDeviceModifierMappingReply
pub const SetDeviceModifierMappingReply = struct {
@"response_type": u8,
@"xi_reply_type": u8,
@"sequence": u16,
@"length": u32,
@"status": u8,
@"pad0": [23]u8,
};
/// @brief GetDeviceButtonMappingcookie
pub const GetDeviceButtonMappingcookie = struct {
sequence: c_uint,
};
/// @brief GetDeviceButtonMappingRequest
pub const GetDeviceButtonMappingRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 28,
@"length": u16,
@"device_id": u8,
@"pad0": [3]u8,
};
/// @brief GetDeviceButtonMappingReply
pub const GetDeviceButtonMappingReply = struct {
@"response_type": u8,
@"xi_reply_type": u8,
@"sequence": u16,
@"length": u32,
@"map_size": u8,
@"pad0": [23]u8,
@"map": []u8,
};
/// @brief SetDeviceButtonMappingcookie
pub const SetDeviceButtonMappingcookie = struct {
sequence: c_uint,
};
/// @brief SetDeviceButtonMappingRequest
pub const SetDeviceButtonMappingRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 29,
@"length": u16,
@"device_id": u8,
@"map_size": u8,
@"pad0": [2]u8,
@"map": []const u8,
};
/// @brief SetDeviceButtonMappingReply
pub const SetDeviceButtonMappingReply = struct {
@"response_type": u8,
@"xi_reply_type": u8,
@"sequence": u16,
@"length": u32,
@"status": u8,
@"pad0": [23]u8,
};
/// @brief KeyState
pub const KeyState = struct {
@"class_id": u8,
@"len": u8,
@"num_keys": u8,
@"pad0": u8,
@"keys": [32]u8,
};
/// @brief ButtonState
pub const ButtonState = struct {
@"class_id": u8,
@"len": u8,
@"num_buttons": u8,
@"pad0": u8,
@"buttons": [32]u8,
};
pub const ValuatorStateModeMask = extern enum(c_uint) {
@"DeviceModeAbsolute" = 1,
@"OutOfProximity" = 2,
};
/// @brief ValuatorState
pub const ValuatorState = struct {
@"class_id": u8,
@"len": u8,
@"num_valuators": u8,
@"mode": u8,
@"valuators": []i32,
};
/// @brief InputState
pub const InputState = struct {
@"class_id": u8,
@"len": u8,
};
/// @brief QueryDeviceStatecookie
pub const QueryDeviceStatecookie = struct {
sequence: c_uint,
};
/// @brief QueryDeviceStateRequest
pub const QueryDeviceStateRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 30,
@"length": u16,
@"device_id": u8,
@"pad0": [3]u8,
};
/// @brief QueryDeviceStateReply
pub const QueryDeviceStateReply = struct {
@"response_type": u8,
@"xi_reply_type": u8,
@"sequence": u16,
@"length": u32,
@"num_classes": u8,
@"pad0": [23]u8,
@"classes": []xcb.input.InputState,
};
/// @brief SendExtensionEventRequest
pub const SendExtensionEventRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 31,
@"length": u16,
@"destination": xcb.WINDOW,
@"device_id": u8,
@"propagate": u8,
@"num_classes": u16,
@"num_events": u8,
@"pad0": [3]u8,
@"events": []const u8,
@"classes": []const xcb.input.EventClass,
};
/// @brief DeviceBellRequest
pub const DeviceBellRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 32,
@"length": u16,
@"device_id": u8,
@"feedback_id": u8,
@"feedback_class": u8,
@"percent": i8,
};
/// @brief SetDeviceValuatorscookie
pub const SetDeviceValuatorscookie = struct {
sequence: c_uint,
};
/// @brief SetDeviceValuatorsRequest
pub const SetDeviceValuatorsRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 33,
@"length": u16,
@"device_id": u8,
@"first_valuator": u8,
@"num_valuators": u8,
@"pad0": u8,
@"valuators": []const i32,
};
/// @brief SetDeviceValuatorsReply
pub const SetDeviceValuatorsReply = struct {
@"response_type": u8,
@"xi_reply_type": u8,
@"sequence": u16,
@"length": u32,
@"status": u8,
@"pad0": [23]u8,
};
pub const DeviceControl = extern enum(c_uint) {
@"resolution" = 1,
@"abs_calib" = 2,
@"core" = 3,
@"enable" = 4,
@"abs_area" = 5,
};
/// @brief DeviceResolutionState
pub const DeviceResolutionState = struct {
@"control_id": u16,
@"len": u16,
@"num_valuators": u32,
@"resolution_values": []u32,
@"resolution_min": []u32,
@"resolution_max": []u32,
};
/// @brief DeviceAbsCalibState
pub const DeviceAbsCalibState = struct {
@"control_id": u16,
@"len": u16,
@"min_x": i32,
@"max_x": i32,
@"min_y": i32,
@"max_y": i32,
@"flip_x": u32,
@"flip_y": u32,
@"rotation": u32,
@"button_threshold": u32,
};
/// @brief DeviceAbsAreaState
pub const DeviceAbsAreaState = struct {
@"control_id": u16,
@"len": u16,
@"offset_x": u32,
@"offset_y": u32,
@"width": u32,
@"height": u32,
@"screen": u32,
@"following": u32,
};
/// @brief DeviceCoreState
pub const DeviceCoreState = struct {
@"control_id": u16,
@"len": u16,
@"status": u8,
@"iscore": u8,
@"pad0": [2]u8,
};
/// @brief DeviceEnableState
pub const DeviceEnableState = struct {
@"control_id": u16,
@"len": u16,
@"enable": u8,
@"pad0": [3]u8,
};
/// @brief DeviceState
pub const DeviceState = struct {
@"control_id": u16,
@"len": u16,
};
/// @brief GetDeviceControlcookie
pub const GetDeviceControlcookie = struct {
sequence: c_uint,
};
/// @brief GetDeviceControlRequest
pub const GetDeviceControlRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 34,
@"length": u16,
@"control_id": u16,
@"device_id": u8,
@"pad0": u8,
};
/// @brief GetDeviceControlReply
pub const GetDeviceControlReply = struct {
@"response_type": u8,
@"xi_reply_type": u8,
@"sequence": u16,
@"length": u32,
@"status": u8,
@"pad0": [23]u8,
};
/// @brief DeviceResolutionCtl
pub const DeviceResolutionCtl = struct {
@"control_id": u16,
@"len": u16,
@"first_valuator": u8,
@"num_valuators": u8,
@"pad0": [2]u8,
@"resolution_values": []u32,
};
/// @brief DeviceAbsCalibCtl
pub const DeviceAbsCalibCtl = struct {
@"control_id": u16,
@"len": u16,
@"min_x": i32,
@"max_x": i32,
@"min_y": i32,
@"max_y": i32,
@"flip_x": u32,
@"flip_y": u32,
@"rotation": u32,
@"button_threshold": u32,
};
/// @brief DeviceAbsAreaCtrl
pub const DeviceAbsAreaCtrl = struct {
@"control_id": u16,
@"len": u16,
@"offset_x": u32,
@"offset_y": u32,
@"width": i32,
@"height": i32,
@"screen": i32,
@"following": u32,
};
/// @brief DeviceCoreCtrl
pub const DeviceCoreCtrl = struct {
@"control_id": u16,
@"len": u16,
@"status": u8,
@"pad0": [3]u8,
};
/// @brief DeviceEnableCtrl
pub const DeviceEnableCtrl = struct {
@"control_id": u16,
@"len": u16,
@"enable": u8,
@"pad0": [3]u8,
};
/// @brief DeviceCtl
pub const DeviceCtl = struct {
@"control_id": u16,
@"len": u16,
};
/// @brief ChangeDeviceControlcookie
pub const ChangeDeviceControlcookie = struct {
sequence: c_uint,
};
/// @brief ChangeDeviceControlRequest
pub const ChangeDeviceControlRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 35,
@"length": u16,
@"control_id": u16,
@"device_id": u8,
@"pad0": u8,
};
/// @brief ChangeDeviceControlReply
pub const ChangeDeviceControlReply = struct {
@"response_type": u8,
@"xi_reply_type": u8,
@"sequence": u16,
@"length": u32,
@"status": u8,
@"pad0": [23]u8,
};
/// @brief ListDevicePropertiescookie
pub const ListDevicePropertiescookie = struct {
sequence: c_uint,
};
/// @brief ListDevicePropertiesRequest
pub const ListDevicePropertiesRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 36,
@"length": u16,
@"device_id": u8,
@"pad0": [3]u8,
};
/// @brief ListDevicePropertiesReply
pub const ListDevicePropertiesReply = struct {
@"response_type": u8,
@"xi_reply_type": u8,
@"sequence": u16,
@"length": u32,
@"num_atoms": u16,
@"pad0": [22]u8,
@"atoms": []xcb.ATOM,
};
pub const PropertyFormat = extern enum(c_uint) {
@"8Bits" = 8,
@"16Bits" = 16,
@"32Bits" = 32,
};
/// @brief ChangeDevicePropertyRequest
pub const ChangeDevicePropertyRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 37,
@"length": u16,
@"property": xcb.ATOM,
@"type": xcb.ATOM,
@"device_id": u8,
@"format": u8,
@"mode": u8,
@"pad0": u8,
@"num_items": u32,
};
/// @brief DeleteDevicePropertyRequest
pub const DeleteDevicePropertyRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 38,
@"length": u16,
@"property": xcb.ATOM,
@"device_id": u8,
@"pad0": [3]u8,
};
/// @brief GetDevicePropertycookie
pub const GetDevicePropertycookie = struct {
sequence: c_uint,
};
/// @brief GetDevicePropertyRequest
pub const GetDevicePropertyRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 39,
@"length": u16,
@"property": xcb.ATOM,
@"type": xcb.ATOM,
@"offset": u32,
@"len": u32,
@"device_id": u8,
@"delete": u8,
@"pad0": [2]u8,
};
/// @brief GetDevicePropertyReply
pub const GetDevicePropertyReply = struct {
@"response_type": u8,
@"xi_reply_type": u8,
@"sequence": u16,
@"length": u32,
@"type": xcb.ATOM,
@"bytes_after": u32,
@"num_items": u32,
@"format": u8,
@"device_id": u8,
@"pad0": [10]u8,
};
pub const Device = extern enum(c_uint) {
@"All" = 0,
@"AllMaster" = 1,
};
/// @brief GroupInfo
pub const GroupInfo = struct {
@"base": u8,
@"latched": u8,
@"locked": u8,
@"effective": u8,
};
/// @brief ModifierInfo
pub const ModifierInfo = struct {
@"base": u32,
@"latched": u32,
@"locked": u32,
@"effective": u32,
};
/// @brief XIQueryPointercookie
pub const XIQueryPointercookie = struct {
sequence: c_uint,
};
/// @brief XIQueryPointerRequest
pub const XIQueryPointerRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 40,
@"length": u16,
@"window": xcb.WINDOW,
@"deviceid": xcb.input.DeviceId,
@"pad0": [2]u8,
};
/// @brief XIQueryPointerReply
pub const XIQueryPointerReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"root": xcb.WINDOW,
@"child": xcb.WINDOW,
@"root_x": xcb.input.FP1616,
@"root_y": xcb.input.FP1616,
@"win_x": xcb.input.FP1616,
@"win_y": xcb.input.FP1616,
@"same_screen": u8,
@"pad1": u8,
@"buttons_len": u16,
@"mods": xcb.input.ModifierInfo,
@"group": xcb.input.GroupInfo,
@"buttons": []u32,
};
/// @brief XIWarpPointerRequest
pub const XIWarpPointerRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 41,
@"length": u16,
@"src_win": xcb.WINDOW,
@"dst_win": xcb.WINDOW,
@"src_x": xcb.input.FP1616,
@"src_y": xcb.input.FP1616,
@"src_width": u16,
@"src_height": u16,
@"dst_x": xcb.input.FP1616,
@"dst_y": xcb.input.FP1616,
@"deviceid": xcb.input.DeviceId,
@"pad0": [2]u8,
};
/// @brief XIChangeCursorRequest
pub const XIChangeCursorRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 42,
@"length": u16,
@"window": xcb.WINDOW,
@"cursor": xcb.CURSOR,
@"deviceid": xcb.input.DeviceId,
@"pad0": [2]u8,
};
pub const HierarchyChangeType = extern enum(c_uint) {
@"AddMaster" = 1,
@"RemoveMaster" = 2,
@"AttachSlave" = 3,
@"DetachSlave" = 4,
};
pub const ChangeMode = extern enum(c_uint) {
@"Attach" = 1,
@"Float" = 2,
};
/// @brief AddMaster
pub const AddMaster = struct {
@"type": u16,
@"len": u16,
@"name_len": u16,
@"send_core": u8,
@"enable": u8,
@"name": []u8,
};
/// @brief RemoveMaster
pub const RemoveMaster = struct {
@"type": u16,
@"len": u16,
@"deviceid": xcb.input.DeviceId,
@"return_mode": u8,
@"pad0": u8,
@"return_pointer": xcb.input.DeviceId,
@"return_keyboard": xcb.input.DeviceId,
};
/// @brief AttachSlave
pub const AttachSlave = struct {
@"type": u16,
@"len": u16,
@"deviceid": xcb.input.DeviceId,
@"master": xcb.input.DeviceId,
};
/// @brief DetachSlave
pub const DetachSlave = struct {
@"type": u16,
@"len": u16,
@"deviceid": xcb.input.DeviceId,
@"pad0": [2]u8,
};
/// @brief HierarchyChange
pub const HierarchyChange = struct {
@"type": u16,
@"len": u16,
};
/// @brief XIChangeHierarchyRequest
pub const XIChangeHierarchyRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 43,
@"length": u16,
@"num_changes": u8,
@"pad0": [3]u8,
@"changes": []const xcb.input.HierarchyChange,
};
/// @brief XISetClientPointerRequest
pub const XISetClientPointerRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 44,
@"length": u16,
@"window": xcb.WINDOW,
@"deviceid": xcb.input.DeviceId,
@"pad0": [2]u8,
};
/// @brief XIGetClientPointercookie
pub const XIGetClientPointercookie = struct {
sequence: c_uint,
};
/// @brief XIGetClientPointerRequest
pub const XIGetClientPointerRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 45,
@"length": u16,
@"window": xcb.WINDOW,
};
/// @brief XIGetClientPointerReply
pub const XIGetClientPointerReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"set": u8,
@"pad1": u8,
@"deviceid": xcb.input.DeviceId,
@"pad2": [20]u8,
};
pub const XIEventMask = extern enum(c_uint) {
@"DeviceChanged" = 2,
@"KeyPress" = 4,
@"KeyRelease" = 8,
@"ButtonPress" = 16,
@"ButtonRelease" = 32,
@"Motion" = 64,
@"Enter" = 128,
@"Leave" = 256,
@"FocusIn" = 512,
@"FocusOut" = 1024,
@"Hierarchy" = 2048,
@"Property" = 4096,
@"RawKeyPress" = 8192,
@"RawKeyRelease" = 16384,
@"RawButtonPress" = 32768,
@"RawButtonRelease" = 65536,
@"RawMotion" = 131072,
@"TouchBegin" = 262144,
@"TouchUpdate" = 524288,
@"TouchEnd" = 1048576,
@"TouchOwnership" = 2097152,
@"RawTouchBegin" = 4194304,
@"RawTouchUpdate" = 8388608,
@"RawTouchEnd" = 16777216,
@"BarrierHit" = 33554432,
@"BarrierLeave" = 67108864,
};
/// @brief EventMask
pub const EventMask = struct {
@"deviceid": xcb.input.DeviceId,
@"mask_len": u16,
@"mask": []u32,
};
/// @brief XISelectEventsRequest
pub const XISelectEventsRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 46,
@"length": u16,
@"window": xcb.WINDOW,
@"num_mask": u16,
@"pad0": [2]u8,
@"masks": []const xcb.input.EventMask,
};
/// @brief XIQueryVersioncookie
pub const XIQueryVersioncookie = struct {
sequence: c_uint,
};
/// @brief XIQueryVersionRequest
pub const XIQueryVersionRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 47,
@"length": u16,
@"major_version": u16,
@"minor_version": u16,
};
/// @brief XIQueryVersionReply
pub const XIQueryVersionReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"major_version": u16,
@"minor_version": u16,
@"pad1": [20]u8,
};
pub const DeviceClassType = extern enum(c_uint) {
@"Key" = 0,
@"Button" = 1,
@"Valuator" = 2,
@"Scroll" = 3,
@"Touch" = 8,
};
pub const DeviceType = extern enum(c_uint) {
@"MasterPointer" = 1,
@"MasterKeyboard" = 2,
@"SlavePointer" = 3,
@"SlaveKeyboard" = 4,
@"FloatingSlave" = 5,
};
pub const ScrollFlags = extern enum(c_uint) {
@"NoEmulation" = 1,
@"Preferred" = 2,
};
pub const ScrollType = extern enum(c_uint) {
@"Vertical" = 1,
@"Horizontal" = 2,
};
pub const TouchMode = extern enum(c_uint) {
@"Direct" = 1,
@"Dependent" = 2,
};
/// @brief ButtonClass
pub const ButtonClass = struct {
@"type": u16,
@"len": u16,
@"sourceid": xcb.input.DeviceId,
@"num_buttons": u16,
@"state": []u32,
@"labels": []xcb.ATOM,
};
/// @brief KeyClass
pub const KeyClass = struct {
@"type": u16,
@"len": u16,
@"sourceid": xcb.input.DeviceId,
@"num_keys": u16,
@"keys": []u32,
};
/// @brief ScrollClass
pub const ScrollClass = struct {
@"type": u16,
@"len": u16,
@"sourceid": xcb.input.DeviceId,
@"number": u16,
@"scroll_type": u16,
@"pad0": [2]u8,
@"flags": u32,
@"increment": xcb.input.FP3232,
};
/// @brief TouchClass
pub const TouchClass = struct {
@"type": u16,
@"len": u16,
@"sourceid": xcb.input.DeviceId,
@"mode": u8,
@"num_touches": u8,
};
/// @brief ValuatorClass
pub const ValuatorClass = struct {
@"type": u16,
@"len": u16,
@"sourceid": xcb.input.DeviceId,
@"number": u16,
@"label": xcb.ATOM,
@"min": xcb.input.FP3232,
@"max": xcb.input.FP3232,
@"value": xcb.input.FP3232,
@"resolution": u32,
@"mode": u8,
@"pad0": [3]u8,
};
/// @brief DeviceClass
pub const DeviceClass = struct {
@"type": u16,
@"len": u16,
@"sourceid": xcb.input.DeviceId,
};
/// @brief XIDeviceInfo
pub const XIDeviceInfo = struct {
@"deviceid": xcb.input.DeviceId,
@"type": u16,
@"attachment": xcb.input.DeviceId,
@"num_classes": u16,
@"name_len": u16,
@"enabled": u8,
@"pad0": u8,
@"name": []u8,
@"classes": []xcb.input.DeviceClass,
};
/// @brief XIQueryDevicecookie
pub const XIQueryDevicecookie = struct {
sequence: c_uint,
};
/// @brief XIQueryDeviceRequest
pub const XIQueryDeviceRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 48,
@"length": u16,
@"deviceid": xcb.input.DeviceId,
@"pad0": [2]u8,
};
/// @brief XIQueryDeviceReply
pub const XIQueryDeviceReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"num_infos": u16,
@"pad1": [22]u8,
@"infos": []xcb.input.XIDeviceInfo,
};
/// @brief XISetFocusRequest
pub const XISetFocusRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 49,
@"length": u16,
@"window": xcb.WINDOW,
@"time": xcb.TIMESTAMP,
@"deviceid": xcb.input.DeviceId,
@"pad0": [2]u8,
};
/// @brief XIGetFocuscookie
pub const XIGetFocuscookie = struct {
sequence: c_uint,
};
/// @brief XIGetFocusRequest
pub const XIGetFocusRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 50,
@"length": u16,
@"deviceid": xcb.input.DeviceId,
@"pad0": [2]u8,
};
/// @brief XIGetFocusReply
pub const XIGetFocusReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"focus": xcb.WINDOW,
@"pad1": [20]u8,
};
pub const GrabOwner = extern enum(c_uint) {
@"NoOwner" = 0,
@"Owner" = 1,
};
/// @brief XIGrabDevicecookie
pub const XIGrabDevicecookie = struct {
sequence: c_uint,
};
/// @brief XIGrabDeviceRequest
pub const XIGrabDeviceRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 51,
@"length": u16,
@"window": xcb.WINDOW,
@"time": xcb.TIMESTAMP,
@"cursor": xcb.CURSOR,
@"deviceid": xcb.input.DeviceId,
@"mode": u8,
@"paired_device_mode": u8,
@"owner_events": u8,
@"pad0": u8,
@"mask_len": u16,
@"mask": []const u32,
};
/// @brief XIGrabDeviceReply
pub const XIGrabDeviceReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"status": u8,
@"pad1": [23]u8,
};
/// @brief XIUngrabDeviceRequest
pub const XIUngrabDeviceRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 52,
@"length": u16,
@"time": xcb.TIMESTAMP,
@"deviceid": xcb.input.DeviceId,
@"pad0": [2]u8,
};
pub const EventMode = extern enum(c_uint) {
@"AsyncDevice" = 0,
@"SyncDevice" = 1,
@"ReplayDevice" = 2,
@"AsyncPairedDevice" = 3,
@"AsyncPair" = 4,
@"SyncPair" = 5,
@"AcceptTouch" = 6,
@"RejectTouch" = 7,
};
/// @brief XIAllowEventsRequest
pub const XIAllowEventsRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 53,
@"length": u16,
@"time": xcb.TIMESTAMP,
@"deviceid": xcb.input.DeviceId,
@"event_mode": u8,
@"pad0": u8,
@"touchid": u32,
@"grab_window": xcb.WINDOW,
};
pub const GrabMode22 = extern enum(c_uint) {
@"Sync" = 0,
@"Async" = 1,
@"Touch" = 2,
};
pub const GrabType = extern enum(c_uint) {
@"Button" = 0,
@"Keycode" = 1,
@"Enter" = 2,
@"FocusIn" = 3,
@"TouchBegin" = 4,
};
pub const ModifierMask = extern enum(c_uint) {
@"Any" = 2147483648,
};
/// @brief GrabModifierInfo
pub const GrabModifierInfo = struct {
@"modifiers": u32,
@"status": u8,
@"pad0": [3]u8,
};
/// @brief XIPassiveGrabDevicecookie
pub const XIPassiveGrabDevicecookie = struct {
sequence: c_uint,
};
/// @brief XIPassiveGrabDeviceRequest
pub const XIPassiveGrabDeviceRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 54,
@"length": u16,
@"time": xcb.TIMESTAMP,
@"grab_window": xcb.WINDOW,
@"cursor": xcb.CURSOR,
@"detail": u32,
@"deviceid": xcb.input.DeviceId,
@"num_modifiers": u16,
@"mask_len": u16,
@"grab_type": u8,
@"grab_mode": u8,
@"paired_device_mode": u8,
@"owner_events": u8,
@"pad0": [2]u8,
@"mask": []const u32,
@"modifiers": []const u32,
};
/// @brief XIPassiveGrabDeviceReply
pub const XIPassiveGrabDeviceReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"num_modifiers": u16,
@"pad1": [22]u8,
@"modifiers": []xcb.input.GrabModifierInfo,
};
/// @brief XIPassiveUngrabDeviceRequest
pub const XIPassiveUngrabDeviceRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 55,
@"length": u16,
@"grab_window": xcb.WINDOW,
@"detail": u32,
@"deviceid": xcb.input.DeviceId,
@"num_modifiers": u16,
@"grab_type": u8,
@"pad0": [3]u8,
@"modifiers": []const u32,
};
/// @brief XIListPropertiescookie
pub const XIListPropertiescookie = struct {
sequence: c_uint,
};
/// @brief XIListPropertiesRequest
pub const XIListPropertiesRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 56,
@"length": u16,
@"deviceid": xcb.input.DeviceId,
@"pad0": [2]u8,
};
/// @brief XIListPropertiesReply
pub const XIListPropertiesReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"num_properties": u16,
@"pad1": [22]u8,
@"properties": []xcb.ATOM,
};
/// @brief XIChangePropertyRequest
pub const XIChangePropertyRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 57,
@"length": u16,
@"deviceid": xcb.input.DeviceId,
@"mode": u8,
@"format": u8,
@"property": xcb.ATOM,
@"type": xcb.ATOM,
@"num_items": u32,
};
/// @brief XIDeletePropertyRequest
pub const XIDeletePropertyRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 58,
@"length": u16,
@"deviceid": xcb.input.DeviceId,
@"pad0": [2]u8,
@"property": xcb.ATOM,
};
/// @brief XIGetPropertycookie
pub const XIGetPropertycookie = struct {
sequence: c_uint,
};
/// @brief XIGetPropertyRequest
pub const XIGetPropertyRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 59,
@"length": u16,
@"deviceid": xcb.input.DeviceId,
@"delete": u8,
@"pad0": u8,
@"property": xcb.ATOM,
@"type": xcb.ATOM,
@"offset": u32,
@"len": u32,
};
/// @brief XIGetPropertyReply
pub const XIGetPropertyReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"type": xcb.ATOM,
@"bytes_after": u32,
@"num_items": u32,
@"format": u8,
@"pad1": [11]u8,
};
/// @brief XIGetSelectedEventscookie
pub const XIGetSelectedEventscookie = struct {
sequence: c_uint,
};
/// @brief XIGetSelectedEventsRequest
pub const XIGetSelectedEventsRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 60,
@"length": u16,
@"window": xcb.WINDOW,
};
/// @brief XIGetSelectedEventsReply
pub const XIGetSelectedEventsReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"num_masks": u16,
@"pad1": [22]u8,
@"masks": []xcb.input.EventMask,
};
/// @brief BarrierReleasePointerInfo
pub const BarrierReleasePointerInfo = struct {
@"deviceid": xcb.input.DeviceId,
@"pad0": [2]u8,
@"barrier": xcb.xfixes.BARRIER,
@"eventid": u32,
};
/// @brief XIBarrierReleasePointerRequest
pub const XIBarrierReleasePointerRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 61,
@"length": u16,
@"num_barriers": u32,
@"barriers": []const xcb.input.BarrierReleasePointerInfo,
};
/// Opcode for DeviceValuator.
pub const DeviceValuatorOpcode = 0;
/// @brief DeviceValuatorEvent
pub const DeviceValuatorEvent = struct {
@"response_type": u8,
@"device_id": u8,
@"sequence": u16,
@"device_state": u16,
@"num_valuators": u8,
@"first_valuator": u8,
@"valuators": [6]i32,
};
pub const MoreEventsMask = extern enum(c_uint) {
@"MoreEvents" = 128,
};
/// Opcode for DeviceKeyPress.
pub const DeviceKeyPressOpcode = 1;
/// @brief DeviceKeyPressEvent
pub const DeviceKeyPressEvent = struct {
@"response_type": u8,
@"detail": u8,
@"sequence": u16,
@"time": xcb.TIMESTAMP,
@"root": xcb.WINDOW,
@"event": xcb.WINDOW,
@"child": xcb.WINDOW,
@"root_x": i16,
@"root_y": i16,
@"event_x": i16,
@"event_y": i16,
@"state": u16,
@"same_screen": u8,
@"device_id": u8,
};
/// Opcode for DeviceKeyRelease.
pub const DeviceKeyReleaseOpcode = 2;
pub const DeviceKeyReleaseEvent = xcb.input.DeviceKeyPressEvent;
/// Opcode for DeviceButtonPress.
pub const DeviceButtonPressOpcode = 3;
pub const DeviceButtonPressEvent = xcb.input.DeviceKeyPressEvent;
/// Opcode for DeviceButtonRelease.
pub const DeviceButtonReleaseOpcode = 4;
pub const DeviceButtonReleaseEvent = xcb.input.DeviceKeyPressEvent;
/// Opcode for DeviceMotionNotify.
pub const DeviceMotionNotifyOpcode = 5;
pub const DeviceMotionNotifyEvent = xcb.input.DeviceKeyPressEvent;
/// Opcode for DeviceFocusIn.
pub const DeviceFocusInOpcode = 6;
/// @brief DeviceFocusInEvent
pub const DeviceFocusInEvent = struct {
@"response_type": u8,
@"detail": u8,
@"sequence": u16,
@"time": xcb.TIMESTAMP,
@"window": xcb.WINDOW,
@"mode": u8,
@"device_id": u8,
@"pad0": [18]u8,
};
/// Opcode for DeviceFocusOut.
pub const DeviceFocusOutOpcode = 7;
pub const DeviceFocusOutEvent = xcb.input.DeviceFocusInEvent;
/// Opcode for ProximityIn.
pub const ProximityInOpcode = 8;
pub const ProximityInEvent = xcb.input.DeviceKeyPressEvent;
/// Opcode for ProximityOut.
pub const ProximityOutOpcode = 9;
pub const ProximityOutEvent = xcb.input.DeviceKeyPressEvent;
pub const ClassesReportedMask = extern enum(c_uint) {
@"OutOfProximity" = 128,
@"DeviceModeAbsolute" = 64,
@"ReportingValuators" = 4,
@"ReportingButtons" = 2,
@"ReportingKeys" = 1,
};
/// Opcode for DeviceStateNotify.
pub const DeviceStateNotifyOpcode = 10;
/// @brief DeviceStateNotifyEvent
pub const DeviceStateNotifyEvent = struct {
@"response_type": u8,
@"device_id": u8,
@"sequence": u16,
@"time": xcb.TIMESTAMP,
@"num_keys": u8,
@"num_buttons": u8,
@"num_valuators": u8,
@"classes_reported": u8,
@"buttons": [4]u8,
@"keys": [4]u8,
@"valuators": [3]u32,
};
/// Opcode for DeviceMappingNotify.
pub const DeviceMappingNotifyOpcode = 11;
/// @brief DeviceMappingNotifyEvent
pub const DeviceMappingNotifyEvent = struct {
@"response_type": u8,
@"device_id": u8,
@"sequence": u16,
@"request": u8,
@"first_keycode": xcb.input.KeyCode,
@"count": u8,
@"pad0": u8,
@"time": xcb.TIMESTAMP,
@"pad1": [20]u8,
};
pub const ChangeDevice = extern enum(c_uint) {
@"NewPointer" = 0,
@"NewKeyboard" = 1,
};
/// Opcode for ChangeDeviceNotify.
pub const ChangeDeviceNotifyOpcode = 12;
/// @brief ChangeDeviceNotifyEvent
pub const ChangeDeviceNotifyEvent = struct {
@"response_type": u8,
@"device_id": u8,
@"sequence": u16,
@"time": xcb.TIMESTAMP,
@"request": u8,
@"pad0": [23]u8,
};
/// Opcode for DeviceKeyStateNotify.
pub const DeviceKeyStateNotifyOpcode = 13;
/// @brief DeviceKeyStateNotifyEvent
pub const DeviceKeyStateNotifyEvent = struct {
@"response_type": u8,
@"device_id": u8,
@"sequence": u16,
@"keys": [28]u8,
};
/// Opcode for DeviceButtonStateNotify.
pub const DeviceButtonStateNotifyOpcode = 14;
/// @brief DeviceButtonStateNotifyEvent
pub const DeviceButtonStateNotifyEvent = struct {
@"response_type": u8,
@"device_id": u8,
@"sequence": u16,
@"buttons": [28]u8,
};
pub const DeviceChange = extern enum(c_uint) {
@"Added" = 0,
@"Removed" = 1,
@"Enabled" = 2,
@"Disabled" = 3,
@"Unrecoverable" = 4,
@"ControlChanged" = 5,
};
/// Opcode for DevicePresenceNotify.
pub const DevicePresenceNotifyOpcode = 15;
/// @brief DevicePresenceNotifyEvent
pub const DevicePresenceNotifyEvent = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"time": xcb.TIMESTAMP,
@"devchange": u8,
@"device_id": u8,
@"control": u16,
@"pad1": [20]u8,
};
/// Opcode for DevicePropertyNotify.
pub const DevicePropertyNotifyOpcode = 16;
/// @brief DevicePropertyNotifyEvent
pub const DevicePropertyNotifyEvent = struct {
@"response_type": u8,
@"state": u8,
@"sequence": u16,
@"time": xcb.TIMESTAMP,
@"property": xcb.ATOM,
@"pad0": [19]u8,
@"device_id": u8,
};
pub const ChangeReason = extern enum(c_uint) {
@"SlaveSwitch" = 1,
@"DeviceChange" = 2,
};
/// Opcode for DeviceChanged.
pub const DeviceChangedOpcode = 1;
/// @brief DeviceChangedEvent
pub const DeviceChangedEvent = struct {
@"response_type": u8,
@"extension": u8,
@"sequence": u16,
@"length": u32,
@"event_type": u16,
@"deviceid": xcb.input.DeviceId,
@"time": xcb.TIMESTAMP,
@"num_classes": u16,
@"sourceid": xcb.input.DeviceId,
@"reason": u8,
@"pad0": [11]u8,
@"full_sequence": u32,
@"classes": []xcb.input.DeviceClass,
};
pub const KeyEventFlags = extern enum(c_uint) {
@"KeyRepeat" = 65536,
};
/// Opcode for KeyPress.
pub const KeyPressOpcode = 2;
/// @brief KeyPressEvent
pub const KeyPressEvent = struct {
@"response_type": u8,
@"extension": u8,
@"sequence": u16,
@"length": u32,
@"event_type": u16,
@"deviceid": xcb.input.DeviceId,
@"time": xcb.TIMESTAMP,
@"detail": u32,
@"root": xcb.WINDOW,
@"event": xcb.WINDOW,
@"child": xcb.WINDOW,
@"full_sequence": u32,
@"root_x": xcb.input.FP1616,
@"root_y": xcb.input.FP1616,
@"event_x": xcb.input.FP1616,
@"event_y": xcb.input.FP1616,
@"buttons_len": u16,
@"valuators_len": u16,
@"sourceid": xcb.input.DeviceId,
@"pad0": [2]u8,
@"flags": u32,
@"mods": xcb.input.ModifierInfo,
@"group": xcb.input.GroupInfo,
@"button_mask": []u32,
@"valuator_mask": []u32,
@"axisvalues": []xcb.input.FP3232,
};
/// Opcode for KeyRelease.
pub const KeyReleaseOpcode = 3;
pub const KeyReleaseEvent = xcb.input.KeyPressEvent;
pub const PointerEventFlags = extern enum(c_uint) {
@"PointerEmulated" = 65536,
};
/// Opcode for ButtonPress.
pub const ButtonPressOpcode = 4;
/// @brief ButtonPressEvent
pub const ButtonPressEvent = struct {
@"response_type": u8,
@"extension": u8,
@"sequence": u16,
@"length": u32,
@"event_type": u16,
@"deviceid": xcb.input.DeviceId,
@"time": xcb.TIMESTAMP,
@"detail": u32,
@"root": xcb.WINDOW,
@"event": xcb.WINDOW,
@"child": xcb.WINDOW,
@"full_sequence": u32,
@"root_x": xcb.input.FP1616,
@"root_y": xcb.input.FP1616,
@"event_x": xcb.input.FP1616,
@"event_y": xcb.input.FP1616,
@"buttons_len": u16,
@"valuators_len": u16,
@"sourceid": xcb.input.DeviceId,
@"pad0": [2]u8,
@"flags": u32,
@"mods": xcb.input.ModifierInfo,
@"group": xcb.input.GroupInfo,
@"button_mask": []u32,
@"valuator_mask": []u32,
@"axisvalues": []xcb.input.FP3232,
};
/// Opcode for ButtonRelease.
pub const ButtonReleaseOpcode = 5;
pub const ButtonReleaseEvent = xcb.input.ButtonPressEvent;
/// Opcode for Motion.
pub const MotionOpcode = 6;
pub const MotionEvent = xcb.input.ButtonPressEvent;
pub const NotifyMode = extern enum(c_uint) {
@"Normal" = 0,
@"Grab" = 1,
@"Ungrab" = 2,
@"WhileGrabbed" = 3,
@"PassiveGrab" = 4,
@"PassiveUngrab" = 5,
};
pub const NotifyDetail = extern enum(c_uint) {
@"Ancestor" = 0,
@"Virtual" = 1,
@"Inferior" = 2,
@"Nonlinear" = 3,
@"NonlinearVirtual" = 4,
@"Pointer" = 5,
@"PointerRoot" = 6,
@"None" = 7,
};
/// Opcode for Enter.
pub const EnterOpcode = 7;
/// @brief EnterEvent
pub const EnterEvent = struct {
@"response_type": u8,
@"extension": u8,
@"sequence": u16,
@"length": u32,
@"event_type": u16,
@"deviceid": xcb.input.DeviceId,
@"time": xcb.TIMESTAMP,
@"sourceid": xcb.input.DeviceId,
@"mode": u8,
@"detail": u8,
@"root": xcb.WINDOW,
@"event": xcb.WINDOW,
@"child": xcb.WINDOW,
@"full_sequence": u32,
@"root_x": xcb.input.FP1616,
@"root_y": xcb.input.FP1616,
@"event_x": xcb.input.FP1616,
@"event_y": xcb.input.FP1616,
@"same_screen": u8,
@"focus": u8,
@"buttons_len": u16,
@"mods": xcb.input.ModifierInfo,
@"group": xcb.input.GroupInfo,
@"buttons": []u32,
};
/// Opcode for Leave.
pub const LeaveOpcode = 8;
pub const LeaveEvent = xcb.input.EnterEvent;
/// Opcode for FocusIn.
pub const FocusInOpcode = 9;
pub const FocusInEvent = xcb.input.EnterEvent;
/// Opcode for FocusOut.
pub const FocusOutOpcode = 10;
pub const FocusOutEvent = xcb.input.EnterEvent;
pub const HierarchyMask = extern enum(c_uint) {
@"MasterAdded" = 1,
@"MasterRemoved" = 2,
@"SlaveAdded" = 4,
@"SlaveRemoved" = 8,
@"SlaveAttached" = 16,
@"SlaveDetached" = 32,
@"DeviceEnabled" = 64,
@"DeviceDisabled" = 128,
};
/// @brief HierarchyInfo
pub const HierarchyInfo = struct {
@"deviceid": xcb.input.DeviceId,
@"attachment": xcb.input.DeviceId,
@"type": u8,
@"enabled": u8,
@"pad0": [2]u8,
@"flags": u32,
};
/// Opcode for Hierarchy.
pub const HierarchyOpcode = 11;
/// @brief HierarchyEvent
pub const HierarchyEvent = struct {
@"response_type": u8,
@"extension": u8,
@"sequence": u16,
@"length": u32,
@"event_type": u16,
@"deviceid": xcb.input.DeviceId,
@"time": xcb.TIMESTAMP,
@"flags": u32,
@"num_infos": u16,
@"pad0": [10]u8,
@"full_sequence": u32,
@"infos": []xcb.input.HierarchyInfo,
};
pub const PropertyFlag = extern enum(c_uint) {
@"Deleted" = 0,
@"Created" = 1,
@"Modified" = 2,
};
/// Opcode for Property.
pub const PropertyOpcode = 12;
/// @brief PropertyEvent
pub const PropertyEvent = struct {
@"response_type": u8,
@"extension": u8,
@"sequence": u16,
@"length": u32,
@"event_type": u16,
@"deviceid": xcb.input.DeviceId,
@"time": xcb.TIMESTAMP,
@"property": xcb.ATOM,
@"what": u8,
@"pad0": [11]u8,
@"full_sequence": u32,
};
/// Opcode for RawKeyPress.
pub const RawKeyPressOpcode = 13;
/// @brief RawKeyPressEvent
pub const RawKeyPressEvent = struct {
@"response_type": u8,
@"extension": u8,
@"sequence": u16,
@"length": u32,
@"event_type": u16,
@"deviceid": xcb.input.DeviceId,
@"time": xcb.TIMESTAMP,
@"detail": u32,
@"sourceid": xcb.input.DeviceId,
@"valuators_len": u16,
@"flags": u32,
@"pad0": [4]u8,
@"full_sequence": u32,
@"valuator_mask": []u32,
@"axisvalues": []xcb.input.FP3232,
@"axisvalues_raw": []xcb.input.FP3232,
};
/// Opcode for RawKeyRelease.
pub const RawKeyReleaseOpcode = 14;
pub const RawKeyReleaseEvent = xcb.input.RawKeyPressEvent;
/// Opcode for RawButtonPress.
pub const RawButtonPressOpcode = 15;
/// @brief RawButtonPressEvent
pub const RawButtonPressEvent = struct {
@"response_type": u8,
@"extension": u8,
@"sequence": u16,
@"length": u32,
@"event_type": u16,
@"deviceid": xcb.input.DeviceId,
@"time": xcb.TIMESTAMP,
@"detail": u32,
@"sourceid": xcb.input.DeviceId,
@"valuators_len": u16,
@"flags": u32,
@"pad0": [4]u8,
@"full_sequence": u32,
@"valuator_mask": []u32,
@"axisvalues": []xcb.input.FP3232,
@"axisvalues_raw": []xcb.input.FP3232,
};
/// Opcode for RawButtonRelease.
pub const RawButtonReleaseOpcode = 16;
pub const RawButtonReleaseEvent = xcb.input.RawButtonPressEvent;
/// Opcode for RawMotion.
pub const RawMotionOpcode = 17;
pub const RawMotionEvent = xcb.input.RawButtonPressEvent;
pub const TouchEventFlags = extern enum(c_uint) {
@"TouchPendingEnd" = 65536,
@"TouchEmulatingPointer" = 131072,
};
/// Opcode for TouchBegin.
pub const TouchBeginOpcode = 18;
/// @brief TouchBeginEvent
pub const TouchBeginEvent = struct {
@"response_type": u8,
@"extension": u8,
@"sequence": u16,
@"length": u32,
@"event_type": u16,
@"deviceid": xcb.input.DeviceId,
@"time": xcb.TIMESTAMP,
@"detail": u32,
@"root": xcb.WINDOW,
@"event": xcb.WINDOW,
@"child": xcb.WINDOW,
@"full_sequence": u32,
@"root_x": xcb.input.FP1616,
@"root_y": xcb.input.FP1616,
@"event_x": xcb.input.FP1616,
@"event_y": xcb.input.FP1616,
@"buttons_len": u16,
@"valuators_len": u16,
@"sourceid": xcb.input.DeviceId,
@"pad0": [2]u8,
@"flags": u32,
@"mods": xcb.input.ModifierInfo,
@"group": xcb.input.GroupInfo,
@"button_mask": []u32,
@"valuator_mask": []u32,
@"axisvalues": []xcb.input.FP3232,
};
/// Opcode for TouchUpdate.
pub const TouchUpdateOpcode = 19;
pub const TouchUpdateEvent = xcb.input.TouchBeginEvent;
/// Opcode for TouchEnd.
pub const TouchEndOpcode = 20;
pub const TouchEndEvent = xcb.input.TouchBeginEvent;
pub const TouchOwnershipFlags = extern enum(c_uint) {
@"None" = 0,
};
/// Opcode for TouchOwnership.
pub const TouchOwnershipOpcode = 21;
/// @brief TouchOwnershipEvent
pub const TouchOwnershipEvent = struct {
@"response_type": u8,
@"extension": u8,
@"sequence": u16,
@"length": u32,
@"event_type": u16,
@"deviceid": xcb.input.DeviceId,
@"time": xcb.TIMESTAMP,
@"touchid": u32,
@"root": xcb.WINDOW,
@"event": xcb.WINDOW,
@"child": xcb.WINDOW,
@"full_sequence": u32,
@"sourceid": xcb.input.DeviceId,
@"pad0": [2]u8,
@"flags": u32,
@"pad1": [8]u8,
};
/// Opcode for RawTouchBegin.
pub const RawTouchBeginOpcode = 22;
/// @brief RawTouchBeginEvent
pub const RawTouchBeginEvent = struct {
@"response_type": u8,
@"extension": u8,
@"sequence": u16,
@"length": u32,
@"event_type": u16,
@"deviceid": xcb.input.DeviceId,
@"time": xcb.TIMESTAMP,
@"detail": u32,
@"sourceid": xcb.input.DeviceId,
@"valuators_len": u16,
@"flags": u32,
@"pad0": [4]u8,
@"full_sequence": u32,
@"valuator_mask": []u32,
@"axisvalues": []xcb.input.FP3232,
@"axisvalues_raw": []xcb.input.FP3232,
};
/// Opcode for RawTouchUpdate.
pub const RawTouchUpdateOpcode = 23;
pub const RawTouchUpdateEvent = xcb.input.RawTouchBeginEvent;
/// Opcode for RawTouchEnd.
pub const RawTouchEndOpcode = 24;
pub const RawTouchEndEvent = xcb.input.RawTouchBeginEvent;
pub const BarrierFlags = extern enum(c_uint) {
@"PointerReleased" = 1,
@"DeviceIsGrabbed" = 2,
};
/// Opcode for BarrierHit.
pub const BarrierHitOpcode = 25;
/// @brief BarrierHitEvent
pub const BarrierHitEvent = struct {
@"response_type": u8,
@"extension": u8,
@"sequence": u16,
@"length": u32,
@"event_type": u16,
@"deviceid": xcb.input.DeviceId,
@"time": xcb.TIMESTAMP,
@"eventid": u32,
@"root": xcb.WINDOW,
@"event": xcb.WINDOW,
@"barrier": xcb.xfixes.BARRIER,
@"full_sequence": u32,
@"dtime": u32,
@"flags": u32,
@"sourceid": xcb.input.DeviceId,
@"pad0": [2]u8,
@"root_x": xcb.input.FP1616,
@"root_y": xcb.input.FP1616,
@"dx": xcb.input.FP3232,
@"dy": xcb.input.FP3232,
};
/// Opcode for BarrierLeave.
pub const BarrierLeaveOpcode = 26;
pub const BarrierLeaveEvent = xcb.input.BarrierHitEvent;
/// Opcode for Device.
pub const DeviceOpcode = 0;
/// @brief DeviceError
pub const DeviceError = struct {
@"response_type": u8,
@"error_code": u8,
@"sequence": u16,
};
/// Opcode for Event.
pub const EventOpcode = 1;
/// @brief EventError
pub const EventError = struct {
@"response_type": u8,
@"error_code": u8,
@"sequence": u16,
};
/// Opcode for Mode.
pub const ModeOpcode = 2;
/// @brief ModeError
pub const ModeError = struct {
@"response_type": u8,
@"error_code": u8,
@"sequence": u16,
};
/// Opcode for DeviceBusy.
pub const DeviceBusyOpcode = 3;
/// @brief DeviceBusyError
pub const DeviceBusyError = struct {
@"response_type": u8,
@"error_code": u8,
@"sequence": u16,
};
/// Opcode for Class.
pub const ClassOpcode = 4;
/// @brief ClassError
pub const ClassError = struct {
@"response_type": u8,
@"error_code": u8,
@"sequence": u16,
};
test "" {
@import("std").testing.refAllDecls(@This());
} | src/auto/xinput.zig |
const std = @import("std");
const Lexer = @import("lexer.zig");
const Arguments = @import("args.zig");
const Task = @import("task.zig");
const Date = @import("date.zig");
const testing = std.testing;
const ParseError = Lexer.TokenError || error {
ExpectedDay,
ExpectedMonth,
ExpectedYear,
ExpectedNext,
ExpectedThis,
ExpectedDuration,
MonthDoesNotExist,
DayOutOfRange,
};
/// Used to parse tasks from the command line argument.
pub fn parseTask(buffer: []u8, timezone: Date.Timezone, args: *Arguments) ParseError!Task {
var lex = Lexer { .args = args, };
const content = readContent(buffer, args);
const due = try root(&lex, timezone);
return Task {
.content = content,
.due = due,
.completed = false,
};
}
fn root(lex: *Lexer, timezone: Date.Timezone) ParseError!?Date {
const t = try lex.peek();
if (t) |val| {
return switch (val) {
.month_name => try monthDayFormat(lex, timezone),
.this => try this(lex),
.next => try next(lex),
.tomorrow => tomorrow(),
.today => today(),
else => ParseError.ExpectedMonth,
};
} else return noDueDate(lex);
}
fn noDueDate(lex: *Lexer) ?Date {
return null;
}
fn this(lex: *Lexer) ParseError!Date {
_ = (try lex.next()) orelse return ParseError.ExpectedThis;
const t = try lex.next();
if (t) |val| {
return switch (val) {
.week => getThisWeek(Date.DayOfWeek.saturday, Date.now()),
.month => getThisMonth(Date.now()),
.week_day_name => |d| getThisWeek(d, Date.now()),
else => ParseError.ExpectedDuration,
};
} else return ParseError.ExpectedThis;
}
fn next(lex: *Lexer) ParseError!Date {
_ = (try lex.next()) orelse return ParseError.ExpectedNext;
const t = try lex.next();
if (t) |val| {
return switch (val) {
.week => getNextWeek(Date.DayOfWeek.saturday, Date.now()),
.month => getNextMonth(Date.now()),
.week_day_name => |d| getThisWeek(d, Date.now()),
else => ParseError.ExpectedDuration,
};
} else return ParseError.ExpectedNext;
}
fn getNextWeek(w: Date.DayOfWeek, date: Date) Date {
const endOfThisWeek = getThisWeek(w, date);
return endOfThisWeek.add(Date {.days = 7});
}
fn getNextMonth(date: Date) Date {
return getThisMonth(getThisMonth(date));
}
fn getDayDifference(start: Date.DayOfWeek, end: Date.DayOfWeek) u32 {
const start_n = @intCast(u32, @enumToInt(start));
const end_n = @intCast(u32, @enumToInt(end));
if (start_n >= end_n) {
return 7 - (std.math.max(start_n, end_n) - std.math.min(start_n, end_n));
}
return end_n - start_n;
}
fn getThisWeek(w: Date.DayOfWeek, date: Date) Date {
const diff = getDayDifference(date.dayOfWeek(), w);
return date.add(Date {.days = diff});
}
fn getThisMonth(date: Date) Date {
const t = date.day();
const month_num = date.month();
const days_in_month = date.yearMonths()[month_num];
return date.add(Date {.days = 1 + days_in_month - t});
}
fn tomorrow() Date {
return Date.now().add(Date {.days = 1}).flatten();
}
fn today() Date {
return Date.now().flatten();
}
fn monthDayFormat(lex: *Lexer, timezone: Date.Timezone) ParseError!Date {
const m = try month(lex);
const d = try day(lex);
const y = blk: {
if (try lex.peek()) |y| {
break :blk try year(lex);
} else {
const now = Date.now().flatten();
const default = try Date.init(now.year(), m, d);
const useSmartYearAssumption = now.compare(default) > 0; // fancy way of saying increment year by 1
break :blk now.year() + if (useSmartYearAssumption) @as(u32, 1) else @as(u32, 0);
}
};
// When user enters may 26, it's implied that it's may 26 00:00:00 CST (or any other timezone).
// So, we must convert it to UTC, so that the formatting doesn't screw up.
return (try Date.init(y, m, d)).toUtc(timezone);
}
fn month(lex: *Lexer) ParseError!u32 {
const t = try lex.next();
if (t) |val| {
switch (val) {
.month_name => |m| return @intCast(u32, @enumToInt(m)),
else => return ParseError.ExpectedMonth,
}
} else return ParseError.ExpectedMonth;
}
fn day(lex: *Lexer) ParseError!u32 {
const t = try lex.next();
if (t) |val| {
switch (val) {
.number => |n| return n - 1,
else => return ParseError.ExpectedDay,
}
} else return ParseError.ExpectedDay;
}
fn year(lex: *Lexer) ParseError!u32 {
const t = try lex.next();
if (t) |val| {
switch (val) {
.number => |n| return n,
else => return ParseError.ExpectedYear
}
} else return ParseError.ExpectedYear;
}
/// Content is the task itself, the todo. It can end with a ";", or if there's nothing left
fn readContent(buffer: []u8, args: *Arguments) [:0]u8 {
var tail: usize = 0; // Points to the first available memory
while (args.next()) |word| {
if (std.mem.eql(u8, word, ";")) {
buffer[tail] = 0;
return buffer[0..tail:0];
} else {
if (tail != 0) {
buffer[tail] = ' ';
tail += 1;
}
std.mem.copy(u8, buffer[tail..], word);
tail += word.len;
}
}
buffer[tail] = 0;
return buffer[0..tail:0];
}
test "parser.readContent" {
var buffer: [100]u8 = undefined;
{
var raw_args = [_][:0]const u8 {"10.1", "Conics", "&", "Calculus", ";", "nice", "extra", "stuff"};
var args = Arguments {
.args = raw_args[0..],
};
const content = readContent(buffer[0..], &args);
testing.expect(std.mem.eql(u8, content, "10.1 Conics & Calculus"));
}
{
var raw_args = [_][:0]const u8 {"10.1", "Conics", "&", "Calculus"};
var args = Arguments {
.args = raw_args[0..],
};
const content = readContent(buffer[0..], &args);
testing.expect(std.mem.eql(u8, content, "10.1 Conics & Calculus"));
}
{
var raw_args = [_][:0]const u8{};
var args = Arguments {
.args = raw_args[0..],
};
const content = readContent(buffer[0..], &args);
testing.expect(std.mem.eql(u8, content, ""));
}
}
test "parser.parseTask" {
var buffer: [100]u8 = undefined;
{
const raw_args = [_][:0]const u8 {"Conic", "Sections", "exam", ";", "jan", "2"};
var args = Arguments {
.args = raw_args[0..],
};
const task = try parseTask(buffer[0..], &args);
testing.expectEqualSlices(u8, "Conic Sections exam", task.content);
testing.expectEqual(Date {.days = 1,}, task.due.?);
testing.expectEqual(false, task.completed);
}
} | src/task_parser.zig |
const std = @import("std");
const builtin = @import("builtin");
//extern "c" fn system([*:0]const u8) c_int;
pub fn putInClipboard(allocator: *std.mem.Allocator, utf8: []const u8) anyerror!void {
switch (builtin.os.tag) {
.windows => try win.putInClipboard(allocator, utf8),
else => return error.ClipboardNotAvailable,
}
}
const win = struct {
extern "user32" fn SetClipboardData(uFormat: c_uint, hMem: ?*c_void) ?*c_void;
extern "user32" fn OpenClipboard(hWndNewOwner: [*c]c_int) c_int;
extern "user32" fn CloseClipboard() c_int;
extern "user32" fn EmptyClipboard() c_int;
extern "user32" fn GetLastError() c_ulong;
extern "kernel32" fn GlobalAlloc(uFlags: c_uint, dwBytes: usize) ?*c_void;
extern "kernel32" fn GlobalLock(hMem: ?*c_void) ?*c_void;
extern "kernel32" fn GlobalUnlock(hMem: ?*c_void) c_int;
extern "kernel32" fn GetConsoleWindow() [*c]c_int;
const cf_text_format: c_uint = 13;
const gmem_moveable: c_uint = 2;
fn putInClipboard(allocator: *std.mem.Allocator, utf8: []const u8) !void {
var utf16 = try std.unicode.utf8ToUtf16LeWithNull(allocator, utf8);
defer allocator.free(utf16);
var text: []const u8 = std.mem.sliceAsBytes(utf16);
//std.debug.print("{} utf16 bytes: {x}\n", .{text.len, text});
var ptr = win.GlobalAlloc(win.gmem_moveable, text.len + 2) orelse {
std.debug.warn("Win Error: {}\n", .{win.GetLastError()});
return error.WinError;
};
{
var buf = win.GlobalLock(ptr) orelse {
std.debug.warn("Win Error: {}\n", .{win.GetLastError()});
return error.WinError;
};
@memcpy(@ptrCast([*]u8, buf), text.ptr, text.len + 2);
}
if (win.GlobalUnlock(ptr) == 0) {
if (win.GetLastError() != 0) {
std.debug.warn("Win Error: {}\n", .{win.GetLastError()});
return error.WinError;
}
}
if (win.OpenClipboard(win.GetConsoleWindow().?) == 0) {
std.debug.warn("Win Error: {}\n", .{win.GetLastError()});
return error.WinError;
}
defer _ = win.CloseClipboard();
if (win.EmptyClipboard() == 0) {
std.debug.warn("Win Error: {}\n", .{win.GetLastError()});
return error.WinError;
}
if (win.SetClipboardData(win.cf_text_format, ptr) == null) {
std.debug.warn("Win Error: {}\n", .{win.GetLastError()});
return error.CouldntCopy;
}
}
}; | src/clipboard.zig |
const math = @import("std").math;
const gmath = @import("gmath.zig").gmath(f64);
const sdf2 = @import("sdf2.zig");
const brdf = @import("brdf.zig");
const Jazbz = @import("jabz.zig").Jazbz(f64);
const Circle = @import("geom.zig").Circle;
const Line = @import("geom.zig").Line;
const Quad = @import("geom.zig").Quad;
const V2 = @import("affine.zig").V2;
const V3 = @import("affine.zig").V3;
const v2 = V2.init;
const v3 = V3.init;
const mix = gmath.mix;
const coMix = gmath.coMix;
pub fn shade(object: anytype, preparedMaterial: *const brdf.PreparedMaterial) Jazbz {
const camera = v3(0.5, 0.5, 512);
const view = camera.sub(object.surface).normalize();
const light1 = preparedMaterial.brdf(object.normal, view, v3(0.1, 0.1, 0.5).sub(object.surface).normalize());
const light2 = preparedMaterial.brdf(object.normal, view, v3(0.8, 0.9, 1).sub(object.surface).normalize());
//var fill = light1;
var fill = light1.scaleJ(1).addLight(light2.scaleJ(0.2)).toJazbz();
fill.j = gmath.filmicDynamicRange(0.01, 0.35 * 1.2, 1, 0.50, fill.j); // filmicDynamicRange(blackPoint, whitePoint, sCurveStrength, sCurveSkew, in)
fill.azbz = fill.azbz.mixPow(0, 1, 0.94);
return fill;
}
pub const Sphere = struct {
const Self = @This();
blend: sdf2.Sd,
surface: V3,
normal: V3,
pub fn forCircle(c0: Circle.PointRadius, p: V2) ?Self {
if (circle(c0, p)) |d| {
const x = p.x - c0.p.x;
const y = p.y - c0.p.y;
const r = c0.r;
const z = math.sqrt(r * r - x * x - y * y);
return Self{
.blend = d,
.surface = v3(p.x, p.y, z),
.normal = if (z == 0) v3(0, 0, 1) else v3(x / z, y / z, 1).normalize(),
};
} else {
return null;
}
}
};
pub const Ellipsoid = struct {
const Self = @This();
blend: sdf2.Sd,
surface: V3,
normal: V3,
pub fn forCircle(c0: Circle.PointRadius, depth: f64, p: V2) ?Self {
if (circle(c0, p)) |d| {
// surface x*N.i + y*N.j + (c*sqrt(r**2 - y**2 - x**2))*N.k
// normal (c*x/(sqrt(r**2 - y**2 - x**2)))*N.i + (c*y/(sqrt(r**2 - y**2 - x**2)))*N.j + N.k
const x = p.x - c0.p.x;
const y = p.y - c0.p.y;
const r = c0.r;
const k = math.sqrt(r * r - y * y - x * x);
return Self{
.blend = d,
.surface = v3(p.x, p.y, depth * k),
.normal = if (k == 0) v3(0, 0, 1) else v3(x * depth / k, y * depth / k, 1).normalize(),
};
} else {
return null;
}
}
};
pub const Torus = struct {
const Self = @This();
blend: sdf2.Sd,
surface: V3,
normal: V3,
pub fn forCircle(c0: Circle.PointRadius, r: f64, p: V2) ?Self {
if (doughnut(Circle.rp(c0.r + r, c0.p), Circle.rp(c0.r - r, c0.p), p)) |d| {
// surface x*N.i + y*N.j + (sqrt(-R**2 + 2*R*sqrt(x**2 + y**2) + r**2 - x**2 - y**2))*N.k
// normal (-(R*x/sqrt(x**2 + y**2) - x)/sqrt(-R**2 + 2*R*sqrt(x**2 + y**2) + r**2 - x**2 - y**2))*N.i + (-(R*y/sqrt(x**2 + y**2) - y)/sqrt(-R**2 + 2*R*sqrt(x**2 + y**2) + r**2 - x**2 - y**2))*N.j + N.k
const x = p.x - c0.p.x;
const y = p.y - c0.p.y;
const R = c0.r;
const a = math.sqrt(x * x + y * y);
const z = math.sqrt(-R * R + 2 * R * a + r * r - x * x - y * y);
return Self{
.blend = d,
.surface = v3(p.x, p.y, z),
.normal = if (z == 0 or a == 0) v3(0, 0, 1) else v3(-(R * x / a - x) / z, -(R * y / a - y) / z, 1).normalize(),
};
} else {
return null;
}
}
};
pub const EllipticalTorus = struct {
const Self = @This();
blend: sdf2.Sd,
surface: V3,
normal: V3,
pub fn forCircle(c0: Circle.PointRadius, r: f64, depth: f64, p: V2) ?Self {
if (doughnut(Circle.rp(c0.r + r, c0.p), Circle.rp(c0.r - r, c0.p), p)) |d| {
// surface x*N.i + y*N.j + (depth*sqrt(r**2 - R**2 + 2*R*sqrt(x**2 + y**2) - x**2 - y**2)/r)*N.k
// normal (-depth*(R*x/sqrt(x**2 + y**2) - x)/(r*sqrt(r**2 - R**2 + 2*R*sqrt(x**2 + y**2) - x**2 - y**2)))*N.i + (-depth*(R*y/sqrt(x**2 + y**2) - y)/(r*sqrt(r**2 - R**2 + 2*R*sqrt(x**2 + y**2) - x**2 - y**2))*N.j + N.k
const x = p.x - c0.p.x;
const y = p.y - c0.p.y;
const R = c0.r;
const a = math.sqrt(x * x + y * y);
const b = math.sqrt(r * r - R * R + 2 * R * a - x * x - y * y);
const z = depth * b / r;
return Self{
.blend = d,
.surface = v3(p.x, p.y, z),
.normal = if (a == 0 or b == 0) v3(0, 0, 1) else v3(-depth * (R * x / a - x) / (r * b), -depth * (R * y / a - y) / (r * b), 1).normalize(),
};
} else {
return null;
}
}
};
pub const SlopedBackground = struct {
const Self = @This();
surface: V3,
normal: V3,
pub fn forBounds(z0: f64, z1: f64, p: V2) Self {
// surface x*N.i + y*N.j + (y*z1 + z0*(1 - y))*N.k
// normal (z0 - z1)*N.j + N.k
return Self{
.surface = v3(p.x, p.y, mix(z0, z1, p.y)),
.normal = v3(0, z0 - z1, 1).normalize(),
};
}
};
pub fn doughnut(c0: Circle.PointRadius, c1: Circle.PointRadius, p: V2) ?sdf2.Sd {
const d0 = c0.signedDist(p);
const d1 = c1.signedDist(p);
const d = d0.cut(d1);
if (d.d <= 0) {
return d;
}
return null;
}
pub fn circle(c0: Circle.PointRadius, p: V2) ?sdf2.Sd {
const d0 = c0.signedDist(p);
if (d0.d <= 0) {
return d0;
}
return null;
} | lib/surfacenormal.zig |
const std = @import("std");
const wren = @import("./wren.zig");
const Vm = @import("./vm.zig").Vm;
const Configuration = @import("./vm.zig").Configuration;
pub fn Handle(comptime T: type) type {
return struct {
const Self = @This();
vm: *Vm,
handle: *wren.Handle,
pub fn init(vm: *Vm, handle: *wren.Handle) Self {
return Self{ .vm = vm, .handle = handle };
}
pub fn get(self: *Self, slot_index: u32) T {
comptime const ti = @typeInfo(T);
return switch (ti) {
.Int => {
self.vm.setSlotHandle(T, slot_index, self);
return self.vm.getSlotNumber(T, slot_index);
},
else => @compileError("not a valid handle type"),
};
}
pub fn set(self: *Self, slot_index: u32, value: T) void {
comptime const ti = @typeInfo(T);
switch (ti) {
.Int => {
self.vm.setSlotHandle(T, slot_index, self);
self.vm.setSlot(slot_index, value);
},
else => @compileError("not a valid handle type"),
}
}
};
}
// const EmptyUserData = struct {};
//
// const testing = std.testing;
//
// fn print(vm: *Vm, msg: []const u8) void {
// std.debug.print("{}", .{msg});
// }
//
// test "number handle" {
// var config = Configuration{};
// config.writeFn = print;
// var vm: Vm = undefined;
// try config.newVmInPlace(EmptyUserData, &vm, null);
//
// try vm.interpret("test",
// \\var a = 3
// \\var b = 0
// \\System.print("a = %(a), b = %(b)")
// );
// vm.ensureSlots(2);
// vm.getVariable("test", "a", 0);
// vm.getVariable("test", "b", 1);
// var ha = vm.createHandle(i32, 0);
// var hb = vm.createHandle(i32, 1);
// testing.expectEqual(@as(i32, 3), ha.get(0));
// testing.expectEqual(@as(i32, 0), hb.get(1));
//
// hb.set(1, 5);
// testing.expectEqual(@as(i32, 5), hb.get(1));
// try vm.interpret("test",
// \\System.print("a = %(a), b = %(b)")
// \\b = 5
// \\a = a * b
// \\System.print("a = %(a), b = %(b)")
// );
// vm.ensureSlots(2);
// testing.expectEqual(@as(i32, 15), ha.get(0));
// testing.expectEqual(@as(i32, 5), hb.get(1));
// } | src/zapata/handle.zig |
const std = @import("std");
const expect = std.testing.expect;
const expectError = std.testing.expectError;
const mem = std.mem;
const builtin = @import("builtin");
pub fn foo() anyerror!i32 {
const x = try bar();
return x + 1;
}
pub fn bar() anyerror!i32 {
return 13;
}
pub fn baz() anyerror!i32 {
const y = foo() catch 1234;
return y + 1;
}
test "error wrapping" {
expect((baz() catch unreachable) == 15);
}
fn gimmeItBroke() []const u8 {
return @errorName(error.ItBroke);
}
test "@errorName" {
expect(mem.eql(u8, @errorName(error.AnError), "AnError"));
expect(mem.eql(u8, @errorName(error.ALongerErrorName), "ALongerErrorName"));
}
test "error values" {
const a = @errorToInt(error.err1);
const b = @errorToInt(error.err2);
expect(a != b);
}
test "redefinition of error values allowed" {
shouldBeNotEqual(error.AnError, error.SecondError);
}
fn shouldBeNotEqual(a: anyerror, b: anyerror) void {
if (a == b) unreachable;
}
test "error binary operator" {
const a = errBinaryOperatorG(true) catch 3;
const b = errBinaryOperatorG(false) catch 3;
expect(a == 3);
expect(b == 10);
}
fn errBinaryOperatorG(x: bool) anyerror!isize {
return if (x) error.ItBroke else @as(isize, 10);
}
test "unwrap simple value from error" {
const i = unwrapSimpleValueFromErrorDo() catch unreachable;
expect(i == 13);
}
fn unwrapSimpleValueFromErrorDo() anyerror!isize {
return 13;
}
test "error return in assignment" {
doErrReturnInAssignment() catch unreachable;
}
fn doErrReturnInAssignment() anyerror!void {
var x: i32 = undefined;
x = try makeANonErr();
}
fn makeANonErr() anyerror!i32 {
return 1;
}
test "error union type " {
testErrorUnionType();
comptime testErrorUnionType();
}
fn testErrorUnionType() void {
const x: anyerror!i32 = 1234;
if (x) |value| expect(value == 1234) else |_| unreachable;
expect(@typeId(@TypeOf(x)) == builtin.TypeId.ErrorUnion);
expect(@typeId(@TypeOf(x).ErrorSet) == builtin.TypeId.ErrorSet);
expect(@TypeOf(x).ErrorSet == anyerror);
}
test "error set type" {
testErrorSetType();
comptime testErrorSetType();
}
const MyErrSet = error{
OutOfMemory,
FileNotFound,
};
fn testErrorSetType() void {
expect(@memberCount(MyErrSet) == 2);
const a: MyErrSet!i32 = 5678;
const b: MyErrSet!i32 = MyErrSet.OutOfMemory;
if (a) |value| expect(value == 5678) else |err| switch (err) {
error.OutOfMemory => unreachable,
error.FileNotFound => unreachable,
}
}
test "explicit error set cast" {
testExplicitErrorSetCast(Set1.A);
comptime testExplicitErrorSetCast(Set1.A);
}
const Set1 = error{
A,
B,
};
const Set2 = error{
A,
C,
};
fn testExplicitErrorSetCast(set1: Set1) void {
var x = @errSetCast(Set2, set1);
var y = @errSetCast(Set1, x);
expect(y == error.A);
}
test "comptime test error for empty error set" {
testComptimeTestErrorEmptySet(1234);
comptime testComptimeTestErrorEmptySet(1234);
}
const EmptyErrorSet = error{};
fn testComptimeTestErrorEmptySet(x: EmptyErrorSet!i32) void {
if (x) |v| expect(v == 1234) else |err| @compileError("bad");
}
test "syntax: optional operator in front of error union operator" {
comptime {
expect(?(anyerror!i32) == ?(anyerror!i32));
}
}
test "comptime err to int of error set with only 1 possible value" {
testErrToIntWithOnePossibleValue(error.A, @errorToInt(error.A));
comptime testErrToIntWithOnePossibleValue(error.A, @errorToInt(error.A));
}
fn testErrToIntWithOnePossibleValue(
x: error{A},
comptime value: u32,
) void {
if (@errorToInt(x) != value) {
@compileError("bad");
}
}
test "empty error union" {
const x = error{} || error{};
}
test "error union peer type resolution" {
testErrorUnionPeerTypeResolution(1);
}
fn testErrorUnionPeerTypeResolution(x: i32) void {
const y = switch (x) {
1 => bar_1(),
2 => baz_1(),
else => quux_1(),
};
if (y) |_| {
@panic("expected error");
} else |e| {
expect(e == error.A);
}
}
fn bar_1() anyerror {
return error.A;
}
fn baz_1() !i32 {
return error.B;
}
fn quux_1() !i32 {
return error.C;
}
test "error: fn returning empty error set can be passed as fn returning any error" {
entry();
comptime entry();
}
fn entry() void {
foo2(bar2);
}
fn foo2(f: fn () anyerror!void) void {
const x = f();
}
fn bar2() (error{}!void) {}
test "error: Zero sized error set returned with value payload crash" {
_ = foo3(0) catch {};
_ = comptime foo3(0) catch {};
}
const Error = error{};
fn foo3(b: usize) Error!usize {
return b;
}
test "error: Infer error set from literals" {
_ = nullLiteral("n") catch |err| handleErrors(err);
_ = floatLiteral("n") catch |err| handleErrors(err);
_ = intLiteral("n") catch |err| handleErrors(err);
_ = comptime nullLiteral("n") catch |err| handleErrors(err);
_ = comptime floatLiteral("n") catch |err| handleErrors(err);
_ = comptime intLiteral("n") catch |err| handleErrors(err);
}
fn handleErrors(err: var) noreturn {
switch (err) {
error.T => {},
}
unreachable;
}
fn nullLiteral(str: []const u8) !?i64 {
if (str[0] == 'n') return null;
return error.T;
}
fn floatLiteral(str: []const u8) !?f64 {
if (str[0] == 'n') return 1.0;
return error.T;
}
fn intLiteral(str: []const u8) !?i64 {
if (str[0] == 'n') return 1;
return error.T;
}
test "nested error union function call in optional unwrap" {
const S = struct {
const Foo = struct {
a: i32,
};
fn errorable() !i32 {
var x: Foo = (try getFoo()) orelse return error.Other;
return x.a;
}
fn errorable2() !i32 {
var x: Foo = (try getFoo2()) orelse return error.Other;
return x.a;
}
fn errorable3() !i32 {
var x: Foo = (try getFoo3()) orelse return error.Other;
return x.a;
}
fn getFoo() anyerror!?Foo {
return Foo{ .a = 1234 };
}
fn getFoo2() anyerror!?Foo {
return error.Failure;
}
fn getFoo3() anyerror!?Foo {
return null;
}
};
expect((try S.errorable()) == 1234);
expectError(error.Failure, S.errorable2());
expectError(error.Other, S.errorable3());
comptime {
expect((try S.errorable()) == 1234);
expectError(error.Failure, S.errorable2());
expectError(error.Other, S.errorable3());
}
}
test "widen cast integer payload of error union function call" {
const S = struct {
fn errorable() !u64 {
var x = @as(u64, try number());
return x;
}
fn number() anyerror!u32 {
return 1234;
}
};
expect((try S.errorable()) == 1234);
}
test "return function call to error set from error union function" {
const S = struct {
fn errorable() anyerror!i32 {
return fail();
}
fn fail() anyerror {
return error.Failure;
}
};
expectError(error.Failure, S.errorable());
comptime expectError(error.Failure, S.errorable());
}
test "optional error set is the same size as error set" {
comptime expect(@sizeOf(?anyerror) == @sizeOf(anyerror));
const S = struct {
fn returnsOptErrSet() ?anyerror {
return null;
}
};
expect(S.returnsOptErrSet() == null);
comptime expect(S.returnsOptErrSet() == null);
}
test "debug info for optional error set" {
const SomeError = error{Hello};
var a_local_variable: ?SomeError = null;
}
test "nested catch" {
const S = struct {
fn entry() void {
expectError(error.Bad, func());
}
fn fail() anyerror!Foo {
return error.Wrong;
}
fn func() anyerror!Foo {
const x = fail() catch
fail() catch
return error.Bad;
unreachable;
}
const Foo = struct {
field: i32,
};
};
S.entry();
comptime S.entry();
}
test "implicit cast to optional to error union to return result loc" {
const S = struct {
fn entry() void {
var x: Foo = undefined;
if (func(&x)) |opt| {
expect(opt != null);
} else |_| @panic("expected non error");
}
fn func(f: *Foo) anyerror!?*Foo {
return f;
}
const Foo = struct {
field: i32,
};
};
S.entry();
//comptime S.entry(); TODO
}
test "function pointer with return type that is error union with payload which is pointer of parent struct" {
const S = struct {
const Foo = struct {
fun: fn (a: i32) (anyerror!*Foo),
};
const Err = error{UnspecifiedErr};
fn bar(a: i32) anyerror!*Foo {
return Err.UnspecifiedErr;
}
fn doTheTest() void {
var x = Foo{ .fun = bar };
expectError(error.UnspecifiedErr, x.fun(1));
}
};
S.doTheTest();
}
test "return result loc as peer result loc in inferred error set function" {
const S = struct {
fn doTheTest() void {
if (foo(2)) |x| {
expect(x.Two);
} else |e| switch (e) {
error.Whatever => @panic("fail"),
}
expectError(error.Whatever, foo(99));
}
const FormValue = union(enum) {
One: void,
Two: bool,
};
fn foo(id: u64) !FormValue {
return switch (id) {
2 => FormValue{ .Two = true },
1 => FormValue{ .One = {} },
else => return error.Whatever,
};
}
};
S.doTheTest();
comptime S.doTheTest();
} | test/stage1/behavior/error.zig |
const builtin = @import("builtin");
comptime {
_ = @import("cases/align.zig");
_ = @import("cases/alignof.zig");
_ = @import("cases/array.zig");
_ = @import("cases/asm.zig");
_ = @import("cases/atomics.zig");
_ = @import("cases/bitcast.zig");
_ = @import("cases/bool.zig");
_ = @import("cases/bugs/394.zig");
_ = @import("cases/bugs/655.zig");
_ = @import("cases/bugs/656.zig");
_ = @import("cases/bugs/828.zig");
_ = @import("cases/bugs/920.zig");
_ = @import("cases/bugs/1111.zig");
_ = @import("cases/byval_arg_var.zig");
_ = @import("cases/cast.zig");
_ = @import("cases/const_slice_child.zig");
_ = @import("cases/coroutines.zig");
_ = @import("cases/defer.zig");
_ = @import("cases/enum.zig");
_ = @import("cases/enum_with_members.zig");
_ = @import("cases/error.zig");
_ = @import("cases/eval.zig");
_ = @import("cases/field_parent_ptr.zig");
_ = @import("cases/fn.zig");
_ = @import("cases/fn_in_struct_in_comptime.zig");
_ = @import("cases/for.zig");
_ = @import("cases/generics.zig");
_ = @import("cases/if.zig");
_ = @import("cases/import.zig");
_ = @import("cases/incomplete_struct_param_tld.zig");
_ = @import("cases/ir_block_deps.zig");
_ = @import("cases/math.zig");
_ = @import("cases/merge_error_sets.zig");
_ = @import("cases/misc.zig");
_ = @import("cases/optional.zig");
_ = @import("cases/namespace_depends_on_compile_var/index.zig");
_ = @import("cases/new_stack_call.zig");
_ = @import("cases/null.zig");
_ = @import("cases/pointers.zig");
_ = @import("cases/pub_enum/index.zig");
_ = @import("cases/ref_var_in_if_after_if_2nd_switch_prong.zig");
_ = @import("cases/reflection.zig");
_ = @import("cases/sizeof_and_typeof.zig");
_ = @import("cases/slice.zig");
_ = @import("cases/struct.zig");
_ = @import("cases/struct_contains_null_ptr_itself.zig");
_ = @import("cases/struct_contains_slice_of_itself.zig");
_ = @import("cases/switch.zig");
_ = @import("cases/switch_prong_err_enum.zig");
_ = @import("cases/switch_prong_implicit_cast.zig");
_ = @import("cases/syntax.zig");
_ = @import("cases/this.zig");
_ = @import("cases/try.zig");
_ = @import("cases/type_info.zig");
_ = @import("cases/undefined.zig");
_ = @import("cases/union.zig");
_ = @import("cases/var_args.zig");
_ = @import("cases/void.zig");
_ = @import("cases/while.zig");
_ = @import("cases/widening.zig");
} | test/behavior.zig |
const std = @import("../std.zig");
const assert = std.debug.assert;
const Target = std.Target;
const mem = std.mem;
/// Contains all the same data as `Target`, additionally introducing the concept of "the native target".
/// The purpose of this abstraction is to provide meaningful and unsurprising defaults.
/// This struct does reference any resources and it is copyable.
pub const CrossTarget = struct {
/// `null` means native.
cpu_arch: ?Target.Cpu.Arch = null,
cpu_model: CpuModel = CpuModel.determined_by_cpu_arch,
/// Sparse set of CPU features to add to the set from `cpu_model`.
cpu_features_add: Target.Cpu.Feature.Set = Target.Cpu.Feature.Set.empty,
/// Sparse set of CPU features to remove from the set from `cpu_model`.
cpu_features_sub: Target.Cpu.Feature.Set = Target.Cpu.Feature.Set.empty,
/// `null` means native.
os_tag: ?Target.Os.Tag = null,
/// `null` means the default version range for `os_tag`. If `os_tag` is `null` (native)
/// then `null` for this field means native.
os_version_min: ?OsVersion = null,
/// When cross compiling, `null` means default (latest known OS version).
/// When `os_tag` is native, `null` means equal to the native OS version.
os_version_max: ?OsVersion = null,
/// `null` means default when cross compiling, or native when os_tag is native.
/// If `isGnuLibC()` is `false`, this must be `null` and is ignored.
glibc_version: ?SemVer = null,
/// `null` means the native C ABI, if `os_tag` is native, otherwise it means the default C ABI.
abi: ?Target.Abi = null,
/// When `os_tag` is `null`, then `null` means native. Otherwise it means the standard path
/// based on the `os_tag`.
dynamic_linker: DynamicLinker = DynamicLinker{},
pub const CpuModel = union(enum) {
/// Always native
native,
/// Always baseline
baseline,
/// If CPU Architecture is native, then the CPU model will be native. Otherwise,
/// it will be baseline.
determined_by_cpu_arch,
explicit: *const Target.Cpu.Model,
};
pub const OsVersion = union(enum) {
none: void,
semver: SemVer,
windows: Target.Os.WindowsVersion,
};
pub const SemVer = std.builtin.Version;
pub const DynamicLinker = Target.DynamicLinker;
pub fn fromTarget(target: Target) CrossTarget {
var result: CrossTarget = .{
.cpu_arch = target.cpu.arch,
.cpu_model = .{ .explicit = target.cpu.model },
.os_tag = target.os.tag,
.os_version_min = undefined,
.os_version_max = undefined,
.abi = target.abi,
.glibc_version = if (target.isGnuLibC())
target.os.version_range.linux.glibc
else
null,
};
result.updateOsVersionRange(target.os);
const all_features = target.cpu.arch.allFeaturesList();
var cpu_model_set = target.cpu.model.features;
cpu_model_set.populateDependencies(all_features);
{
// The "add" set is the full set with the CPU Model set removed.
const add_set = &result.cpu_features_add;
add_set.* = target.cpu.features;
add_set.removeFeatureSet(cpu_model_set);
}
{
// The "sub" set is the features that are on in CPU Model set and off in the full set.
const sub_set = &result.cpu_features_sub;
sub_set.* = cpu_model_set;
sub_set.removeFeatureSet(target.cpu.features);
}
return result;
}
fn updateOsVersionRange(self: *CrossTarget, os: Target.Os) void {
switch (os.tag) {
.freestanding,
.ananas,
.cloudabi,
.fuchsia,
.kfreebsd,
.lv2,
.solaris,
.haiku,
.minix,
.rtems,
.nacl,
.cnk,
.aix,
.cuda,
.nvcl,
.amdhsa,
.ps4,
.elfiamcu,
.mesa3d,
.contiki,
.amdpal,
.hermit,
.hurd,
.wasi,
.emscripten,
.uefi,
.other,
=> {
self.os_version_min = .{ .none = {} };
self.os_version_max = .{ .none = {} };
},
.freebsd,
.macosx,
.ios,
.tvos,
.watchos,
.netbsd,
.openbsd,
.dragonfly,
=> {
self.os_version_min = .{ .semver = os.version_range.semver.min };
self.os_version_max = .{ .semver = os.version_range.semver.max };
},
.linux => {
self.os_version_min = .{ .semver = os.version_range.linux.range.min };
self.os_version_max = .{ .semver = os.version_range.linux.range.max };
},
.windows => {
self.os_version_min = .{ .windows = os.version_range.windows.min };
self.os_version_max = .{ .windows = os.version_range.windows.max };
},
}
}
/// TODO deprecated, use `std.zig.system.NativeTargetInfo.detect`.
pub fn toTarget(self: CrossTarget) Target {
return .{
.cpu = self.getCpu(),
.os = self.getOs(),
.abi = self.getAbi(),
};
}
pub const ParseOptions = struct {
/// This is sometimes called a "triple". It looks roughly like this:
/// riscv64-linux-musl
/// The fields are, respectively:
/// * CPU Architecture
/// * Operating System (and optional version range)
/// * C ABI (optional, with optional glibc version)
/// The string "native" can be used for CPU architecture as well as Operating System.
/// If the CPU Architecture is specified as "native", then the Operating System and C ABI may be omitted.
arch_os_abi: []const u8 = "native",
/// Looks like "name+a+b-c-d+e", where "name" is a CPU Model name, "a", "b", and "e"
/// are examples of CPU features to add to the set, and "c" and "d" are examples of CPU features
/// to remove from the set.
/// The following special strings are recognized for CPU Model name:
/// * "baseline" - The "default" set of CPU features for cross-compiling. A conservative set
/// of features that is expected to be supported on most available hardware.
/// * "native" - The native CPU model is to be detected when compiling.
/// If this field is not provided (`null`), then the value will depend on the
/// parsed CPU Architecture. If native, then this will be "native". Otherwise, it will be "baseline".
cpu_features: ?[]const u8 = null,
/// Absolute path to dynamic linker, to override the default, which is either a natively
/// detected path, or a standard path.
dynamic_linker: ?[]const u8 = null,
/// If this is provided, the function will populate some information about parsing failures,
/// so that user-friendly error messages can be delivered.
diagnostics: ?*Diagnostics = null,
pub const Diagnostics = struct {
/// If the architecture was determined, this will be populated.
arch: ?Target.Cpu.Arch = null,
/// If the OS name was determined, this will be populated.
os_name: ?[]const u8 = null,
/// If the OS tag was determined, this will be populated.
os_tag: ?Target.Os.Tag = null,
/// If the ABI was determined, this will be populated.
abi: ?Target.Abi = null,
/// If the CPU name was determined, this will be populated.
cpu_name: ?[]const u8 = null,
/// If error.UnknownCpuFeature is returned, this will be populated.
unknown_feature_name: ?[]const u8 = null,
};
};
pub fn parse(args: ParseOptions) !CrossTarget {
var dummy_diags: ParseOptions.Diagnostics = undefined;
const diags = args.diagnostics orelse &dummy_diags;
var result: CrossTarget = .{
.dynamic_linker = DynamicLinker.init(args.dynamic_linker),
};
var it = mem.separate(args.arch_os_abi, "-");
const arch_name = it.next().?;
const arch_is_native = mem.eql(u8, arch_name, "native");
if (!arch_is_native) {
result.cpu_arch = std.meta.stringToEnum(Target.Cpu.Arch, arch_name) orelse
return error.UnknownArchitecture;
}
const arch = result.getCpuArch();
diags.arch = arch;
if (it.next()) |os_text| {
try parseOs(&result, diags, os_text);
} else if (!arch_is_native) {
return error.MissingOperatingSystem;
}
const opt_abi_text = it.next();
if (opt_abi_text) |abi_text| {
var abi_it = mem.separate(abi_text, ".");
const abi = std.meta.stringToEnum(Target.Abi, abi_it.next().?) orelse
return error.UnknownApplicationBinaryInterface;
result.abi = abi;
diags.abi = abi;
const abi_ver_text = abi_it.rest();
if (abi_it.next() != null) {
if (result.isGnuLibC()) {
result.glibc_version = SemVer.parse(abi_ver_text) catch |err| switch (err) {
error.Overflow => return error.InvalidAbiVersion,
error.InvalidCharacter => return error.InvalidAbiVersion,
error.InvalidVersion => return error.InvalidAbiVersion,
};
} else {
return error.InvalidAbiVersion;
}
}
}
if (it.next() != null) return error.UnexpectedExtraField;
if (args.cpu_features) |cpu_features| {
const all_features = arch.allFeaturesList();
var index: usize = 0;
while (index < cpu_features.len and
cpu_features[index] != '+' and
cpu_features[index] != '-')
{
index += 1;
}
const cpu_name = cpu_features[0..index];
diags.cpu_name = cpu_name;
const add_set = &result.cpu_features_add;
const sub_set = &result.cpu_features_sub;
if (mem.eql(u8, cpu_name, "native")) {
result.cpu_model = .native;
} else if (mem.eql(u8, cpu_name, "baseline")) {
result.cpu_model = .baseline;
} else {
result.cpu_model = .{ .explicit = try arch.parseCpuModel(cpu_name) };
}
while (index < cpu_features.len) {
const op = cpu_features[index];
const set = switch (op) {
'+' => add_set,
'-' => sub_set,
else => unreachable,
};
index += 1;
const start = index;
while (index < cpu_features.len and
cpu_features[index] != '+' and
cpu_features[index] != '-')
{
index += 1;
}
const feature_name = cpu_features[start..index];
for (all_features) |feature, feat_index_usize| {
const feat_index = @intCast(Target.Cpu.Feature.Set.Index, feat_index_usize);
if (mem.eql(u8, feature_name, feature.name)) {
set.addFeature(feat_index);
break;
}
} else {
diags.unknown_feature_name = feature_name;
return error.UnknownCpuFeature;
}
}
}
return result;
}
/// TODO deprecated, use `std.zig.system.NativeTargetInfo.detect`.
pub fn getCpu(self: CrossTarget) Target.Cpu {
switch (self.cpu_model) {
.native => {
// This works when doing `zig build` because Zig generates a build executable using
// native CPU model & features. However this will not be accurate otherwise, and
// will need to be integrated with `std.zig.system.NativeTargetInfo.detect`.
return Target.current.cpu;
},
.baseline => {
var adjusted_baseline = Target.Cpu.baseline(self.getCpuArch());
self.updateCpuFeatures(&adjusted_baseline.features);
return adjusted_baseline;
},
.determined_by_cpu_arch => if (self.cpu_arch == null) {
// This works when doing `zig build` because Zig generates a build executable using
// native CPU model & features. However this will not be accurate otherwise, and
// will need to be integrated with `std.zig.system.NativeTargetInfo.detect`.
return Target.current.cpu;
} else {
var adjusted_baseline = Target.Cpu.baseline(self.getCpuArch());
self.updateCpuFeatures(&adjusted_baseline.features);
return adjusted_baseline;
},
.explicit => |model| {
var adjusted_model = model.toCpu(self.getCpuArch());
self.updateCpuFeatures(&adjusted_model.features);
return adjusted_model;
},
}
}
pub fn getCpuArch(self: CrossTarget) Target.Cpu.Arch {
return self.cpu_arch orelse Target.current.cpu.arch;
}
pub fn getCpuModel(self: CrossTarget) *const Target.Cpu.Model {
return switch (self.cpu_model) {
.explicit => |cpu_model| cpu_model,
else => self.getCpu().model,
};
}
pub fn getCpuFeatures(self: CrossTarget) Target.Cpu.Feature.Set {
return self.getCpu().features;
}
/// TODO deprecated, use `std.zig.system.NativeTargetInfo.detect`.
pub fn getOs(self: CrossTarget) Target.Os {
// `Target.current.os` works when doing `zig build` because Zig generates a build executable using
// native OS version range. However this will not be accurate otherwise, and
// will need to be integrated with `std.zig.system.NativeTargetInfo.detect`.
var adjusted_os = if (self.os_tag) |os_tag| Target.Os.defaultVersionRange(os_tag) else Target.current.os;
if (self.os_version_min) |min| switch (min) {
.none => {},
.semver => |semver| switch (self.getOsTag()) {
.linux => adjusted_os.version_range.linux.range.min = semver,
else => adjusted_os.version_range.semver.min = semver,
},
.windows => |win_ver| adjusted_os.version_range.windows.min = win_ver,
};
if (self.os_version_max) |max| switch (max) {
.none => {},
.semver => |semver| switch (self.getOsTag()) {
.linux => adjusted_os.version_range.linux.range.max = semver,
else => adjusted_os.version_range.semver.max = semver,
},
.windows => |win_ver| adjusted_os.version_range.windows.max = win_ver,
};
if (self.glibc_version) |glibc| {
assert(self.isGnuLibC());
adjusted_os.version_range.linux.glibc = glibc;
}
return adjusted_os;
}
pub fn getOsTag(self: CrossTarget) Target.Os.Tag {
return self.os_tag orelse Target.current.os.tag;
}
/// TODO deprecated, use `std.zig.system.NativeTargetInfo.detect`.
pub fn getOsVersionMin(self: CrossTarget) OsVersion {
if (self.os_version_min) |version_min| return version_min;
var tmp: CrossTarget = undefined;
tmp.updateOsVersionRange(self.getOs());
return tmp.os_version_min.?;
}
/// TODO deprecated, use `std.zig.system.NativeTargetInfo.detect`.
pub fn getOsVersionMax(self: CrossTarget) OsVersion {
if (self.os_version_max) |version_max| return version_max;
var tmp: CrossTarget = undefined;
tmp.updateOsVersionRange(self.getOs());
return tmp.os_version_max.?;
}
/// TODO deprecated, use `std.zig.system.NativeTargetInfo.detect`.
pub fn getAbi(self: CrossTarget) Target.Abi {
if (self.abi) |abi| return abi;
if (self.os_tag == null) {
// This works when doing `zig build` because Zig generates a build executable using
// native CPU model & features. However this will not be accurate otherwise, and
// will need to be integrated with `std.zig.system.NativeTargetInfo.detect`.
return Target.current.abi;
}
return Target.Abi.default(self.getCpuArch(), self.getOs());
}
pub fn isFreeBSD(self: CrossTarget) bool {
return self.getOsTag() == .freebsd;
}
pub fn isDarwin(self: CrossTarget) bool {
return self.getOsTag().isDarwin();
}
pub fn isNetBSD(self: CrossTarget) bool {
return self.getOsTag() == .netbsd;
}
pub fn isUefi(self: CrossTarget) bool {
return self.getOsTag() == .uefi;
}
pub fn isDragonFlyBSD(self: CrossTarget) bool {
return self.getOsTag() == .dragonfly;
}
pub fn isLinux(self: CrossTarget) bool {
return self.getOsTag() == .linux;
}
pub fn isWindows(self: CrossTarget) bool {
return self.getOsTag() == .windows;
}
pub fn oFileExt(self: CrossTarget) [:0]const u8 {
return self.getAbi().oFileExt();
}
pub fn exeFileExt(self: CrossTarget) [:0]const u8 {
return Target.exeFileExtSimple(self.getCpuArch(), self.getOsTag());
}
pub fn staticLibSuffix(self: CrossTarget) [:0]const u8 {
return Target.staticLibSuffix_cpu_arch_abi(self.getCpuArch(), self.getAbi());
}
pub fn dynamicLibSuffix(self: CrossTarget) [:0]const u8 {
return self.getOsTag().dynamicLibSuffix();
}
pub fn libPrefix(self: CrossTarget) [:0]const u8 {
return Target.libPrefix_cpu_arch_abi(self.getCpuArch(), self.getAbi());
}
pub fn isNativeCpu(self: CrossTarget) bool {
return self.cpu_arch == null and
(self.cpu_model == .native or self.cpu_model == .determined_by_cpu_arch) and
self.cpu_features_sub.isEmpty() and self.cpu_features_add.isEmpty();
}
pub fn isNativeOs(self: CrossTarget) bool {
return self.os_tag == null and self.os_version_min == null and self.os_version_max == null and
self.dynamic_linker.get() == null and self.glibc_version == null;
}
pub fn isNative(self: CrossTarget) bool {
return self.isNativeCpu() and self.isNativeOs() and self.abi == null;
}
pub fn zigTriple(self: CrossTarget, allocator: *mem.Allocator) error{OutOfMemory}![]u8 {
if (self.isNative()) {
return mem.dupe(allocator, u8, "native");
}
const arch_name = if (self.cpu_arch) |arch| @tagName(arch) else "native";
const os_name = if (self.os_tag) |os_tag| @tagName(os_tag) else "native";
var result = std.ArrayList(u8).init(allocator);
defer result.deinit();
try result.outStream().print("{}-{}", .{ arch_name, os_name });
// The zig target syntax does not allow specifying a max os version with no min, so
// if either are present, we need the min.
if (self.os_version_min != null or self.os_version_max != null) {
switch (self.getOsVersionMin()) {
.none => {},
.semver => |v| try result.outStream().print(".{}", .{v}),
.windows => |v| try result.outStream().print(".{}", .{@tagName(v)}),
}
}
if (self.os_version_max) |max| {
switch (max) {
.none => {},
.semver => |v| try result.outStream().print("...{}", .{v}),
.windows => |v| try result.outStream().print("...{}", .{@tagName(v)}),
}
}
if (self.glibc_version) |v| {
try result.outStream().print("-{}.{}", .{ @tagName(self.getAbi()), v });
} else if (self.abi) |abi| {
try result.outStream().print("-{}", .{@tagName(abi)});
}
return result.toOwnedSlice();
}
pub fn allocDescription(self: CrossTarget, allocator: *mem.Allocator) ![]u8 {
// TODO is there anything else worthy of the description that is not
// already captured in the triple?
return self.zigTriple(allocator);
}
pub fn linuxTriple(self: CrossTarget, allocator: *mem.Allocator) ![]u8 {
return Target.linuxTripleSimple(allocator, self.getCpuArch(), self.getOsTag(), self.getAbi());
}
pub fn wantSharedLibSymLinks(self: CrossTarget) bool {
return self.getOsTag() != .windows;
}
pub const VcpkgLinkage = std.builtin.LinkMode;
/// Returned slice must be freed by the caller.
pub fn vcpkgTriplet(self: CrossTarget, allocator: *mem.Allocator, linkage: VcpkgLinkage) ![]u8 {
const arch = switch (self.getCpuArch()) {
.i386 => "x86",
.x86_64 => "x64",
.arm,
.armeb,
.thumb,
.thumbeb,
.aarch64_32,
=> "arm",
.aarch64,
.aarch64_be,
=> "arm64",
else => return error.UnsupportedVcpkgArchitecture,
};
const os = switch (self.getOsTag()) {
.windows => "windows",
.linux => "linux",
.macosx => "macos",
else => return error.UnsupportedVcpkgOperatingSystem,
};
const static_suffix = switch (linkage) {
.Static => "-static",
.Dynamic => "",
};
return std.fmt.allocPrint(allocator, "{}-{}{}", .{ arch, os, static_suffix });
}
pub const Executor = union(enum) {
native,
qemu: []const u8,
wine: []const u8,
wasmtime: []const u8,
unavailable,
};
/// Note that even a `CrossTarget` which returns `false` for `isNative` could still be natively executed.
/// For example `-target arm-native` running on an aarch64 host.
pub fn getExternalExecutor(self: CrossTarget) Executor {
const cpu_arch = self.getCpuArch();
const os_tag = self.getOsTag();
const os_match = os_tag == Target.current.os.tag;
// If the OS and CPU arch match, the binary can be considered native.
if (os_match and cpu_arch == Target.current.cpu.arch) {
// However, we also need to verify that the dynamic linker path is valid.
// TODO Until that is implemented, we prevent returning `.native` when the OS is non-native.
if (self.os_tag == null) {
return .native;
}
}
// If the OS matches, we can use QEMU to emulate a foreign architecture.
if (os_match) {
return switch (cpu_arch) {
.aarch64 => Executor{ .qemu = "qemu-aarch64" },
.aarch64_be => Executor{ .qemu = "qemu-aarch64_be" },
.arm => Executor{ .qemu = "qemu-arm" },
.armeb => Executor{ .qemu = "qemu-armeb" },
.i386 => Executor{ .qemu = "qemu-i386" },
.mips => Executor{ .qemu = "qemu-mips" },
.mipsel => Executor{ .qemu = "qemu-mipsel" },
.mips64 => Executor{ .qemu = "qemu-mips64" },
.mips64el => Executor{ .qemu = "qemu-mips64el" },
.powerpc => Executor{ .qemu = "qemu-ppc" },
.powerpc64 => Executor{ .qemu = "qemu-ppc64" },
.powerpc64le => Executor{ .qemu = "qemu-ppc64le" },
.riscv32 => Executor{ .qemu = "qemu-riscv32" },
.riscv64 => Executor{ .qemu = "qemu-riscv64" },
.s390x => Executor{ .qemu = "qemu-s390x" },
.sparc => Executor{ .qemu = "qemu-sparc" },
.x86_64 => Executor{ .qemu = "qemu-x86_64" },
else => return .unavailable,
};
}
switch (os_tag) {
.windows => switch (cpu_arch.ptrBitWidth()) {
32 => return Executor{ .wine = "wine" },
64 => return Executor{ .wine = "wine64" },
else => return .unavailable,
},
.wasi => switch (cpu_arch.ptrBitWidth()) {
32 => return Executor{ .wasmtime = "wasmtime" },
else => return .unavailable,
},
else => return .unavailable,
}
}
pub fn isGnuLibC(self: CrossTarget) bool {
return Target.isGnuLibC_os_tag_abi(self.getOsTag(), self.getAbi());
}
pub fn setGnuLibCVersion(self: *CrossTarget, major: u32, minor: u32, patch: u32) void {
assert(self.isGnuLibC());
self.glibc_version = SemVer{ .major = major, .minor = minor, .patch = patch };
}
pub fn getObjectFormat(self: CrossTarget) Target.ObjectFormat {
return Target.getObjectFormatSimple(self.getOsTag(), self.getCpuArch());
}
fn updateCpuFeatures(self: CrossTarget, set: *Target.Cpu.Feature.Set) void {
set.removeFeatureSet(self.cpu_features_sub);
set.addFeatureSet(self.cpu_features_add);
set.populateDependencies(self.getCpuArch().allFeaturesList());
set.removeFeatureSet(self.cpu_features_sub);
}
fn parseOs(result: *CrossTarget, diags: *ParseOptions.Diagnostics, text: []const u8) !void {
var it = mem.separate(text, ".");
const os_name = it.next().?;
diags.os_name = os_name;
const os_is_native = mem.eql(u8, os_name, "native");
if (!os_is_native) {
result.os_tag = std.meta.stringToEnum(Target.Os.Tag, os_name) orelse
return error.UnknownOperatingSystem;
}
const tag = result.getOsTag();
diags.os_tag = tag;
const version_text = it.rest();
if (it.next() == null) return;
switch (tag) {
.freestanding,
.ananas,
.cloudabi,
.fuchsia,
.kfreebsd,
.lv2,
.solaris,
.haiku,
.minix,
.rtems,
.nacl,
.cnk,
.aix,
.cuda,
.nvcl,
.amdhsa,
.ps4,
.elfiamcu,
.mesa3d,
.contiki,
.amdpal,
.hermit,
.hurd,
.wasi,
.emscripten,
.uefi,
.other,
=> return error.InvalidOperatingSystemVersion,
.freebsd,
.macosx,
.ios,
.tvos,
.watchos,
.netbsd,
.openbsd,
.linux,
.dragonfly,
=> {
var range_it = mem.separate(version_text, "...");
const min_text = range_it.next().?;
const min_ver = SemVer.parse(min_text) catch |err| switch (err) {
error.Overflow => return error.InvalidOperatingSystemVersion,
error.InvalidCharacter => return error.InvalidOperatingSystemVersion,
error.InvalidVersion => return error.InvalidOperatingSystemVersion,
};
result.os_version_min = .{ .semver = min_ver };
const max_text = range_it.next() orelse return;
const max_ver = SemVer.parse(max_text) catch |err| switch (err) {
error.Overflow => return error.InvalidOperatingSystemVersion,
error.InvalidCharacter => return error.InvalidOperatingSystemVersion,
error.InvalidVersion => return error.InvalidOperatingSystemVersion,
};
result.os_version_max = .{ .semver = max_ver };
},
.windows => {
var range_it = mem.separate(version_text, "...");
const min_text = range_it.next().?;
const min_ver = std.meta.stringToEnum(Target.Os.WindowsVersion, min_text) orelse
return error.InvalidOperatingSystemVersion;
result.os_version_min = .{ .windows = min_ver };
const max_text = range_it.next() orelse return;
const max_ver = std.meta.stringToEnum(Target.Os.WindowsVersion, max_text) orelse
return error.InvalidOperatingSystemVersion;
result.os_version_max = .{ .windows = max_ver };
},
}
}
};
test "CrossTarget.parse" {
if (Target.current.isGnuLibC()) {
var cross_target = try CrossTarget.parse(.{});
cross_target.setGnuLibCVersion(2, 1, 1);
const text = try cross_target.zigTriple(std.testing.allocator);
defer std.testing.allocator.free(text);
std.testing.expectEqualSlices(u8, "native-native-gnu.2.1.1", text);
}
{
const cross_target = try CrossTarget.parse(.{
.arch_os_abi = "aarch64-linux",
.cpu_features = "native",
});
std.testing.expect(cross_target.cpu_arch.? == .aarch64);
std.testing.expect(cross_target.cpu_model == .native);
}
{
const cross_target = try CrossTarget.parse(.{ .arch_os_abi = "native" });
std.testing.expect(cross_target.cpu_arch == null);
std.testing.expect(cross_target.isNative());
const text = try cross_target.zigTriple(std.testing.allocator);
defer std.testing.allocator.free(text);
std.testing.expectEqualSlices(u8, "native", text);
}
{
const cross_target = try CrossTarget.parse(.{
.arch_os_abi = "x86_64-linux-gnu",
.cpu_features = "x86_64-sse-sse2-avx-cx8",
});
const target = cross_target.toTarget();
std.testing.expect(target.os.tag == .linux);
std.testing.expect(target.abi == .gnu);
std.testing.expect(target.cpu.arch == .x86_64);
std.testing.expect(!Target.x86.featureSetHas(target.cpu.features, .sse));
std.testing.expect(!Target.x86.featureSetHas(target.cpu.features, .avx));
std.testing.expect(!Target.x86.featureSetHas(target.cpu.features, .cx8));
std.testing.expect(Target.x86.featureSetHas(target.cpu.features, .cmov));
std.testing.expect(Target.x86.featureSetHas(target.cpu.features, .fxsr));
const text = try cross_target.zigTriple(std.testing.allocator);
defer std.testing.allocator.free(text);
std.testing.expectEqualSlices(u8, "x86_64-linux-gnu", text);
}
{
const cross_target = try CrossTarget.parse(.{
.arch_os_abi = "arm-linux-musleabihf",
.cpu_features = "generic+v8a",
});
const target = cross_target.toTarget();
std.testing.expect(target.os.tag == .linux);
std.testing.expect(target.abi == .musleabihf);
std.testing.expect(target.cpu.arch == .arm);
std.testing.expect(target.cpu.model == &Target.arm.cpu.generic);
std.testing.expect(Target.arm.featureSetHas(target.cpu.features, .v8a));
const text = try cross_target.zigTriple(std.testing.allocator);
defer std.testing.allocator.free(text);
std.testing.expectEqualSlices(u8, "arm-linux-musleabihf", text);
}
{
const cross_target = try CrossTarget.parse(.{
.arch_os_abi = "aarch64-linux.3.10...4.4.1-gnu.2.27",
.cpu_features = "generic+v8a",
});
const target = cross_target.toTarget();
std.testing.expect(target.cpu.arch == .aarch64);
std.testing.expect(target.os.tag == .linux);
std.testing.expect(target.os.version_range.linux.range.min.major == 3);
std.testing.expect(target.os.version_range.linux.range.min.minor == 10);
std.testing.expect(target.os.version_range.linux.range.min.patch == 0);
std.testing.expect(target.os.version_range.linux.range.max.major == 4);
std.testing.expect(target.os.version_range.linux.range.max.minor == 4);
std.testing.expect(target.os.version_range.linux.range.max.patch == 1);
std.testing.expect(target.os.version_range.linux.glibc.major == 2);
std.testing.expect(target.os.version_range.linux.glibc.minor == 27);
std.testing.expect(target.os.version_range.linux.glibc.patch == 0);
std.testing.expect(target.abi == .gnu);
const text = try cross_target.zigTriple(std.testing.allocator);
defer std.testing.allocator.free(text);
std.testing.expectEqualSlices(u8, "aarch64-linux.3.10...4.4.1-gnu.2.27", text);
}
} | lib/std/zig/cross_target.zig |
const std = @import("std");
const builtin = @import("builtin");
const expect = std.testing.expect;
const native_endian = builtin.target.cpu.arch.endian();
test "reinterpret bytes as integer with nonzero offset" {
if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO
try testReinterpretBytesAsInteger();
comptime try testReinterpretBytesAsInteger();
}
fn testReinterpretBytesAsInteger() !void {
const bytes = "\x12\x34\x56\x78\xab";
const expected = switch (native_endian) {
.Little => 0xab785634,
.Big => 0x345678ab,
};
try expect(@ptrCast(*align(1) const u32, bytes[1..5]).* == expected);
}
test "reinterpret an array over multiple elements, with no well-defined layout" {
if (builtin.zig_backend == .stage1) return error.SkipZigTest;
if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO
try testReinterpretWithOffsetAndNoWellDefinedLayout();
comptime try testReinterpretWithOffsetAndNoWellDefinedLayout();
}
fn testReinterpretWithOffsetAndNoWellDefinedLayout() !void {
const bytes: ?[5]?u8 = [5]?u8{ 0x12, 0x34, 0x56, 0x78, 0x9a };
const ptr = &bytes.?[1];
const copy: [4]?u8 = @ptrCast(*const [4]?u8, ptr).*;
_ = copy;
//try expect(@ptrCast(*align(1)?u8, bytes[1..5]).* == );
}
test "reinterpret bytes inside auto-layout struct as integer with nonzero offset" {
if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO
try testReinterpretStructWrappedBytesAsInteger();
comptime try testReinterpretStructWrappedBytesAsInteger();
}
fn testReinterpretStructWrappedBytesAsInteger() !void {
const S = struct { bytes: [5:0]u8 };
const obj = S{ .bytes = "\x12\x34\x56\x78\xab".* };
const expected = switch (native_endian) {
.Little => 0xab785634,
.Big => 0x345678ab,
};
try expect(@ptrCast(*align(1) const u32, obj.bytes[1..5]).* == expected);
}
test "reinterpret bytes of an array into an extern struct" {
if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO
try testReinterpretBytesAsExternStruct();
comptime try testReinterpretBytesAsExternStruct();
}
fn testReinterpretBytesAsExternStruct() !void {
var bytes align(2) = [_]u8{ 1, 2, 3, 4, 5, 6 };
const S = extern struct {
a: u8,
b: u16,
c: u8,
};
var ptr = @ptrCast(*const S, &bytes);
var val = ptr.c;
try expect(val == 5);
}
test "reinterpret bytes of an extern struct into another" {
if (builtin.zig_backend == .stage1) return error.SkipZigTest;
if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO
try testReinterpretExternStructAsExternStruct();
comptime try testReinterpretExternStructAsExternStruct();
}
fn testReinterpretExternStructAsExternStruct() !void {
const S1 = extern struct {
a: u8,
b: u16,
c: u8,
};
comptime var bytes align(2) = S1{ .a = 0, .b = 0, .c = 5 };
const S2 = extern struct {
a: u32 align(2),
c: u8,
};
var ptr = @ptrCast(*const S2, &bytes);
var val = ptr.c;
try expect(val == 5);
}
test "lower reinterpreted comptime field ptr" {
if (builtin.zig_backend == .stage1) return error.SkipZigTest;
if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO
// Test lowering a field ptr
comptime var bytes align(2) = [_]u8{ 1, 2, 3, 4, 5, 6 };
const S = extern struct {
a: u32 align(2),
c: u8,
};
comptime var ptr = @ptrCast(*const S, &bytes);
var val = &ptr.c;
try expect(val.* == 5);
// Test lowering an elem ptr
comptime var src_value = S{ .a = 15, .c = 5 };
comptime var ptr2 = @ptrCast(*[@sizeOf(S)]u8, &src_value);
var val2 = &ptr2[4];
try expect(val2.* == 5);
}
test "reinterpret struct field at comptime" {
if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO
const numNative = comptime Bytes.init(0x12345678);
if (native_endian != .Little) {
try expect(std.mem.eql(u8, &[_]u8{ 0x12, 0x34, 0x56, 0x78 }, &numNative.bytes));
} else {
try expect(std.mem.eql(u8, &[_]u8{ 0x78, 0x56, 0x34, 0x12 }, &numNative.bytes));
}
}
const Bytes = struct {
bytes: [4]u8,
pub fn init(v: u32) Bytes {
var res: Bytes = undefined;
@ptrCast(*align(1) u32, &res.bytes).* = v;
return res;
}
};
test "comptime ptrcast keeps larger alignment" {
comptime {
const a: u32 = 1234;
const p = @ptrCast([*]const u8, &a);
try expect(@TypeOf(p) == [*]align(@alignOf(u32)) const u8);
}
}
test "implicit optional pointer to optional anyopaque pointer" {
if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO
var buf: [4]u8 = "aoeu".*;
var x: ?[*]u8 = &buf;
var y: ?*anyopaque = x;
var z = @ptrCast(*[4]u8, y);
try expect(std.mem.eql(u8, z, "aoeu"));
} | test/behavior/ptrcast.zig |
const std = @import("std.zig");
const builtin = @import("builtin");
const math = std.math;
const print = std.debug.print;
pub const FailingAllocator = @import("testing/failing_allocator.zig").FailingAllocator;
/// This should only be used in temporary test programs.
pub const allocator = allocator_instance.allocator();
pub var allocator_instance = std.heap.GeneralPurposeAllocator(.{}){};
pub const failing_allocator = failing_allocator_instance.allocator();
pub var failing_allocator_instance = FailingAllocator.init(base_allocator_instance.allocator(), 0);
pub var base_allocator_instance = std.heap.FixedBufferAllocator.init("");
/// TODO https://github.com/ziglang/zig/issues/5738
pub var log_level = std.log.Level.warn;
/// This is available to any test that wants to execute Zig in a child process.
/// It will be the same executable that is running `zig test`.
pub var zig_exe_path: []const u8 = undefined;
/// This function is intended to be used only in tests. It prints diagnostics to stderr
/// and then returns a test failure error when actual_error_union is not expected_error.
pub fn expectError(expected_error: anyerror, actual_error_union: anytype) !void {
if (actual_error_union) |actual_payload| {
std.debug.print("expected error.{s}, found {any}\n", .{ @errorName(expected_error), actual_payload });
return error.TestUnexpectedError;
} else |actual_error| {
if (expected_error != actual_error) {
std.debug.print("expected error.{s}, found error.{s}\n", .{
@errorName(expected_error),
@errorName(actual_error),
});
return error.TestExpectedError;
}
}
}
/// 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 returns a test failure error.
/// `actual` is casted to the type of `expected`.
pub fn expectEqual(expected: anytype, actual: @TypeOf(expected)) !void {
switch (@typeInfo(@TypeOf(actual))) {
.NoReturn,
.BoundFn,
.Opaque,
.Frame,
.AnyFrame,
=> @compileError("value of type " ++ @typeName(@TypeOf(actual)) ++ " encountered"),
.Undefined,
.Null,
.Void,
=> return,
.Type => {
if (actual != expected) {
std.debug.print("expected type {s}, found type {s}\n", .{ @typeName(expected), @typeName(actual) });
return error.TestExpectedEqual;
}
},
.Bool,
.Int,
.Float,
.ComptimeFloat,
.ComptimeInt,
.EnumLiteral,
.Enum,
.Fn,
.ErrorSet,
=> {
if (actual != expected) {
std.debug.print("expected {}, found {}\n", .{ expected, actual });
return error.TestExpectedEqual;
}
},
.Pointer => |pointer| {
switch (pointer.size) {
.One, .Many, .C => {
if (actual != expected) {
std.debug.print("expected {*}, found {*}\n", .{ expected, actual });
return error.TestExpectedEqual;
}
},
.Slice => {
if (actual.ptr != expected.ptr) {
std.debug.print("expected slice ptr {*}, found {*}\n", .{ expected.ptr, actual.ptr });
return error.TestExpectedEqual;
}
if (actual.len != expected.len) {
std.debug.print("expected slice len {}, found {}\n", .{ expected.len, actual.len });
return error.TestExpectedEqual;
}
},
}
},
.Array => |array| try expectEqualSlices(array.child, &expected, &actual),
.Vector => |info| {
var i: usize = 0;
while (i < info.len) : (i += 1) {
if (!std.meta.eql(expected[i], actual[i])) {
std.debug.print("index {} incorrect. expected {}, found {}\n", .{
i, expected[i], actual[i],
});
return error.TestExpectedEqual;
}
}
},
.Struct => |structType| {
inline for (structType.fields) |field| {
try expectEqual(@field(expected, field.name), @field(actual, field.name));
}
},
.Union => |union_info| {
if (union_info.tag_type == null) {
@compileError("Unable to compare untagged union values");
}
const Tag = std.meta.Tag(@TypeOf(expected));
const expectedTag = @as(Tag, expected);
const actualTag = @as(Tag, actual);
try expectEqual(expectedTag, actualTag);
// we only reach this loop if the tags are equal
inline for (std.meta.fields(@TypeOf(actual))) |fld| {
if (std.mem.eql(u8, fld.name, @tagName(actualTag))) {
try expectEqual(@field(expected, fld.name), @field(actual, fld.name));
return;
}
}
// we iterate over *all* union fields
// => we should never get here as the loop above is
// including all possible values.
unreachable;
},
.Optional => {
if (expected) |expected_payload| {
if (actual) |actual_payload| {
try expectEqual(expected_payload, actual_payload);
} else {
std.debug.print("expected {any}, found null\n", .{expected_payload});
return error.TestExpectedEqual;
}
} else {
if (actual) |actual_payload| {
std.debug.print("expected null, found {any}\n", .{actual_payload});
return error.TestExpectedEqual;
}
}
},
.ErrorUnion => {
if (expected) |expected_payload| {
if (actual) |actual_payload| {
try expectEqual(expected_payload, actual_payload);
} else |actual_err| {
std.debug.print("expected {any}, found {}\n", .{ expected_payload, actual_err });
return error.TestExpectedEqual;
}
} else |expected_err| {
if (actual) |actual_payload| {
std.debug.print("expected {}, found {any}\n", .{ expected_err, actual_payload });
return error.TestExpectedEqual;
} else |actual_err| {
try expectEqual(expected_err, actual_err);
}
}
},
}
}
test "expectEqual.union(enum)" {
const T = union(enum) {
a: i32,
b: f32,
};
const a10 = T{ .a = 10 };
try expectEqual(a10, a10);
}
/// This function is intended to be used only in tests. When the formatted result of the template
/// and its arguments does not equal the expected text, it prints diagnostics to stderr to show how
/// they are not equal, then returns an error.
pub fn expectFmt(expected: []const u8, comptime template: []const u8, args: anytype) !void {
const result = try std.fmt.allocPrint(allocator, template, args);
defer allocator.free(result);
if (std.mem.eql(u8, result, expected)) return;
print("\n====== expected this output: =========\n", .{});
print("{s}", .{expected});
print("\n======== instead found this: =========\n", .{});
print("{s}", .{result});
print("\n======================================\n", .{});
return error.TestExpectedFmt;
}
/// This function is intended to be used only in tests. When the actual value is
/// not approximately equal to the expected value, prints diagnostics to stderr
/// to show exactly how they are not equal, then returns a test failure error.
/// See `math.approxEqAbs` for more informations on the tolerance parameter.
/// The types must be floating point
pub fn expectApproxEqAbs(expected: anytype, actual: @TypeOf(expected), tolerance: @TypeOf(expected)) !void {
const T = @TypeOf(expected);
switch (@typeInfo(T)) {
.Float => if (!math.approxEqAbs(T, expected, actual, tolerance)) {
std.debug.print("actual {}, not within absolute tolerance {} of expected {}\n", .{ actual, tolerance, expected });
return error.TestExpectedApproxEqAbs;
},
.ComptimeFloat => @compileError("Cannot approximately compare two comptime_float values"),
else => @compileError("Unable to compare non floating point values"),
}
}
test "expectApproxEqAbs" {
inline for ([_]type{ f16, f32, f64, f128 }) |T| {
const pos_x: T = 12.0;
const pos_y: T = 12.06;
const neg_x: T = -12.0;
const neg_y: T = -12.06;
try expectApproxEqAbs(pos_x, pos_y, 0.1);
try expectApproxEqAbs(neg_x, neg_y, 0.1);
}
}
/// This function is intended to be used only in tests. When the actual value is
/// not approximately equal to the expected value, prints diagnostics to stderr
/// to show exactly how they are not equal, then returns a test failure error.
/// See `math.approxEqRel` for more informations on the tolerance parameter.
/// The types must be floating point
pub fn expectApproxEqRel(expected: anytype, actual: @TypeOf(expected), tolerance: @TypeOf(expected)) !void {
const T = @TypeOf(expected);
switch (@typeInfo(T)) {
.Float => if (!math.approxEqRel(T, expected, actual, tolerance)) {
std.debug.print("actual {}, not within relative tolerance {} of expected {}\n", .{ actual, tolerance, expected });
return error.TestExpectedApproxEqRel;
},
.ComptimeFloat => @compileError("Cannot approximately compare two comptime_float values"),
else => @compileError("Unable to compare non floating point values"),
}
}
test "expectApproxEqRel" {
inline for ([_]type{ f16, f32, f64, f128 }) |T| {
const eps_value = comptime math.epsilon(T);
const sqrt_eps_value = comptime @sqrt(eps_value);
const pos_x: T = 12.0;
const pos_y: T = pos_x + 2 * eps_value;
const neg_x: T = -12.0;
const neg_y: T = neg_x - 2 * eps_value;
try expectApproxEqRel(pos_x, pos_y, sqrt_eps_value);
try expectApproxEqRel(neg_x, neg_y, sqrt_eps_value);
}
}
/// 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 returns a test failure error.
/// If your inputs are UTF-8 encoded strings, consider calling `expectEqualStrings` instead.
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.print("slice lengths differ. expected {d}, found {d}\n", .{ expected.len, actual.len });
return error.TestExpectedEqual;
}
var i: usize = 0;
while (i < expected.len) : (i += 1) {
if (!std.meta.eql(expected[i], actual[i])) {
std.debug.print("index {} incorrect. expected {any}, found {any}\n", .{ i, expected[i], actual[i] });
return error.TestExpectedEqual;
}
}
}
/// This function is intended to be used only in tests. Checks that two slices or two arrays are equal,
/// including that their sentinel (if any) are the same. Will error if given another type.
pub fn expectEqualSentinel(comptime T: type, comptime sentinel: T, expected: [:sentinel]const T, actual: [:sentinel]const T) !void {
try expectEqualSlices(T, expected, actual);
const expected_value_sentinel = blk: {
switch (@typeInfo(@TypeOf(expected))) {
.Pointer => {
break :blk expected[expected.len];
},
.Array => |array_info| {
const indexable_outside_of_bounds = @as([]const array_info.child, &expected);
break :blk indexable_outside_of_bounds[indexable_outside_of_bounds.len];
},
else => {},
}
};
const actual_value_sentinel = blk: {
switch (@typeInfo(@TypeOf(actual))) {
.Pointer => {
break :blk actual[actual.len];
},
.Array => |array_info| {
const indexable_outside_of_bounds = @as([]const array_info.child, &actual);
break :blk indexable_outside_of_bounds[indexable_outside_of_bounds.len];
},
else => {},
}
};
if (!std.meta.eql(sentinel, expected_value_sentinel)) {
std.debug.print("expectEqualSentinel: 'expected' sentinel in memory is different from its type sentinel. type sentinel {}, in memory sentinel {}\n", .{ sentinel, expected_value_sentinel });
return error.TestExpectedEqual;
}
if (!std.meta.eql(sentinel, actual_value_sentinel)) {
std.debug.print("expectEqualSentinel: 'actual' sentinel in memory is different from its type sentinel. type sentinel {}, in memory sentinel {}\n", .{ sentinel, actual_value_sentinel });
return error.TestExpectedEqual;
}
}
/// This function is intended to be used only in tests.
/// When `ok` is false, returns a test failure error.
pub fn expect(ok: bool) !void {
if (!ok) return error.TestUnexpectedResult;
}
pub const TmpDir = struct {
dir: std.fs.Dir,
parent_dir: std.fs.Dir,
sub_path: [sub_path_len]u8,
const random_bytes_count = 12;
const sub_path_len = std.fs.base64_encoder.calcSize(random_bytes_count);
/// caller owns memory
pub fn getFullPath(self: *TmpDir, alloc: std.mem.Allocator) ![]u8 {
const cwd_str = try std.process.getCwdAlloc(alloc);
defer alloc.free(cwd_str);
const path = try std.fs.path.join(alloc, &[_][]const u8{
cwd_str,
"zig-cache",
"tmp",
&self.sub_path,
});
return path;
}
pub fn cleanup(self: *TmpDir) void {
self.dir.close();
self.parent_dir.deleteTree(&self.sub_path) catch {};
self.parent_dir.close();
self.* = undefined;
}
};
fn getCwdOrWasiPreopen() std.fs.Dir {
if (builtin.os.tag == .wasi and !builtin.link_libc) {
var preopens = std.fs.wasi.PreopenList.init(allocator);
defer preopens.deinit();
preopens.populate(null) catch
@panic("unable to make tmp dir for testing: unable to populate preopens");
const preopen = preopens.find(std.fs.wasi.PreopenType{ .Dir = "." }) orelse
@panic("unable to make tmp dir for testing: didn't find '.' in the preopens");
return std.fs.Dir{ .fd = preopen.fd };
} else {
return std.fs.cwd();
}
}
pub fn tmpDir(opts: std.fs.Dir.OpenDirOptions) TmpDir {
var random_bytes: [TmpDir.random_bytes_count]u8 = undefined;
std.crypto.random.bytes(&random_bytes);
var sub_path: [TmpDir.sub_path_len]u8 = undefined;
_ = std.fs.base64_encoder.encode(&sub_path, &random_bytes);
var cwd = getCwdOrWasiPreopen();
var cache_dir = cwd.makeOpenPath("zig-cache", .{}) catch
@panic("unable to make tmp dir for testing: unable to make and open zig-cache dir");
defer cache_dir.close();
var parent_dir = cache_dir.makeOpenPath("tmp", .{}) catch
@panic("unable to make tmp dir for testing: unable to make and open zig-cache/tmp dir");
var dir = parent_dir.makeOpenPath(&sub_path, opts) catch
@panic("unable to make tmp dir for testing: unable to make and open the tmp dir");
return .{
.dir = dir,
.parent_dir = parent_dir,
.sub_path = sub_path,
};
}
const TestArgs = struct {
testexec: [:0]const u8 = undefined,
zigexec: [:0]const u8 = undefined,
};
/// Get test arguments inside test block by regular test runner ('zig test file.zig')
/// Caller must provide backing ArgIterator
pub fn getTestArgs(it: *std.process.ArgIterator) !TestArgs {
var testargs = TestArgs{};
testargs.testexec = it.next() orelse unreachable;
testargs.zigexec = it.next() orelse unreachable;
try expect(!it.skip());
return testargs;
}
test "getTestArgs" {
var it = try std.process.argsWithAllocator(allocator);
const testargs = try getTestArgs(&it);
defer it.deinit(); // no-op unless WASI or Windows
try expect(testargs.testexec.len > 0); // zig compiler executable path
try expect(testargs.zigexec.len > 0); // test runner executable path
}
/// Spawns child process with 'zigexec build-exe zigfile -femit-bin=binfile'
/// and expects success
pub fn buildExe(zigexec: []const u8, zigfile: []const u8, binfile: []const u8) !void {
const flag_emit = "-femit-bin=";
const cmd_emit = try std.mem.concat(allocator, u8, &[_][]const u8{ flag_emit, binfile });
defer allocator.free(cmd_emit);
const args = [_][]const u8{ zigexec, "build-exe", zigfile, cmd_emit };
var procCompileChild = std.ChildProcess.init(&args, allocator);
try procCompileChild.spawn();
const ret_val = try procCompileChild.wait();
try expectEqual(ret_val, .{ .Exited = 0 });
}
test "expectEqual nested array" {
const a = [2][2]f32{
[_]f32{ 1.0, 0.0 },
[_]f32{ 0.0, 1.0 },
};
const b = [2][2]f32{
[_]f32{ 1.0, 0.0 },
[_]f32{ 0.0, 1.0 },
};
try expectEqual(a, b);
}
test "expectEqual vector" {
var a = @splat(4, @as(u32, 4));
var b = @splat(4, @as(u32, 4));
try expectEqual(a, b);
}
pub fn expectEqualStrings(expected: []const u8, actual: []const u8) !void {
if (std.mem.indexOfDiff(u8, actual, expected)) |diff_index| {
print("\n====== expected this output: =========\n", .{});
printWithVisibleNewlines(expected);
print("\n======== instead found this: =========\n", .{});
printWithVisibleNewlines(actual);
print("\n======================================\n", .{});
var diff_line_number: usize = 1;
for (expected[0..diff_index]) |value| {
if (value == '\n') diff_line_number += 1;
}
print("First difference occurs on line {d}:\n", .{diff_line_number});
print("expected:\n", .{});
printIndicatorLine(expected, diff_index);
print("found:\n", .{});
printIndicatorLine(actual, diff_index);
return error.TestExpectedEqual;
}
}
pub fn expectStringStartsWith(actual: []const u8, expected_starts_with: []const u8) !void {
if (std.mem.startsWith(u8, actual, expected_starts_with))
return;
const shortened_actual = if (actual.len >= expected_starts_with.len)
actual[0..expected_starts_with.len]
else
actual;
print("\n====== expected to start with: =========\n", .{});
printWithVisibleNewlines(expected_starts_with);
print("\n====== instead ended with: ===========\n", .{});
printWithVisibleNewlines(shortened_actual);
print("\n========= full output: ==============\n", .{});
printWithVisibleNewlines(actual);
print("\n======================================\n", .{});
return error.TestExpectedStartsWith;
}
pub fn expectStringEndsWith(actual: []const u8, expected_ends_with: []const u8) !void {
if (std.mem.endsWith(u8, actual, expected_ends_with))
return;
const shortened_actual = if (actual.len >= expected_ends_with.len)
actual[(actual.len - expected_ends_with.len)..]
else
actual;
print("\n====== expected to end with: =========\n", .{});
printWithVisibleNewlines(expected_ends_with);
print("\n====== instead ended with: ===========\n", .{});
printWithVisibleNewlines(shortened_actual);
print("\n========= full output: ==============\n", .{});
printWithVisibleNewlines(actual);
print("\n======================================\n", .{});
return error.TestExpectedEndsWith;
}
fn printIndicatorLine(source: []const u8, indicator_index: usize) void {
const line_begin_index = if (std.mem.lastIndexOfScalar(u8, source[0..indicator_index], '\n')) |line_begin|
line_begin + 1
else
0;
const line_end_index = if (std.mem.indexOfScalar(u8, source[indicator_index..], '\n')) |line_end|
(indicator_index + line_end)
else
source.len;
printLine(source[line_begin_index..line_end_index]);
{
var i: usize = line_begin_index;
while (i < indicator_index) : (i += 1)
print(" ", .{});
}
print("^\n", .{});
}
fn printWithVisibleNewlines(source: []const u8) void {
var i: usize = 0;
while (std.mem.indexOfScalar(u8, source[i..], '\n')) |nl| : (i += nl + 1) {
printLine(source[i .. i + nl]);
}
print("{s}␃\n", .{source[i..]}); // End of Text symbol (ETX)
}
fn printLine(line: []const u8) void {
if (line.len != 0) switch (line[line.len - 1]) {
' ', '\t' => return print("{s}⏎\n", .{line}), // Carriage return symbol,
else => {},
};
print("{s}\n", .{line});
}
test {
try expectEqualStrings("foo", "foo");
}
/// Exhaustively check that allocation failures within `test_fn` are handled without
/// introducing memory leaks. If used with the `testing.allocator` as the `backing_allocator`,
/// it will also be able to detect double frees, etc (when runtime safety is enabled).
///
/// The provided `test_fn` must have a `std.mem.Allocator` as its first argument,
/// and must have a return type of `!void`. Any extra arguments of `test_fn` can
/// be provided via the `extra_args` tuple.
///
/// Any relevant state shared between runs of `test_fn` *must* be reset within `test_fn`.
///
/// Expects that the `test_fn` has a deterministic number of memory allocations
/// (an error will be returned if non-deterministic allocations are detected).
///
/// The strategy employed is to:
/// - Run the test function once to get the total number of allocations.
/// - Then, iterate and run the function X more times, incrementing
/// the failing index each iteration (where X is the total number of
/// allocations determined previously)
///
/// ---
///
/// Here's an example of using a simple test case that will cause a leak when the
/// allocation of `bar` fails (but will pass normally):
///
/// ```zig
/// test {
/// const length: usize = 10;
/// const allocator = std.testing.allocator;
/// var foo = try allocator.alloc(u8, length);
/// var bar = try allocator.alloc(u8, length);
///
/// allocator.free(foo);
/// allocator.free(bar);
/// }
/// ```
///
/// The test case can be converted to something that this function can use by
/// doing:
///
/// ```zig
/// fn testImpl(allocator: std.mem.Allocator, length: usize) !void {
/// var foo = try allocator.alloc(u8, length);
/// var bar = try allocator.alloc(u8, length);
///
/// allocator.free(foo);
/// allocator.free(bar);
/// }
///
/// test {
/// const length: usize = 10;
/// const allocator = std.testing.allocator;
/// try std.testing.checkAllAllocationFailures(allocator, testImpl, .{length});
/// }
/// ```
///
/// Running this test will show that `foo` is leaked when the allocation of
/// `bar` fails. The simplest fix, in this case, would be to use defer like so:
///
/// ```zig
/// fn testImpl(allocator: std.mem.Allocator, length: usize) !void {
/// var foo = try allocator.alloc(u8, length);
/// defer allocator.free(foo);
/// var bar = try allocator.alloc(u8, length);
/// defer allocator.free(bar);
/// }
/// ```
pub fn checkAllAllocationFailures(backing_allocator: std.mem.Allocator, comptime test_fn: anytype, extra_args: anytype) !void {
switch (@typeInfo(@typeInfo(@TypeOf(test_fn)).Fn.return_type.?)) {
.ErrorUnion => |info| {
if (info.payload != void) {
@compileError("Return type must be !void");
}
},
else => @compileError("Return type must be !void"),
}
if (@typeInfo(@TypeOf(extra_args)) != .Struct) {
@compileError("Expected tuple or struct argument, found " ++ @typeName(@TypeOf(extra_args)));
}
const ArgsTuple = std.meta.ArgsTuple(@TypeOf(test_fn));
const fn_args_fields = @typeInfo(ArgsTuple).Struct.fields;
if (fn_args_fields.len == 0 or fn_args_fields[0].field_type != std.mem.Allocator) {
@compileError("The provided function must have an " ++ @typeName(std.mem.Allocator) ++ " as its first argument");
}
const expected_args_tuple_len = fn_args_fields.len - 1;
if (extra_args.len != expected_args_tuple_len) {
@compileError("The provided function expects " ++ (comptime std.fmt.comptimePrint("{d}", .{expected_args_tuple_len})) ++ " extra arguments, but the provided tuple contains " ++ (comptime std.fmt.comptimePrint("{d}", .{extra_args.len})));
}
// Setup the tuple that will actually be used with @call (we'll need to insert
// the failing allocator in field @"0" before each @call)
var args: ArgsTuple = undefined;
inline for (@typeInfo(@TypeOf(extra_args)).Struct.fields) |field, i| {
const expected_type = fn_args_fields[i + 1].field_type;
if (expected_type != field.field_type) {
@compileError("Unexpected type for extra argument at index " ++ (comptime std.fmt.comptimePrint("{d}", .{i})) ++ ": expected " ++ @typeName(expected_type) ++ ", found " ++ @typeName(field.field_type));
}
const arg_i_str = comptime str: {
var str_buf: [100]u8 = undefined;
const args_i = i + 1;
const str_len = std.fmt.formatIntBuf(&str_buf, args_i, 10, .lower, .{});
break :str str_buf[0..str_len];
};
@field(args, arg_i_str) = @field(extra_args, field.name);
}
// Try it once with unlimited memory, make sure it works
const needed_alloc_count = x: {
var failing_allocator_inst = std.testing.FailingAllocator.init(backing_allocator, std.math.maxInt(usize));
args.@"0" = failing_allocator_inst.allocator();
try @call(.{}, test_fn, args);
break :x failing_allocator_inst.index;
};
var fail_index: usize = 0;
while (fail_index < needed_alloc_count) : (fail_index += 1) {
var failing_allocator_inst = std.testing.FailingAllocator.init(backing_allocator, fail_index);
args.@"0" = failing_allocator_inst.allocator();
if (@call(.{}, test_fn, args)) |_| {
return error.NondeterministicMemoryUsage;
} else |err| switch (err) {
error.OutOfMemory => {
if (failing_allocator_inst.allocated_bytes != failing_allocator_inst.freed_bytes) {
print(
"\nfail_index: {d}/{d}\nallocated bytes: {d}\nfreed bytes: {d}\nallocations: {d}\ndeallocations: {d}\n",
.{
fail_index,
needed_alloc_count,
failing_allocator_inst.allocated_bytes,
failing_allocator_inst.freed_bytes,
failing_allocator_inst.allocations,
failing_allocator_inst.deallocations,
},
);
return error.MemoryLeakDetected;
}
},
else => return err,
}
}
}
/// Given a type, reference all the declarations inside, so that the semantic analyzer sees them.
pub fn refAllDecls(comptime T: type) void {
if (!builtin.is_test) return;
inline for (comptime std.meta.declarations(T)) |decl| {
if (decl.is_pub) _ = @field(T, decl.name);
}
} | lib/std/testing.zig |
const std = @import("std");
const liu = @import("src/liu/lib.zig");
const assets = @import("src/assets.zig");
const bld = std.build;
const Arch = std.Target.Cpu.Arch;
const Builder = bld.Builder;
const Mode = std.builtin.Mode;
var mode: Mode = undefined;
const ProgData = struct {
name: []const u8,
output: []const u8,
root: []const u8,
};
fn wasmProgram(b: *Builder, prog: ProgData) *bld.LibExeObjStep {
const vers = b.version(0, 0, 0);
const program = b.addSharedLibrary(prog.name, prog.root, vers);
program.addPackagePath("liu", "src/liu/lib.zig");
program.addPackagePath("assets", "src/assets.zig");
program.setBuildMode(mode);
program.setTarget(.{ .cpu_arch = .wasm32, .os_tag = .freestanding });
// Output straight to static folder by default to make things easier
program.setOutputDir(prog.output);
if (mode != .Debug) {
program.strip = true;
}
program.install();
b.default_step.dependOn(&program.step);
return program;
}
pub fn build(b: *Builder) !void {
// Standard release options allow the person running `zig build` to select
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall.
mode = b.standardReleaseOptions();
// const cache_dir = "./.zig/zig-cache";
// const out_dir = "./.zig/zig-out";
// const cwd = std.fs.cwd();
// try cwd.makePath(cache_dir);
// try cwd.makePath(out_dir ++ "/lib");
// try cwd.makePath(out_dir ++ "/bin");
// try cwd.makePath(out_dir ++ "/include");
// b.install_prefix = try cwd.realpathAlloc(liu.Temp, "./.zig/zig-out");
// b.install_path = try cwd.realpathAlloc(liu.Temp, "./.zig/zig-out");
// b.lib_dir = try cwd.realpathAlloc(liu.Temp, out_dir ++ "/lib");
// b.exe_dir = try cwd.realpathAlloc(liu.Temp, out_dir ++ "/bin");
// b.h_dir = try cwd.realpathAlloc(liu.Temp, out_dir ++ "/include");
// b.dest_dir = try cwd.realpathAlloc(liu.Temp, "./.zig");
// b.cache_root = try cwd.realpathAlloc(liu.Temp, "./.zig/zig-cache");
// b.override_dest_dir = "./.zig";
_ = wasmProgram(b, .{
.name = "kilordle",
.root = "./src/routes/kilordle/kilordle.zig",
.output = "./static/kilordle/",
});
_ = wasmProgram(b, .{
.name = "painter",
.root = "./src/routes/painter/painter.zig",
.output = "./static/painter/",
});
_ = wasmProgram(b, .{
.name = "erlang",
.root = "./src/routes/erlang/erlang.zig",
.output = "./static/erlang/",
});
}
// For running scripts/etc.
pub fn main() !void {
try assets.kilordle.generate();
}
// Experimenting with comptime branch quota
// fn erro() !void {}
// test {
// comptime {
// var i: u32 = 0;
// while (i < 333) : (i += 1) {
// try erro();
// }
// }
// } | build.zig |
const std = @import("std");
const assertOrPanic = std.debug.assertOrPanic;
const builtin = @import("builtin");
const AtomicRmwOp = builtin.AtomicRmwOp;
const AtomicOrder = builtin.AtomicOrder;
test "cmpxchg" {
var x: i32 = 1234;
if (@cmpxchgWeak(i32, &x, 99, 5678, AtomicOrder.SeqCst, AtomicOrder.SeqCst)) |x1| {
assertOrPanic(x1 == 1234);
} else {
@panic("cmpxchg should have failed");
}
while (@cmpxchgWeak(i32, &x, 1234, 5678, AtomicOrder.SeqCst, AtomicOrder.SeqCst)) |x1| {
assertOrPanic(x1 == 1234);
}
assertOrPanic(x == 5678);
assertOrPanic(@cmpxchgStrong(i32, &x, 5678, 42, AtomicOrder.SeqCst, AtomicOrder.SeqCst) == null);
assertOrPanic(x == 42);
}
test "fence" {
var x: i32 = 1234;
@fence(AtomicOrder.SeqCst);
x = 5678;
}
test "atomicrmw and atomicload" {
var data: u8 = 200;
testAtomicRmw(&data);
assertOrPanic(data == 42);
testAtomicLoad(&data);
}
fn testAtomicRmw(ptr: *u8) void {
const prev_value = @atomicRmw(u8, ptr, AtomicRmwOp.Xchg, 42, AtomicOrder.SeqCst);
assertOrPanic(prev_value == 200);
comptime {
var x: i32 = 1234;
const y: i32 = 12345;
assertOrPanic(@atomicLoad(i32, &x, AtomicOrder.SeqCst) == 1234);
assertOrPanic(@atomicLoad(i32, &y, AtomicOrder.SeqCst) == 12345);
}
}
fn testAtomicLoad(ptr: *u8) void {
const x = @atomicLoad(u8, ptr, AtomicOrder.SeqCst);
assertOrPanic(x == 42);
}
test "cmpxchg with ptr" {
var data1: i32 = 1234;
var data2: i32 = 5678;
var data3: i32 = 9101;
var x: *i32 = &data1;
if (@cmpxchgWeak(*i32, &x, &data2, &data3, AtomicOrder.SeqCst, AtomicOrder.SeqCst)) |x1| {
assertOrPanic(x1 == &data1);
} else {
@panic("cmpxchg should have failed");
}
while (@cmpxchgWeak(*i32, &x, &data1, &data3, AtomicOrder.SeqCst, AtomicOrder.SeqCst)) |x1| {
assertOrPanic(x1 == &data1);
}
assertOrPanic(x == &data3);
assertOrPanic(@cmpxchgStrong(*i32, &x, &data3, &data2, AtomicOrder.SeqCst, AtomicOrder.SeqCst) == null);
assertOrPanic(x == &data2);
} | test/stage1/behavior/atomics.zig |
usingnamespace @import("../linux.zig");
/// Routing/device hook
pub const NETLINK_ROUTE = 0;
/// Unused number
pub const NETLINK_UNUSED = 1;
/// Reserved for user mode socket protocols
pub const NETLINK_USERSOCK = 2;
/// Unused number, formerly ip_queue
pub const NETLINK_FIREWALL = 3;
/// socket monitoring
pub const NETLINK_SOCK_DIAG = 4;
/// netfilter/iptables ULOG
pub const NETLINK_NFLOG = 5;
/// ipsec
pub const NETLINK_XFRM = 6;
/// SELinux event notifications
pub const NETLINK_SELINUX = 7;
/// Open-iSCSI
pub const NETLINK_ISCSI = 8;
/// auditing
pub const NETLINK_AUDIT = 9;
pub const NETLINK_FIB_LOOKUP = 10;
pub const NETLINK_CONNECTOR = 11;
/// netfilter subsystem
pub const NETLINK_NETFILTER = 12;
pub const NETLINK_IP6_FW = 13;
/// DECnet routing messages
pub const NETLINK_DNRTMSG = 14;
/// Kernel messages to userspace
pub const NETLINK_KOBJECT_UEVENT = 15;
pub const NETLINK_GENERIC = 16;
// leave room for NETLINK_DM (DM Events)
/// SCSI Transports
pub const NETLINK_SCSITRANSPORT = 18;
pub const NETLINK_ECRYPTFS = 19;
pub const NETLINK_RDMA = 20;
/// Crypto layer
pub const NETLINK_CRYPTO = 21;
/// SMC monitoring
pub const NETLINK_SMC = 22;
// Flags values
/// It is request message.
pub const NLM_F_REQUEST = 0x01;
/// Multipart message, terminated by NLMSG_DONE
pub const NLM_F_MULTI = 0x02;
/// Reply with ack, with zero or error code
pub const NLM_F_ACK = 0x04;
/// Echo this request
pub const NLM_F_ECHO = 0x08;
/// Dump was inconsistent due to sequence change
pub const NLM_F_DUMP_INTR = 0x10;
/// Dump was filtered as requested
pub const NLM_F_DUMP_FILTERED = 0x20;
// Modifiers to GET request
/// specify tree root
pub const NLM_F_ROOT = 0x100;
/// return all matching
pub const NLM_F_MATCH = 0x200;
/// atomic GET
pub const NLM_F_ATOMIC = 0x400;
pub const NLM_F_DUMP = NLM_F_ROOT | NLM_F_MATCH;
// Modifiers to NEW request
/// Override existing
pub const NLM_F_REPLACE = 0x100;
/// Do not touch, if it exists
pub const NLM_F_EXCL = 0x200;
/// Create, if it does not exist
pub const NLM_F_CREATE = 0x400;
/// Add to end of list
pub const NLM_F_APPEND = 0x800;
// Modifiers to DELETE request
/// Do not delete recursively
pub const NLM_F_NONREC = 0x100;
// Flags for ACK message
/// request was capped
pub const NLM_F_CAPPED = 0x100;
/// extended ACK TVLs were included
pub const NLM_F_ACK_TLVS = 0x200;
pub const NetlinkMessageType = extern enum(u16) {
/// Nothing.
NOOP = 0x1,
/// Error
ERROR = 0x2,
/// End of a dump
DONE = 0x3,
/// Data lost
OVERRUN = 0x4,
/// < 0x10: reserved control messages
pub const MIN_TYPE = 0x10;
// rtlink types
RTM_NEWLINK = 16,
RTM_DELLINK,
RTM_GETLINK,
RTM_SETLINK,
RTM_NEWADDR = 20,
RTM_DELADDR,
RTM_GETADDR,
RTM_NEWROUTE = 24,
RTM_DELROUTE,
RTM_GETROUTE,
RTM_NEWNEIGH = 28,
RTM_DELNEIGH,
RTM_GETNEIGH,
RTM_NEWRULE = 32,
RTM_DELRULE,
RTM_GETRULE,
RTM_NEWQDISC = 36,
RTM_DELQDISC,
RTM_GETQDISC,
RTM_NEWTCLASS = 40,
RTM_DELTCLASS,
RTM_GETTCLASS,
RTM_NEWTFILTER = 44,
RTM_DELTFILTER,
RTM_GETTFILTER,
RTM_NEWACTION = 48,
RTM_DELACTION,
RTM_GETACTION,
RTM_NEWPREFIX = 52,
RTM_GETMULTICAST = 58,
RTM_GETANYCAST = 62,
RTM_NEWNEIGHTBL = 64,
RTM_GETNEIGHTBL = 66,
RTM_SETNEIGHTBL,
RTM_NEWNDUSEROPT = 68,
RTM_NEWADDRLABEL = 72,
RTM_DELADDRLABEL,
RTM_GETADDRLABEL,
RTM_GETDCB = 78,
RTM_SETDCB,
RTM_NEWNETCONF = 80,
RTM_DELNETCONF,
RTM_GETNETCONF = 82,
RTM_NEWMDB = 84,
RTM_DELMDB = 85,
RTM_GETMDB = 86,
RTM_NEWNSID = 88,
RTM_DELNSID = 89,
RTM_GETNSID = 90,
RTM_NEWSTATS = 92,
RTM_GETSTATS = 94,
RTM_NEWCACHEREPORT = 96,
RTM_NEWCHAIN = 100,
RTM_DELCHAIN,
RTM_GETCHAIN,
RTM_NEWNEXTHOP = 104,
RTM_DELNEXTHOP,
RTM_GETNEXTHOP,
_,
};
/// Netlink socket address
pub const sockaddr_nl = extern struct {
family: sa_family_t = AF_NETLINK,
__pad1: c_ushort = 0,
/// port ID
pid: u32,
/// multicast groups mask
groups: u32,
};
/// Netlink message header
/// Specified in RFC 3549 Section 2.3.2
pub const nlmsghdr = extern struct {
/// Length of message including header
len: u32,
/// Message content
@"type": NetlinkMessageType,
/// Additional flags
flags: u16,
/// Sequence number
seq: u32,
/// Sending process port ID
pid: u32,
};
pub const ifinfomsg = extern struct {
family: u8,
__pad1: u8 = 0,
/// ARPHRD_*
@"type": c_ushort,
/// Link index
index: c_int,
/// IFF_* flags
flags: c_uint,
/// IFF_* change mask
/// is reserved for future use and should be always set to 0xFFFFFFFF.
change: c_uint = 0xFFFFFFFF,
};
pub const rtattr = extern struct {
/// Length of option
len: c_ushort,
/// Type of option
@"type": IFLA,
pub const ALIGNTO = 4;
};
pub const IFLA = extern enum(c_ushort) {
UNSPEC,
ADDRESS,
BROADCAST,
IFNAME,
MTU,
LINK,
QDISC,
STATS,
COST,
PRIORITY,
MASTER,
/// Wireless Extension event
WIRELESS,
/// Protocol specific information for a link
PROTINFO,
TXQLEN,
MAP,
WEIGHT,
OPERSTATE,
LINKMODE,
LINKINFO,
NET_NS_PID,
IFALIAS,
/// Number of VFs if device is SR-IOV PF
NUM_VF,
VFINFO_LIST,
STATS64,
VF_PORTS,
PORT_SELF,
AF_SPEC,
/// Group the device belongs to
GROUP,
NET_NS_FD,
/// Extended info mask, VFs, etc
EXT_MASK,
/// Promiscuity count: > 0 means acts PROMISC
PROMISCUITY,
NUM_TX_QUEUES,
NUM_RX_QUEUES,
CARRIER,
PHYS_PORT_ID,
CARRIER_CHANGES,
PHYS_SWITCH_ID,
LINK_NETNSID,
PHYS_PORT_NAME,
PROTO_DOWN,
GSO_MAX_SEGS,
GSO_MAX_SIZE,
PAD,
XDP,
EVENT,
NEW_NETNSID,
IF_NETNSID = 46,
TARGET_NETNSID = 46, // new alias
CARRIER_UP_COUNT,
CARRIER_DOWN_COUNT,
NEW_IFINDEX,
MIN_MTU,
MAX_MTU,
_,
};
pub const rtnl_link_ifmap = extern struct {
mem_start: u64,
mem_end: u64,
base_addr: u64,
irq: u16,
dma: u8,
port: u8,
};
pub const rtnl_link_stats = extern struct {
/// total packets received
rx_packets: u32,
/// total packets transmitted
tx_packets: u32,
/// total bytes received
rx_bytes: u32,
/// total bytes transmitted
tx_bytes: u32,
/// bad packets received
rx_errors: u32,
/// packet transmit problems
tx_errors: u32,
/// no space in linux buffers
rx_dropped: u32,
/// no space available in linux
tx_dropped: u32,
/// multicast packets received
multicast: u32,
collisions: u32,
// detailed rx_errors
rx_length_errors: u32,
/// receiver ring buff overflow
rx_over_errors: u32,
/// recved pkt with crc error
rx_crc_errors: u32,
/// recv'd frame alignment error
rx_frame_errors: u32,
/// recv'r fifo overrun
rx_fifo_errors: u32,
/// receiver missed packet
rx_missed_errors: u32,
// detailed tx_errors
tx_aborted_errors: u32,
tx_carrier_errors: u32,
tx_fifo_errors: u32,
tx_heartbeat_errors: u32,
tx_window_errors: u32,
// for cslip etc
rx_compressed: u32,
tx_compressed: u32,
/// dropped, no handler found
rx_nohandler: u32,
};
pub const rtnl_link_stats64 = extern struct {
/// total packets received
rx_packets: u64,
/// total packets transmitted
tx_packets: u64,
/// total bytes received
rx_bytes: u64,
/// total bytes transmitted
tx_bytes: u64,
/// bad packets received
rx_errors: u64,
/// packet transmit problems
tx_errors: u64,
/// no space in linux buffers
rx_dropped: u64,
/// no space available in linux
tx_dropped: u64,
/// multicast packets received
multicast: u64,
collisions: u64,
// detailed rx_errors
rx_length_errors: u64,
/// receiver ring buff overflow
rx_over_errors: u64,
/// recved pkt with crc error
rx_crc_errors: u64,
/// recv'd frame alignment error
rx_frame_errors: u64,
/// recv'r fifo overrun
rx_fifo_errors: u64,
/// receiver missed packet
rx_missed_errors: u64,
// detailed tx_errors
tx_aborted_errors: u64,
tx_carrier_errors: u64,
tx_fifo_errors: u64,
tx_heartbeat_errors: u64,
tx_window_errors: u64,
// for cslip etc
rx_compressed: u64,
tx_compressed: u64,
/// dropped, no handler found
rx_nohandler: u64,
}; | lib/std/os/bits/linux/netlink.zig |
const std = @import("std");
const builtin = @import("builtin");
const liu = @import("liu");
const wasm = liu.wasm;
pub const WasmCommand = void;
pub usingnamespace wasm;
var wordles: []const u8 = undefined;
var wordle_words: []const u8 = undefined;
const ArrayList = std.ArrayList;
const ext = struct {
extern fn setPuzzles(obj: wasm.Obj) void;
extern fn setWordsLeft(count: usize) void;
fn submitWordExt(l0: u8, l1: u8, l2: u8, l3: u8, l4: u8) callconv(.C) bool {
return submitWord([_]u8{ l0, l1, l2, l3, l4 }) catch @panic("submitWord failed");
}
fn initExt(l_wordles: wasm.Obj, l_words: wasm.Obj) callconv(.C) void {
init(l_wordles, l_words) catch @panic("init failed");
}
};
// I think this needs to be in root. I tried moving it inside `ext` and most of
// the code got deleted.
comptime {
@export(ext.initExt, .{ .name = "init", .linkage = .Strong });
@export(ext.submitWordExt, .{ .name = "submitWord", .linkage = .Strong });
}
const Wordle = struct {
text: [5]u8,
matches: [5]Match,
letters_found: u8,
places_found: u8,
};
const Puzzle = struct {
solution: [5]u8,
filled: [5]u8,
submits: []u8,
};
const MatchKind = enum(u8) { none, letter, exact };
const Match = union(MatchKind) {
none: void,
exact: void,
letter: u8,
};
var wordles_left: ArrayList(Wordle) = undefined;
var submissions: ArrayList([5]u8) = undefined;
fn setWordsLeft(count: usize) void {
if (builtin.target.cpu.arch != .wasm32) return;
ext.setWordsLeft(count);
}
fn setPuzzles(puzzles: []Puzzle) void {
if (builtin.target.cpu.arch != .wasm32) return;
const mark = wasm.watermark();
defer wasm.setWatermark(mark);
const arr = wasm.out.array();
const solution_key = wasm.out.string("solution");
const filled_key = wasm.out.string("filled");
const submits_key = wasm.out.string("submits");
for (puzzles) |puzzle| {
const obj = wasm.out.obj();
const solution = wasm.out.string(&puzzle.solution);
const filled = wasm.out.string(&puzzle.filled);
const submits = wasm.out.string(puzzle.submits);
wasm.out.objSet(obj, solution_key, solution);
wasm.out.objSet(obj, filled_key, filled);
wasm.out.objSet(obj, submits_key, submits);
wasm.out.arrayPush(arr, obj);
}
ext.setPuzzles(arr);
}
fn searchList(word: []const u8, dict: []const u8) bool {
var word_index: u32 = 0;
while (word_index < dict.len) : (word_index += 6) {
const dict_slice = dict[word_index..(word_index + 5)];
if (std.mem.eql(u8, word, dict_slice)) {
return true;
}
}
return false;
}
// Returns array of matches. Value v at index i is a match between wordle[i]
// and submission[v], or null if that match doesn't exist.
fn matchWordle(wordle: [5]u8, submission: [5]u8) [5]Match {
var text = submission;
var match = [_]Match{.none} ** 5;
for (wordle) |c, idx| {
if (submission[idx] == c) {
match[idx] = .exact;
text[idx] = 0;
}
}
for (wordle) |c, idx| {
if (match[idx] == .exact) {
continue;
}
for (text) |*slot, text_idx| {
if (slot.* == c) {
match[idx] = .{ .letter = @truncate(u8, text_idx) };
slot.* = 0;
}
}
}
return match;
}
pub fn submitWord(word: [5]u8) !bool {
var _temp = liu.Temp.init();
const temp = _temp.allocator();
defer _temp.deinit();
// lowercase
for (word) |letter| {
if (letter < 'a' or letter > 'z') {
wasm.out.post(.err, "invalid string {s}", .{word});
return false;
}
}
const is_wordle = searchList(&word, wordles);
if (!is_wordle and !searchList(&word, wordle_words)) {
return false;
}
try submissions.append(word);
// We use a buffer that's 1 bigger than what we'll eventually read so
// that we can add to the end and then sort the whole thing. This strategy
// also has the benefit that insertion sort is guaranteed linear time
// over our buffer, since it does one sweep up and then one sweep down.
const top_count = 32;
var top_values = try std.BoundedArray(Wordle, top_count + 1).init(0);
var write_head: u32 = 0;
var read_head: u32 = 0;
const arena_len = wordles_left.items.len;
while (read_head < arena_len) : (read_head += 1) {
const wordle = &wordles_left.items[read_head];
const new_matches = matchWordle(wordle.text, word);
for (new_matches) |new_match, idx| {
const old_match = wordle.matches[idx];
if (@enumToInt(old_match) >= @enumToInt(new_match)) continue;
wordle.matches[idx] = new_match;
if (old_match == .none) wordle.letters_found += 1;
if (new_match == .exact) wordle.places_found += 1;
}
// wordle is done, so we "delete" it by not writing it back to the buffer
if (wordle.places_found >= 5) {
continue;
}
try top_values.append(wordle.*);
std.sort.insertionSort(Wordle, top_values.slice(), {}, compareWordles);
if (top_values.len > top_count) {
_ = top_values.pop();
}
// write-back would be no-op
if (read_head == write_head) {
write_head += 1;
continue;
}
wordles_left.items[write_head] = wordle.*;
write_head += 1;
}
wordles_left.items.len = write_head;
var puzzles = ArrayList(Puzzle).init(temp);
for (top_values.slice()) |wordle| {
var relevant_submits = ArrayList(u8).init(temp);
var matches = [_]Match{.none} ** 5;
// This gets displayed in the app; in debug mode, we output the lowercase
// letter so we can see it in the UI to spot-check math. In release,
// we don't do that, because tha'd be bad.
var filled = if (builtin.mode == .Debug) wordle.text else [_]u8{' '} ** 5;
var found: u32 = 0;
for (wordle.matches) |match, idx| {
if (match == .exact) {
matches[idx] = .exact;
filled[idx] = wordle.text[idx] - 'a' + 'A';
}
}
for (submissions.items) |submit| {
if (found >= 5) {
break;
}
const found_before = found;
var submit_letters = submit;
const new_matches = matchWordle(wordle.text, submit);
for (matches) |*slot, idx| {
switch (slot.*) {
.exact => continue,
.letter => continue,
.none => {},
}
switch (new_matches[idx]) {
.none => continue,
.exact => unreachable,
.letter => |submit_idx| {
// Uppercase means the output text should be orange.
submit_letters[submit_idx] = submit[submit_idx] - 'a' + 'A';
slot.* = .{ .letter = submit_idx };
found += 1;
},
}
}
if (found_before < found) {
try relevant_submits.appendSlice(&submit_letters);
try relevant_submits.append(',');
}
}
if (relevant_submits.items.len > 0) {
_ = relevant_submits.pop();
}
try puzzles.append(.{
.solution = wordle.text,
.filled = filled,
.submits = relevant_submits.items,
});
}
setPuzzles(puzzles.items);
setWordsLeft(wordles_left.items.len);
return true;
}
fn compareWordles(context: void, left: Wordle, right: Wordle) bool {
_ = context;
if (left.places_found != right.places_found) {
return left.places_found > right.places_found;
}
if (left.letters_found != right.letters_found) {
return left.letters_found > right.letters_found;
}
return false;
}
pub fn init(l_wordles: wasm.Obj, l_words: wasm.Obj) !void {
wasm.initIfNecessary();
wordles = try wasm.in.bytes(l_wordles, liu.Pages);
wordle_words = try wasm.in.bytes(l_words, liu.Pages);
wordles_left = ArrayList(Wordle).init(liu.Pages);
submissions = ArrayList([5]u8).init(liu.Pages);
const wordle_count = (wordles.len - 1) / 6 + 1;
try wordles_left.ensureUnusedCapacity(wordle_count);
var word_index: u32 = 0;
while ((word_index + 5) < wordles.len) : (word_index += 6) {
var wordle = Wordle{
.text = undefined,
.matches = .{.none} ** 5,
.letters_found = 0,
.places_found = 0,
};
std.mem.copy(u8, &wordle.text, wordles[word_index..(word_index + 5)]);
wordles_left.appendAssumeCapacity(wordle);
}
setWordsLeft(wordles_left.items.len);
std.log.info("WASM initialized!", .{});
} | src/kilordle.zig |
const std = @import("std");
const io = @import("io.zig");
const Serial = io.Serial;
pub const idt = @import("interrupts/idt.zig");
pub const InterruptFrame = packed struct {
eip: u32,
cs: u32,
eflags: u32,
pub fn print(self: *const @This(), writer: anytype) !void {
const msg =
\\eip {x:0>8}
\\eflags {x:0>8} cs {x:0>8}
\\
;
try writer.print(msg, .{self.eip, self.eflags, self.cs});
}
};
// Structure containing all registers at the state of the interrupt
pub const RegsState = packed struct {
ebp: u32,
edi: u32,
esi: u32,
edx: u32,
ecx: u32,
ebx: u32,
eax: u32,
pub fn print(self: *const @This(), writer: anytype) !void {
const msg =
\\eax {x:0>8} ecx {x:0>8} edx {x:0>8} ebx {x:0>8}
\\esp ???????? ebp {x:0>8} esi {x:0>8} edi {x:0>8}
\\
;
try writer.print(msg, .{
self.eax, self.ecx, self.edx, self.ebx,
self.ebp, self.esi, self.edi,
});
}
};
pub const InterruptContext = packed struct {
n: u32,
error_code: u32,
frame: *InterruptFrame,
regs: *RegsState,
};
pub const InterruptHandler = fn(ctx: *InterruptContext) InterruptError!void;
pub const InterruptError = Serial.SerialError;
var interrupt_table = [_]?InterruptHandler{null}**256;
// Add interrupt handler to table
pub fn add(n: u8, handler: InterruptHandler) void {
interrupt_table[n] = handler;
}
// Remove interrupt handler
pub fn remove(n: u8) void {
interrupt_table[n] = null;
}
// Default interrupt handler
fn default(ctx: *const InterruptContext) InterruptError!void {
const tc = @import("term_color.zig");
const out = Serial.writer();
try out.print(tc.YELLOW, .{});
try out.print("Interrupt: {0d} 0x{0x:0>2}, error: 0x{1x:0>8}",
.{ctx.n, ctx.error_code});
try out.print("\n" ++ tc.RESET, .{});
try out.print("Registers:\n", .{});
try ctx.regs.print(out);
try ctx.frame.print(out);
}
// Handler for all interrupts
export fn interruptRouter(ctx: *InterruptContext) void {
if (interrupt_table[ctx.n]) |handler| {
handler(ctx) catch |err| {
const out = Serial.writer();
out.print("[isr] error at {}: {}\n", .{
handler, err,
}) catch {};
};
}
else {
default(ctx) catch {};
}
} | src/interrupts.zig |
pub const WLX_VERSION_1_0 = @as(u32, 65536);
pub const WLX_VERSION_1_1 = @as(u32, 65537);
pub const WLX_VERSION_1_2 = @as(u32, 65538);
pub const WLX_VERSION_1_3 = @as(u32, 65539);
pub const WLX_VERSION_1_4 = @as(u32, 65540);
pub const WLX_CURRENT_VERSION = @as(u32, 65540);
pub const WLX_SAS_TYPE_TIMEOUT = @as(u32, 0);
pub const WLX_SAS_TYPE_CTRL_ALT_DEL = @as(u32, 1);
pub const WLX_SAS_TYPE_SCRNSVR_TIMEOUT = @as(u32, 2);
pub const WLX_SAS_TYPE_SCRNSVR_ACTIVITY = @as(u32, 3);
pub const WLX_SAS_TYPE_USER_LOGOFF = @as(u32, 4);
pub const WLX_SAS_TYPE_SC_INSERT = @as(u32, 5);
pub const WLX_SAS_TYPE_SC_REMOVE = @as(u32, 6);
pub const WLX_SAS_TYPE_AUTHENTICATED = @as(u32, 7);
pub const WLX_SAS_TYPE_SC_FIRST_READER_ARRIVED = @as(u32, 8);
pub const WLX_SAS_TYPE_SC_LAST_READER_REMOVED = @as(u32, 9);
pub const WLX_SAS_TYPE_SWITCHUSER = @as(u32, 10);
pub const WLX_SAS_TYPE_MAX_MSFT_VALUE = @as(u32, 127);
pub const WLX_LOGON_OPT_NO_PROFILE = @as(u32, 1);
pub const WLX_PROFILE_TYPE_V1_0 = @as(u32, 1);
pub const WLX_PROFILE_TYPE_V2_0 = @as(u32, 2);
pub const WLX_SAS_ACTION_LOGON = @as(u32, 1);
pub const WLX_SAS_ACTION_NONE = @as(u32, 2);
pub const WLX_SAS_ACTION_LOCK_WKSTA = @as(u32, 3);
pub const WLX_SAS_ACTION_LOGOFF = @as(u32, 4);
pub const WLX_SAS_ACTION_PWD_CHANGED = @as(u32, 6);
pub const WLX_SAS_ACTION_TASKLIST = @as(u32, 7);
pub const WLX_SAS_ACTION_UNLOCK_WKSTA = @as(u32, 8);
pub const WLX_SAS_ACTION_FORCE_LOGOFF = @as(u32, 9);
pub const WLX_SAS_ACTION_SHUTDOWN_SLEEP = @as(u32, 12);
pub const WLX_SAS_ACTION_SHUTDOWN_SLEEP2 = @as(u32, 13);
pub const WLX_SAS_ACTION_SHUTDOWN_HIBERNATE = @as(u32, 14);
pub const WLX_SAS_ACTION_RECONNECTED = @as(u32, 15);
pub const WLX_SAS_ACTION_DELAYED_FORCE_LOGOFF = @as(u32, 16);
pub const WLX_SAS_ACTION_SWITCH_CONSOLE = @as(u32, 17);
pub const WLX_WM_SAS = @as(u32, 1625);
pub const WLX_DLG_SAS = @as(u32, 101);
pub const WLX_DLG_INPUT_TIMEOUT = @as(u32, 102);
pub const WLX_DLG_SCREEN_SAVER_TIMEOUT = @as(u32, 103);
pub const WLX_DLG_USER_LOGOFF = @as(u32, 104);
pub const WLX_DIRECTORY_LENGTH = @as(u32, 256);
pub const WLX_CREDENTIAL_TYPE_V1_0 = @as(u32, 1);
pub const WLX_CREDENTIAL_TYPE_V2_0 = @as(u32, 2);
pub const WLX_CONSOLESWITCHCREDENTIAL_TYPE_V1_0 = @as(u32, 1);
pub const STATUSMSG_OPTION_NOANIMATION = @as(u32, 1);
pub const STATUSMSG_OPTION_SETFOREGROUND = @as(u32, 2);
pub const WLX_DESKTOP_NAME = @as(u32, 1);
pub const WLX_DESKTOP_HANDLE = @as(u32, 2);
pub const WLX_CREATE_INSTANCE_ONLY = @as(u32, 1);
pub const WLX_CREATE_USER = @as(u32, 2);
pub const WLX_OPTION_USE_CTRL_ALT_DEL = @as(u32, 1);
pub const WLX_OPTION_CONTEXT_POINTER = @as(u32, 2);
pub const WLX_OPTION_USE_SMART_CARD = @as(u32, 3);
pub const WLX_OPTION_FORCE_LOGOFF_TIME = @as(u32, 4);
pub const WLX_OPTION_IGNORE_AUTO_LOGON = @as(u32, 8);
pub const WLX_OPTION_NO_SWITCH_ON_SAS = @as(u32, 9);
pub const WLX_OPTION_SMART_CARD_PRESENT = @as(u32, 65537);
pub const WLX_OPTION_SMART_CARD_INFO = @as(u32, 65538);
pub const WLX_OPTION_DISPATCH_TABLE_SIZE = @as(u32, 65539);
//--------------------------------------------------------------------------------
// Section: Types (44)
//--------------------------------------------------------------------------------
pub const WLX_SHUTDOWN_TYPE = enum(u32) {
N = 5,
_REBOOT = 11,
_POWER_OFF = 10,
};
pub const WLX_SAS_ACTION_SHUTDOWN = WLX_SHUTDOWN_TYPE.N;
pub const WLX_SAS_ACTION_SHUTDOWN_REBOOT = WLX_SHUTDOWN_TYPE._REBOOT;
pub const WLX_SAS_ACTION_SHUTDOWN_POWER_OFF = WLX_SHUTDOWN_TYPE._POWER_OFF;
pub const WLX_SC_NOTIFICATION_INFO = extern struct {
pszCard: ?PWSTR,
pszReader: ?PWSTR,
pszContainer: ?PWSTR,
pszCryptoProvider: ?PWSTR,
};
pub const WLX_PROFILE_V1_0 = extern struct {
dwType: u32,
pszProfile: ?PWSTR,
};
pub const WLX_PROFILE_V2_0 = extern struct {
dwType: u32,
pszProfile: ?PWSTR,
pszPolicy: ?PWSTR,
pszNetworkDefaultUserProfile: ?PWSTR,
pszServerName: ?PWSTR,
pszEnvironment: ?PWSTR,
};
pub const WLX_MPR_NOTIFY_INFO = extern struct {
pszUserName: ?PWSTR,
pszDomain: ?PWSTR,
pszPassword: ?PWSTR,
pszOldPassword: ?PWSTR,
};
pub const WLX_TERMINAL_SERVICES_DATA = extern struct {
ProfilePath: [257]u16,
HomeDir: [257]u16,
HomeDirDrive: [4]u16,
};
pub const WLX_CLIENT_CREDENTIALS_INFO_V1_0 = extern struct {
dwType: u32,
pszUserName: ?PWSTR,
pszDomain: ?PWSTR,
pszPassword: ?PWSTR,
fPromptForPassword: BOOL,
};
pub const WLX_CLIENT_CREDENTIALS_INFO_V2_0 = extern struct {
dwType: u32,
pszUserName: ?PWSTR,
pszDomain: ?PWSTR,
pszPassword: ?PWSTR,
fPromptForPassword: BOOL,
fDisconnectOnLogonFailure: BOOL,
};
pub const WLX_CONSOLESWITCH_CREDENTIALS_INFO_V1_0 = extern struct {
dwType: u32,
UserToken: ?HANDLE,
LogonId: LUID,
Quotas: QUOTA_LIMITS,
UserName: ?PWSTR,
Domain: ?PWSTR,
LogonTime: LARGE_INTEGER,
SmartCardLogon: BOOL,
ProfileLength: u32,
MessageType: u32,
LogonCount: u16,
BadPasswordCount: u16,
ProfileLogonTime: LARGE_INTEGER,
LogoffTime: LARGE_INTEGER,
KickOffTime: LARGE_INTEGER,
PasswordLastSet: LARGE_INTEGER,
PasswordCanChange: LARGE_INTEGER,
PasswordMustChange: LARGE_INTEGER,
LogonScript: ?PWSTR,
HomeDirectory: ?PWSTR,
FullName: ?PWSTR,
ProfilePath: ?PWSTR,
HomeDirectoryDrive: ?PWSTR,
LogonServer: ?PWSTR,
UserFlags: u32,
PrivateDataLen: u32,
PrivateData: ?*u8,
};
pub const WLX_DESKTOP = extern struct {
Size: u32,
Flags: u32,
hDesktop: ?HDESK,
pszDesktopName: ?PWSTR,
};
pub const PWLX_USE_CTRL_ALT_DEL = fn(
hWlx: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) void;
pub const PWLX_SET_CONTEXT_POINTER = fn(
hWlx: ?HANDLE,
pWlxContext: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) void;
pub const PWLX_SAS_NOTIFY = fn(
hWlx: ?HANDLE,
dwSasType: u32,
) callconv(@import("std").os.windows.WINAPI) void;
pub const PWLX_SET_TIMEOUT = fn(
hWlx: ?HANDLE,
Timeout: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PWLX_ASSIGN_SHELL_PROTECTION = fn(
hWlx: ?HANDLE,
hToken: ?HANDLE,
hProcess: ?HANDLE,
hThread: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const PWLX_MESSAGE_BOX = fn(
hWlx: ?HANDLE,
hwndOwner: ?HWND,
lpszText: ?PWSTR,
lpszTitle: ?PWSTR,
fuStyle: u32,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const PWLX_DIALOG_BOX = fn(
hWlx: ?HANDLE,
hInst: ?HANDLE,
lpszTemplate: ?PWSTR,
hwndOwner: ?HWND,
dlgprc: ?DLGPROC,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const PWLX_DIALOG_BOX_INDIRECT = fn(
hWlx: ?HANDLE,
hInst: ?HANDLE,
hDialogTemplate: ?*DLGTEMPLATE,
hwndOwner: ?HWND,
dlgprc: ?DLGPROC,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const PWLX_DIALOG_BOX_PARAM = fn(
hWlx: ?HANDLE,
hInst: ?HANDLE,
lpszTemplate: ?PWSTR,
hwndOwner: ?HWND,
dlgprc: ?DLGPROC,
dwInitParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const PWLX_DIALOG_BOX_INDIRECT_PARAM = fn(
hWlx: ?HANDLE,
hInst: ?HANDLE,
hDialogTemplate: ?*DLGTEMPLATE,
hwndOwner: ?HWND,
dlgprc: ?DLGPROC,
dwInitParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const PWLX_SWITCH_DESKTOP_TO_USER = fn(
hWlx: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const PWLX_SWITCH_DESKTOP_TO_WINLOGON = fn(
hWlx: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const PWLX_CHANGE_PASSWORD_NOTIFY = fn(
hWlx: ?HANDLE,
pMprInfo: ?*WLX_MPR_NOTIFY_INFO,
dwChangeInfo: u32,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const PWLX_GET_SOURCE_DESKTOP = fn(
hWlx: ?HANDLE,
ppDesktop: ?*?*WLX_DESKTOP,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PWLX_SET_RETURN_DESKTOP = fn(
hWlx: ?HANDLE,
pDesktop: ?*WLX_DESKTOP,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PWLX_CREATE_USER_DESKTOP = fn(
hWlx: ?HANDLE,
hToken: ?HANDLE,
Flags: u32,
pszDesktopName: ?PWSTR,
ppDesktop: ?*?*WLX_DESKTOP,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PWLX_CHANGE_PASSWORD_NOTIFY_EX = fn(
hWlx: ?HANDLE,
pMprInfo: ?*WLX_MPR_NOTIFY_INFO,
dwChangeInfo: u32,
ProviderName: ?PWSTR,
Reserved: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const PWLX_CLOSE_USER_DESKTOP = fn(
hWlx: ?HANDLE,
pDesktop: ?*WLX_DESKTOP,
hToken: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PWLX_SET_OPTION = fn(
hWlx: ?HANDLE,
Option: u32,
Value: usize,
OldValue: ?*usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PWLX_GET_OPTION = fn(
hWlx: ?HANDLE,
Option: u32,
Value: ?*usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PWLX_WIN31_MIGRATE = fn(
hWlx: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) void;
pub const PWLX_QUERY_CLIENT_CREDENTIALS = fn(
pCred: ?*WLX_CLIENT_CREDENTIALS_INFO_V1_0,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PWLX_QUERY_IC_CREDENTIALS = fn(
pCred: ?*WLX_CLIENT_CREDENTIALS_INFO_V1_0,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PWLX_QUERY_TS_LOGON_CREDENTIALS = fn(
pCred: ?*WLX_CLIENT_CREDENTIALS_INFO_V2_0,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PWLX_DISCONNECT = fn(
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PWLX_QUERY_TERMINAL_SERVICES_DATA = fn(
hWlx: ?HANDLE,
pTSData: ?*WLX_TERMINAL_SERVICES_DATA,
UserName: ?PWSTR,
Domain: ?PWSTR,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const PWLX_QUERY_CONSOLESWITCH_CREDENTIALS = fn(
pCred: ?*WLX_CONSOLESWITCH_CREDENTIALS_INFO_V1_0,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const WLX_DISPATCH_VERSION_1_0 = extern struct {
WlxUseCtrlAltDel: ?PWLX_USE_CTRL_ALT_DEL,
WlxSetContextPointer: ?PWLX_SET_CONTEXT_POINTER,
WlxSasNotify: ?PWLX_SAS_NOTIFY,
WlxSetTimeout: ?PWLX_SET_TIMEOUT,
WlxAssignShellProtection: ?PWLX_ASSIGN_SHELL_PROTECTION,
WlxMessageBox: ?PWLX_MESSAGE_BOX,
WlxDialogBox: ?PWLX_DIALOG_BOX,
WlxDialogBoxParam: ?PWLX_DIALOG_BOX_PARAM,
WlxDialogBoxIndirect: ?PWLX_DIALOG_BOX_INDIRECT,
WlxDialogBoxIndirectParam: ?PWLX_DIALOG_BOX_INDIRECT_PARAM,
WlxSwitchDesktopToUser: ?PWLX_SWITCH_DESKTOP_TO_USER,
WlxSwitchDesktopToWinlogon: ?PWLX_SWITCH_DESKTOP_TO_WINLOGON,
WlxChangePasswordNotify: ?PWLX_CHANGE_PASSWORD_NOTIFY,
};
pub const WLX_DISPATCH_VERSION_1_1 = extern struct {
WlxUseCtrlAltDel: ?PWLX_USE_CTRL_ALT_DEL,
WlxSetContextPointer: ?PWLX_SET_CONTEXT_POINTER,
WlxSasNotify: ?PWLX_SAS_NOTIFY,
WlxSetTimeout: ?PWLX_SET_TIMEOUT,
WlxAssignShellProtection: ?PWLX_ASSIGN_SHELL_PROTECTION,
WlxMessageBox: ?PWLX_MESSAGE_BOX,
WlxDialogBox: ?PWLX_DIALOG_BOX,
WlxDialogBoxParam: ?PWLX_DIALOG_BOX_PARAM,
WlxDialogBoxIndirect: ?PWLX_DIALOG_BOX_INDIRECT,
WlxDialogBoxIndirectParam: ?PWLX_DIALOG_BOX_INDIRECT_PARAM,
WlxSwitchDesktopToUser: ?PWLX_SWITCH_DESKTOP_TO_USER,
WlxSwitchDesktopToWinlogon: ?PWLX_SWITCH_DESKTOP_TO_WINLOGON,
WlxChangePasswordNotify: ?PWLX_CHANGE_PASSWORD_NOTIFY,
WlxGetSourceDesktop: ?PWLX_GET_SOURCE_DESKTOP,
WlxSetReturnDesktop: ?PWLX_SET_RETURN_DESKTOP,
WlxCreateUserDesktop: ?PWLX_CREATE_USER_DESKTOP,
WlxChangePasswordNotifyEx: ?PWLX_CHANGE_PASSWORD_NOTIFY_EX,
};
pub const WLX_DISPATCH_VERSION_1_2 = extern struct {
WlxUseCtrlAltDel: ?PWLX_USE_CTRL_ALT_DEL,
WlxSetContextPointer: ?PWLX_SET_CONTEXT_POINTER,
WlxSasNotify: ?PWLX_SAS_NOTIFY,
WlxSetTimeout: ?PWLX_SET_TIMEOUT,
WlxAssignShellProtection: ?PWLX_ASSIGN_SHELL_PROTECTION,
WlxMessageBox: ?PWLX_MESSAGE_BOX,
WlxDialogBox: ?PWLX_DIALOG_BOX,
WlxDialogBoxParam: ?PWLX_DIALOG_BOX_PARAM,
WlxDialogBoxIndirect: ?PWLX_DIALOG_BOX_INDIRECT,
WlxDialogBoxIndirectParam: ?PWLX_DIALOG_BOX_INDIRECT_PARAM,
WlxSwitchDesktopToUser: ?PWLX_SWITCH_DESKTOP_TO_USER,
WlxSwitchDesktopToWinlogon: ?PWLX_SWITCH_DESKTOP_TO_WINLOGON,
WlxChangePasswordNotify: ?PWLX_CHANGE_PASSWORD_NOTIFY,
WlxGetSourceDesktop: ?PWLX_GET_SOURCE_DESKTOP,
WlxSetReturnDesktop: ?PWLX_SET_RETURN_DESKTOP,
WlxCreateUserDesktop: ?PWLX_CREATE_USER_DESKTOP,
WlxChangePasswordNotifyEx: ?PWLX_CHANGE_PASSWORD_NOTIFY_EX,
WlxCloseUserDesktop: ?PWLX_CLOSE_USER_DESKTOP,
};
pub const WLX_DISPATCH_VERSION_1_3 = extern struct {
WlxUseCtrlAltDel: ?PWLX_USE_CTRL_ALT_DEL,
WlxSetContextPointer: ?PWLX_SET_CONTEXT_POINTER,
WlxSasNotify: ?PWLX_SAS_NOTIFY,
WlxSetTimeout: ?PWLX_SET_TIMEOUT,
WlxAssignShellProtection: ?PWLX_ASSIGN_SHELL_PROTECTION,
WlxMessageBox: ?PWLX_MESSAGE_BOX,
WlxDialogBox: ?PWLX_DIALOG_BOX,
WlxDialogBoxParam: ?PWLX_DIALOG_BOX_PARAM,
WlxDialogBoxIndirect: ?PWLX_DIALOG_BOX_INDIRECT,
WlxDialogBoxIndirectParam: ?PWLX_DIALOG_BOX_INDIRECT_PARAM,
WlxSwitchDesktopToUser: ?PWLX_SWITCH_DESKTOP_TO_USER,
WlxSwitchDesktopToWinlogon: ?PWLX_SWITCH_DESKTOP_TO_WINLOGON,
WlxChangePasswordNotify: ?PWLX_CHANGE_PASSWORD_NOTIFY,
WlxGetSourceDesktop: ?PWLX_GET_SOURCE_DESKTOP,
WlxSetReturnDesktop: ?PWLX_SET_RETURN_DESKTOP,
WlxCreateUserDesktop: ?PWLX_CREATE_USER_DESKTOP,
WlxChangePasswordNotifyEx: ?PWLX_CHANGE_PASSWORD_NOTIFY_EX,
WlxCloseUserDesktop: ?PWLX_CLOSE_USER_DESKTOP,
WlxSetOption: ?PWLX_SET_OPTION,
WlxGetOption: ?PWLX_GET_OPTION,
WlxWin31Migrate: ?PWLX_WIN31_MIGRATE,
WlxQueryClientCredentials: ?PWLX_QUERY_CLIENT_CREDENTIALS,
WlxQueryInetConnectorCredentials: ?PWLX_QUERY_IC_CREDENTIALS,
WlxDisconnect: ?PWLX_DISCONNECT,
WlxQueryTerminalServicesData: ?PWLX_QUERY_TERMINAL_SERVICES_DATA,
};
pub const WLX_DISPATCH_VERSION_1_4 = extern struct {
WlxUseCtrlAltDel: ?PWLX_USE_CTRL_ALT_DEL,
WlxSetContextPointer: ?PWLX_SET_CONTEXT_POINTER,
WlxSasNotify: ?PWLX_SAS_NOTIFY,
WlxSetTimeout: ?PWLX_SET_TIMEOUT,
WlxAssignShellProtection: ?PWLX_ASSIGN_SHELL_PROTECTION,
WlxMessageBox: ?PWLX_MESSAGE_BOX,
WlxDialogBox: ?PWLX_DIALOG_BOX,
WlxDialogBoxParam: ?PWLX_DIALOG_BOX_PARAM,
WlxDialogBoxIndirect: ?PWLX_DIALOG_BOX_INDIRECT,
WlxDialogBoxIndirectParam: ?PWLX_DIALOG_BOX_INDIRECT_PARAM,
WlxSwitchDesktopToUser: ?PWLX_SWITCH_DESKTOP_TO_USER,
WlxSwitchDesktopToWinlogon: ?PWLX_SWITCH_DESKTOP_TO_WINLOGON,
WlxChangePasswordNotify: ?PWLX_CHANGE_PASSWORD_NOTIFY,
WlxGetSourceDesktop: ?PWLX_GET_SOURCE_DESKTOP,
WlxSetReturnDesktop: ?PWLX_SET_RETURN_DESKTOP,
WlxCreateUserDesktop: ?PWLX_CREATE_USER_DESKTOP,
WlxChangePasswordNotifyEx: ?PWLX_CHANGE_PASSWORD_NOTIFY_EX,
WlxCloseUserDesktop: ?PWLX_CLOSE_USER_DESKTOP,
WlxSetOption: ?PWLX_SET_OPTION,
WlxGetOption: ?PWLX_GET_OPTION,
WlxWin31Migrate: ?PWLX_WIN31_MIGRATE,
WlxQueryClientCredentials: ?PWLX_QUERY_CLIENT_CREDENTIALS,
WlxQueryInetConnectorCredentials: ?PWLX_QUERY_IC_CREDENTIALS,
WlxDisconnect: ?PWLX_DISCONNECT,
WlxQueryTerminalServicesData: ?PWLX_QUERY_TERMINAL_SERVICES_DATA,
WlxQueryConsoleSwitchCredentials: ?PWLX_QUERY_CONSOLESWITCH_CREDENTIALS,
WlxQueryTsLogonCredentials: ?PWLX_QUERY_TS_LOGON_CREDENTIALS,
};
pub const PFNMSGECALLBACK = fn(
bVerbose: BOOL,
lpMessage: ?PWSTR,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const WLX_NOTIFICATION_INFO = extern struct {
Size: u32,
Flags: u32,
UserName: ?PWSTR,
Domain: ?PWSTR,
WindowStation: ?PWSTR,
hToken: ?HANDLE,
hDesktop: ?HDESK,
pStatusCallback: ?PFNMSGECALLBACK,
};
//--------------------------------------------------------------------------------
// 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 (11)
//--------------------------------------------------------------------------------
const BOOL = @import("../foundation.zig").BOOL;
const DLGPROC = @import("../ui/windows_and_messaging.zig").DLGPROC;
const DLGTEMPLATE = @import("../ui/windows_and_messaging.zig").DLGTEMPLATE;
const HANDLE = @import("../foundation.zig").HANDLE;
const HDESK = @import("../system/stations_and_desktops.zig").HDESK;
const HWND = @import("../foundation.zig").HWND;
const LARGE_INTEGER = @import("../foundation.zig").LARGE_INTEGER;
const LPARAM = @import("../foundation.zig").LPARAM;
const LUID = @import("../foundation.zig").LUID;
const PWSTR = @import("../foundation.zig").PWSTR;
const QUOTA_LIMITS = @import("../security.zig").QUOTA_LIMITS;
test {
// The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476
if (@hasDecl(@This(), "PWLX_USE_CTRL_ALT_DEL")) { _ = PWLX_USE_CTRL_ALT_DEL; }
if (@hasDecl(@This(), "PWLX_SET_CONTEXT_POINTER")) { _ = PWLX_SET_CONTEXT_POINTER; }
if (@hasDecl(@This(), "PWLX_SAS_NOTIFY")) { _ = PWLX_SAS_NOTIFY; }
if (@hasDecl(@This(), "PWLX_SET_TIMEOUT")) { _ = PWLX_SET_TIMEOUT; }
if (@hasDecl(@This(), "PWLX_ASSIGN_SHELL_PROTECTION")) { _ = PWLX_ASSIGN_SHELL_PROTECTION; }
if (@hasDecl(@This(), "PWLX_MESSAGE_BOX")) { _ = PWLX_MESSAGE_BOX; }
if (@hasDecl(@This(), "PWLX_DIALOG_BOX")) { _ = PWLX_DIALOG_BOX; }
if (@hasDecl(@This(), "PWLX_DIALOG_BOX_INDIRECT")) { _ = PWLX_DIALOG_BOX_INDIRECT; }
if (@hasDecl(@This(), "PWLX_DIALOG_BOX_PARAM")) { _ = PWLX_DIALOG_BOX_PARAM; }
if (@hasDecl(@This(), "PWLX_DIALOG_BOX_INDIRECT_PARAM")) { _ = PWLX_DIALOG_BOX_INDIRECT_PARAM; }
if (@hasDecl(@This(), "PWLX_SWITCH_DESKTOP_TO_USER")) { _ = PWLX_SWITCH_DESKTOP_TO_USER; }
if (@hasDecl(@This(), "PWLX_SWITCH_DESKTOP_TO_WINLOGON")) { _ = PWLX_SWITCH_DESKTOP_TO_WINLOGON; }
if (@hasDecl(@This(), "PWLX_CHANGE_PASSWORD_NOTIFY")) { _ = PWLX_CHANGE_PASSWORD_NOTIFY; }
if (@hasDecl(@This(), "PWLX_GET_SOURCE_DESKTOP")) { _ = PWLX_GET_SOURCE_DESKTOP; }
if (@hasDecl(@This(), "PWLX_SET_RETURN_DESKTOP")) { _ = PWLX_SET_RETURN_DESKTOP; }
if (@hasDecl(@This(), "PWLX_CREATE_USER_DESKTOP")) { _ = PWLX_CREATE_USER_DESKTOP; }
if (@hasDecl(@This(), "PWLX_CHANGE_PASSWORD_NOTIFY_EX")) { _ = PWLX_CHANGE_PASSWORD_NOTIFY_EX; }
if (@hasDecl(@This(), "PWLX_CLOSE_USER_DESKTOP")) { _ = PWLX_CLOSE_USER_DESKTOP; }
if (@hasDecl(@This(), "PWLX_SET_OPTION")) { _ = PWLX_SET_OPTION; }
if (@hasDecl(@This(), "PWLX_GET_OPTION")) { _ = PWLX_GET_OPTION; }
if (@hasDecl(@This(), "PWLX_WIN31_MIGRATE")) { _ = PWLX_WIN31_MIGRATE; }
if (@hasDecl(@This(), "PWLX_QUERY_CLIENT_CREDENTIALS")) { _ = PWLX_QUERY_CLIENT_CREDENTIALS; }
if (@hasDecl(@This(), "PWLX_QUERY_IC_CREDENTIALS")) { _ = PWLX_QUERY_IC_CREDENTIALS; }
if (@hasDecl(@This(), "PWLX_QUERY_TS_LOGON_CREDENTIALS")) { _ = PWLX_QUERY_TS_LOGON_CREDENTIALS; }
if (@hasDecl(@This(), "PWLX_DISCONNECT")) { _ = PWLX_DISCONNECT; }
if (@hasDecl(@This(), "PWLX_QUERY_TERMINAL_SERVICES_DATA")) { _ = PWLX_QUERY_TERMINAL_SERVICES_DATA; }
if (@hasDecl(@This(), "PWLX_QUERY_CONSOLESWITCH_CREDENTIALS")) { _ = PWLX_QUERY_CONSOLESWITCH_CREDENTIALS; }
if (@hasDecl(@This(), "PFNMSGECALLBACK")) { _ = PFNMSGECALLBACK; }
@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/security/win_wlx.zig |
pub const _IID_IXmlReader = Guid.initString("7279fc81-709d-4095-b63d-69fe4b0d9030");
pub const _IID_IXmlWriter = Guid.initString("7279fc88-709d-4095-b63d-69fe4b0d9030");
pub const _IID_IXmlResolver = Guid.initString("7279fc82-709d-4095-b63d-69fe4b0d9030");
//--------------------------------------------------------------------------------
// Section: Types (12)
//--------------------------------------------------------------------------------
pub const XmlNodeType = enum(i32) {
XmlNodeType_None = 0,
XmlNodeType_Element = 1,
XmlNodeType_Attribute = 2,
XmlNodeType_Text = 3,
XmlNodeType_CDATA = 4,
XmlNodeType_ProcessingInstruction = 7,
XmlNodeType_Comment = 8,
XmlNodeType_DocumentType = 10,
XmlNodeType_Whitespace = 13,
XmlNodeType_EndElement = 15,
XmlNodeType_XmlDeclaration = 17,
// _XmlNodeType_Last = 17, this enum value conflicts with XmlNodeType_XmlDeclaration
};
pub const XmlNodeType_None = XmlNodeType.XmlNodeType_None;
pub const XmlNodeType_Element = XmlNodeType.XmlNodeType_Element;
pub const XmlNodeType_Attribute = XmlNodeType.XmlNodeType_Attribute;
pub const XmlNodeType_Text = XmlNodeType.XmlNodeType_Text;
pub const XmlNodeType_CDATA = XmlNodeType.XmlNodeType_CDATA;
pub const XmlNodeType_ProcessingInstruction = XmlNodeType.XmlNodeType_ProcessingInstruction;
pub const XmlNodeType_Comment = XmlNodeType.XmlNodeType_Comment;
pub const XmlNodeType_DocumentType = XmlNodeType.XmlNodeType_DocumentType;
pub const XmlNodeType_Whitespace = XmlNodeType.XmlNodeType_Whitespace;
pub const XmlNodeType_EndElement = XmlNodeType.XmlNodeType_EndElement;
pub const XmlNodeType_XmlDeclaration = XmlNodeType.XmlNodeType_XmlDeclaration;
pub const _XmlNodeType_Last = XmlNodeType.XmlNodeType_XmlDeclaration;
pub const XmlConformanceLevel = enum(i32) {
XmlConformanceLevel_Auto = 0,
XmlConformanceLevel_Fragment = 1,
XmlConformanceLevel_Document = 2,
// _XmlConformanceLevel_Last = 2, this enum value conflicts with XmlConformanceLevel_Document
};
pub const XmlConformanceLevel_Auto = XmlConformanceLevel.XmlConformanceLevel_Auto;
pub const XmlConformanceLevel_Fragment = XmlConformanceLevel.XmlConformanceLevel_Fragment;
pub const XmlConformanceLevel_Document = XmlConformanceLevel.XmlConformanceLevel_Document;
pub const _XmlConformanceLevel_Last = XmlConformanceLevel.XmlConformanceLevel_Document;
pub const DtdProcessing = enum(i32) {
DtdProcessing_Prohibit = 0,
DtdProcessing_Parse = 1,
// _DtdProcessing_Last = 1, this enum value conflicts with DtdProcessing_Parse
};
pub const DtdProcessing_Prohibit = DtdProcessing.DtdProcessing_Prohibit;
pub const DtdProcessing_Parse = DtdProcessing.DtdProcessing_Parse;
pub const _DtdProcessing_Last = DtdProcessing.DtdProcessing_Parse;
pub const XmlReadState = enum(i32) {
Initial = 0,
Interactive = 1,
Error = 2,
EndOfFile = 3,
Closed = 4,
};
pub const XmlReadState_Initial = XmlReadState.Initial;
pub const XmlReadState_Interactive = XmlReadState.Interactive;
pub const XmlReadState_Error = XmlReadState.Error;
pub const XmlReadState_EndOfFile = XmlReadState.EndOfFile;
pub const XmlReadState_Closed = XmlReadState.Closed;
pub const XmlReaderProperty = enum(i32) {
XmlReaderProperty_MultiLanguage = 0,
XmlReaderProperty_ConformanceLevel = 1,
XmlReaderProperty_RandomAccess = 2,
XmlReaderProperty_XmlResolver = 3,
XmlReaderProperty_DtdProcessing = 4,
XmlReaderProperty_ReadState = 5,
XmlReaderProperty_MaxElementDepth = 6,
XmlReaderProperty_MaxEntityExpansion = 7,
// _XmlReaderProperty_Last = 7, this enum value conflicts with XmlReaderProperty_MaxEntityExpansion
};
pub const XmlReaderProperty_MultiLanguage = XmlReaderProperty.XmlReaderProperty_MultiLanguage;
pub const XmlReaderProperty_ConformanceLevel = XmlReaderProperty.XmlReaderProperty_ConformanceLevel;
pub const XmlReaderProperty_RandomAccess = XmlReaderProperty.XmlReaderProperty_RandomAccess;
pub const XmlReaderProperty_XmlResolver = XmlReaderProperty.XmlReaderProperty_XmlResolver;
pub const XmlReaderProperty_DtdProcessing = XmlReaderProperty.XmlReaderProperty_DtdProcessing;
pub const XmlReaderProperty_ReadState = XmlReaderProperty.XmlReaderProperty_ReadState;
pub const XmlReaderProperty_MaxElementDepth = XmlReaderProperty.XmlReaderProperty_MaxElementDepth;
pub const XmlReaderProperty_MaxEntityExpansion = XmlReaderProperty.XmlReaderProperty_MaxEntityExpansion;
pub const _XmlReaderProperty_Last = XmlReaderProperty.XmlReaderProperty_MaxEntityExpansion;
pub const XmlError = enum(i32) {
MX_E_MX = -1072894464,
MX_E_INPUTEND = -1072894463,
MX_E_ENCODING = -1072894462,
MX_E_ENCODINGSWITCH = -1072894461,
MX_E_ENCODINGSIGNATURE = -1072894460,
WC_E_WC = -1072894432,
WC_E_WHITESPACE = -1072894431,
WC_E_SEMICOLON = -1072894430,
WC_E_GREATERTHAN = -1072894429,
WC_E_QUOTE = -1072894428,
WC_E_EQUAL = -1072894427,
WC_E_LESSTHAN = -1072894426,
WC_E_HEXDIGIT = -1072894425,
WC_E_DIGIT = -1072894424,
WC_E_LEFTBRACKET = -1072894423,
WC_E_LEFTPAREN = -1072894422,
WC_E_XMLCHARACTER = -1072894421,
WC_E_NAMECHARACTER = -1072894420,
WC_E_SYNTAX = -1072894419,
WC_E_CDSECT = -1072894418,
WC_E_COMMENT = -1072894417,
WC_E_CONDSECT = -1072894416,
WC_E_DECLATTLIST = -1072894415,
WC_E_DECLDOCTYPE = -1072894414,
WC_E_DECLELEMENT = -1072894413,
WC_E_DECLENTITY = -1072894412,
WC_E_DECLNOTATION = -1072894411,
WC_E_NDATA = -1072894410,
WC_E_PUBLIC = -1072894409,
WC_E_SYSTEM = -1072894408,
WC_E_NAME = -1072894407,
WC_E_ROOTELEMENT = -1072894406,
WC_E_ELEMENTMATCH = -1072894405,
WC_E_UNIQUEATTRIBUTE = -1072894404,
WC_E_TEXTXMLDECL = -1072894403,
WC_E_LEADINGXML = -1072894402,
WC_E_TEXTDECL = -1072894401,
WC_E_XMLDECL = -1072894400,
WC_E_ENCNAME = -1072894399,
WC_E_PUBLICID = -1072894398,
WC_E_PESINTERNALSUBSET = -1072894397,
WC_E_PESBETWEENDECLS = -1072894396,
WC_E_NORECURSION = -1072894395,
WC_E_ENTITYCONTENT = -1072894394,
WC_E_UNDECLAREDENTITY = -1072894393,
WC_E_PARSEDENTITY = -1072894392,
WC_E_NOEXTERNALENTITYREF = -1072894391,
WC_E_PI = -1072894390,
WC_E_SYSTEMID = -1072894389,
WC_E_QUESTIONMARK = -1072894388,
WC_E_CDSECTEND = -1072894387,
WC_E_MOREDATA = -1072894386,
WC_E_DTDPROHIBITED = -1072894385,
WC_E_INVALIDXMLSPACE = -1072894384,
NC_E_NC = -1072894368,
NC_E_QNAMECHARACTER = -1072894367,
NC_E_QNAMECOLON = -1072894366,
NC_E_NAMECOLON = -1072894365,
NC_E_DECLAREDPREFIX = -1072894364,
NC_E_UNDECLAREDPREFIX = -1072894363,
NC_E_EMPTYURI = -1072894362,
NC_E_XMLPREFIXRESERVED = -1072894361,
NC_E_XMLNSPREFIXRESERVED = -1072894360,
NC_E_XMLURIRESERVED = -1072894359,
NC_E_XMLNSURIRESERVED = -1072894358,
SC_E_SC = -1072894336,
SC_E_MAXELEMENTDEPTH = -1072894335,
SC_E_MAXENTITYEXPANSION = -1072894334,
WR_E_WR = -1072894208,
WR_E_NONWHITESPACE = -1072894207,
WR_E_NSPREFIXDECLARED = -1072894206,
WR_E_NSPREFIXWITHEMPTYNSURI = -1072894205,
WR_E_DUPLICATEATTRIBUTE = -1072894204,
WR_E_XMLNSPREFIXDECLARATION = -1072894203,
WR_E_XMLPREFIXDECLARATION = -1072894202,
WR_E_XMLURIDECLARATION = -1072894201,
WR_E_XMLNSURIDECLARATION = -1072894200,
WR_E_NAMESPACEUNDECLARED = -1072894199,
WR_E_INVALIDXMLSPACE = -1072894198,
WR_E_INVALIDACTION = -1072894197,
WR_E_INVALIDSURROGATEPAIR = -1072894196,
XML_E_INVALID_DECIMAL = -1072898019,
XML_E_INVALID_HEXIDECIMAL = -1072898018,
XML_E_INVALID_UNICODE = -1072898017,
XML_E_INVALIDENCODING = -1072897938,
};
pub const MX_E_MX = XmlError.MX_E_MX;
pub const MX_E_INPUTEND = XmlError.MX_E_INPUTEND;
pub const MX_E_ENCODING = XmlError.MX_E_ENCODING;
pub const MX_E_ENCODINGSWITCH = XmlError.MX_E_ENCODINGSWITCH;
pub const MX_E_ENCODINGSIGNATURE = XmlError.MX_E_ENCODINGSIGNATURE;
pub const WC_E_WC = XmlError.WC_E_WC;
pub const WC_E_WHITESPACE = XmlError.WC_E_WHITESPACE;
pub const WC_E_SEMICOLON = XmlError.WC_E_SEMICOLON;
pub const WC_E_GREATERTHAN = XmlError.WC_E_GREATERTHAN;
pub const WC_E_QUOTE = XmlError.WC_E_QUOTE;
pub const WC_E_EQUAL = XmlError.WC_E_EQUAL;
pub const WC_E_LESSTHAN = XmlError.WC_E_LESSTHAN;
pub const WC_E_HEXDIGIT = XmlError.WC_E_HEXDIGIT;
pub const WC_E_DIGIT = XmlError.WC_E_DIGIT;
pub const WC_E_LEFTBRACKET = XmlError.WC_E_LEFTBRACKET;
pub const WC_E_LEFTPAREN = XmlError.WC_E_LEFTPAREN;
pub const WC_E_XMLCHARACTER = XmlError.WC_E_XMLCHARACTER;
pub const WC_E_NAMECHARACTER = XmlError.WC_E_NAMECHARACTER;
pub const WC_E_SYNTAX = XmlError.WC_E_SYNTAX;
pub const WC_E_CDSECT = XmlError.WC_E_CDSECT;
pub const WC_E_COMMENT = XmlError.WC_E_COMMENT;
pub const WC_E_CONDSECT = XmlError.WC_E_CONDSECT;
pub const WC_E_DECLATTLIST = XmlError.WC_E_DECLATTLIST;
pub const WC_E_DECLDOCTYPE = XmlError.WC_E_DECLDOCTYPE;
pub const WC_E_DECLELEMENT = XmlError.WC_E_DECLELEMENT;
pub const WC_E_DECLENTITY = XmlError.WC_E_DECLENTITY;
pub const WC_E_DECLNOTATION = XmlError.WC_E_DECLNOTATION;
pub const WC_E_NDATA = XmlError.WC_E_NDATA;
pub const WC_E_PUBLIC = XmlError.WC_E_PUBLIC;
pub const WC_E_SYSTEM = XmlError.WC_E_SYSTEM;
pub const WC_E_NAME = XmlError.WC_E_NAME;
pub const WC_E_ROOTELEMENT = XmlError.WC_E_ROOTELEMENT;
pub const WC_E_ELEMENTMATCH = XmlError.WC_E_ELEMENTMATCH;
pub const WC_E_UNIQUEATTRIBUTE = XmlError.WC_E_UNIQUEATTRIBUTE;
pub const WC_E_TEXTXMLDECL = XmlError.WC_E_TEXTXMLDECL;
pub const WC_E_LEADINGXML = XmlError.WC_E_LEADINGXML;
pub const WC_E_TEXTDECL = XmlError.WC_E_TEXTDECL;
pub const WC_E_XMLDECL = XmlError.WC_E_XMLDECL;
pub const WC_E_ENCNAME = XmlError.WC_E_ENCNAME;
pub const WC_E_PUBLICID = XmlError.WC_E_PUBLICID;
pub const WC_E_PESINTERNALSUBSET = XmlError.WC_E_PESINTERNALSUBSET;
pub const WC_E_PESBETWEENDECLS = XmlError.WC_E_PESBETWEENDECLS;
pub const WC_E_NORECURSION = XmlError.WC_E_NORECURSION;
pub const WC_E_ENTITYCONTENT = XmlError.WC_E_ENTITYCONTENT;
pub const WC_E_UNDECLAREDENTITY = XmlError.WC_E_UNDECLAREDENTITY;
pub const WC_E_PARSEDENTITY = XmlError.WC_E_PARSEDENTITY;
pub const WC_E_NOEXTERNALENTITYREF = XmlError.WC_E_NOEXTERNALENTITYREF;
pub const WC_E_PI = XmlError.WC_E_PI;
pub const WC_E_SYSTEMID = XmlError.WC_E_SYSTEMID;
pub const WC_E_QUESTIONMARK = XmlError.WC_E_QUESTIONMARK;
pub const WC_E_CDSECTEND = XmlError.WC_E_CDSECTEND;
pub const WC_E_MOREDATA = XmlError.WC_E_MOREDATA;
pub const WC_E_DTDPROHIBITED = XmlError.WC_E_DTDPROHIBITED;
pub const WC_E_INVALIDXMLSPACE = XmlError.WC_E_INVALIDXMLSPACE;
pub const NC_E_NC = XmlError.NC_E_NC;
pub const NC_E_QNAMECHARACTER = XmlError.NC_E_QNAMECHARACTER;
pub const NC_E_QNAMECOLON = XmlError.NC_E_QNAMECOLON;
pub const NC_E_NAMECOLON = XmlError.NC_E_NAMECOLON;
pub const NC_E_DECLAREDPREFIX = XmlError.NC_E_DECLAREDPREFIX;
pub const NC_E_UNDECLAREDPREFIX = XmlError.NC_E_UNDECLAREDPREFIX;
pub const NC_E_EMPTYURI = XmlError.NC_E_EMPTYURI;
pub const NC_E_XMLPREFIXRESERVED = XmlError.NC_E_XMLPREFIXRESERVED;
pub const NC_E_XMLNSPREFIXRESERVED = XmlError.NC_E_XMLNSPREFIXRESERVED;
pub const NC_E_XMLURIRESERVED = XmlError.NC_E_XMLURIRESERVED;
pub const NC_E_XMLNSURIRESERVED = XmlError.NC_E_XMLNSURIRESERVED;
pub const SC_E_SC = XmlError.SC_E_SC;
pub const SC_E_MAXELEMENTDEPTH = XmlError.SC_E_MAXELEMENTDEPTH;
pub const SC_E_MAXENTITYEXPANSION = XmlError.SC_E_MAXENTITYEXPANSION;
pub const WR_E_WR = XmlError.WR_E_WR;
pub const WR_E_NONWHITESPACE = XmlError.WR_E_NONWHITESPACE;
pub const WR_E_NSPREFIXDECLARED = XmlError.WR_E_NSPREFIXDECLARED;
pub const WR_E_NSPREFIXWITHEMPTYNSURI = XmlError.WR_E_NSPREFIXWITHEMPTYNSURI;
pub const WR_E_DUPLICATEATTRIBUTE = XmlError.WR_E_DUPLICATEATTRIBUTE;
pub const WR_E_XMLNSPREFIXDECLARATION = XmlError.WR_E_XMLNSPREFIXDECLARATION;
pub const WR_E_XMLPREFIXDECLARATION = XmlError.WR_E_XMLPREFIXDECLARATION;
pub const WR_E_XMLURIDECLARATION = XmlError.WR_E_XMLURIDECLARATION;
pub const WR_E_XMLNSURIDECLARATION = XmlError.WR_E_XMLNSURIDECLARATION;
pub const WR_E_NAMESPACEUNDECLARED = XmlError.WR_E_NAMESPACEUNDECLARED;
pub const WR_E_INVALIDXMLSPACE = XmlError.WR_E_INVALIDXMLSPACE;
pub const WR_E_INVALIDACTION = XmlError.WR_E_INVALIDACTION;
pub const WR_E_INVALIDSURROGATEPAIR = XmlError.WR_E_INVALIDSURROGATEPAIR;
pub const XML_E_INVALID_DECIMAL = XmlError.XML_E_INVALID_DECIMAL;
pub const XML_E_INVALID_HEXIDECIMAL = XmlError.XML_E_INVALID_HEXIDECIMAL;
pub const XML_E_INVALID_UNICODE = XmlError.XML_E_INVALID_UNICODE;
pub const XML_E_INVALIDENCODING = XmlError.XML_E_INVALIDENCODING;
pub const XmlStandalone = enum(i32) {
XmlStandalone_Omit = 0,
XmlStandalone_Yes = 1,
XmlStandalone_No = 2,
// _XmlStandalone_Last = 2, this enum value conflicts with XmlStandalone_No
};
pub const XmlStandalone_Omit = XmlStandalone.XmlStandalone_Omit;
pub const XmlStandalone_Yes = XmlStandalone.XmlStandalone_Yes;
pub const XmlStandalone_No = XmlStandalone.XmlStandalone_No;
pub const _XmlStandalone_Last = XmlStandalone.XmlStandalone_No;
pub const XmlWriterProperty = enum(i32) {
XmlWriterProperty_MultiLanguage = 0,
XmlWriterProperty_Indent = 1,
XmlWriterProperty_ByteOrderMark = 2,
XmlWriterProperty_OmitXmlDeclaration = 3,
XmlWriterProperty_ConformanceLevel = 4,
XmlWriterProperty_CompactEmptyElement = 5,
// _XmlWriterProperty_Last = 5, this enum value conflicts with XmlWriterProperty_CompactEmptyElement
};
pub const XmlWriterProperty_MultiLanguage = XmlWriterProperty.XmlWriterProperty_MultiLanguage;
pub const XmlWriterProperty_Indent = XmlWriterProperty.XmlWriterProperty_Indent;
pub const XmlWriterProperty_ByteOrderMark = XmlWriterProperty.XmlWriterProperty_ByteOrderMark;
pub const XmlWriterProperty_OmitXmlDeclaration = XmlWriterProperty.XmlWriterProperty_OmitXmlDeclaration;
pub const XmlWriterProperty_ConformanceLevel = XmlWriterProperty.XmlWriterProperty_ConformanceLevel;
pub const XmlWriterProperty_CompactEmptyElement = XmlWriterProperty.XmlWriterProperty_CompactEmptyElement;
pub const _XmlWriterProperty_Last = XmlWriterProperty.XmlWriterProperty_CompactEmptyElement;
const IID_IXmlReader_Value = Guid.initString("7279fc81-709d-4095-b63d-69fe4b0d9030");
pub const IID_IXmlReader = &IID_IXmlReader_Value;
pub const IXmlReader = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetInput: fn(
self: *const IXmlReader,
pInput: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetProperty: fn(
self: *const IXmlReader,
nProperty: u32,
ppValue: ?*isize,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetProperty: fn(
self: *const IXmlReader,
nProperty: u32,
pValue: isize,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Read: fn(
self: *const IXmlReader,
pNodeType: ?*XmlNodeType,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetNodeType: fn(
self: *const IXmlReader,
pNodeType: ?*XmlNodeType,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
MoveToFirstAttribute: fn(
self: *const IXmlReader,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
MoveToNextAttribute: fn(
self: *const IXmlReader,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
MoveToAttributeByName: fn(
self: *const IXmlReader,
pwszLocalName: ?[*:0]const u16,
pwszNamespaceUri: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
MoveToElement: fn(
self: *const IXmlReader,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetQualifiedName: fn(
self: *const IXmlReader,
ppwszQualifiedName: ?*?PWSTR,
pcwchQualifiedName: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetNamespaceUri: fn(
self: *const IXmlReader,
ppwszNamespaceUri: ?*?PWSTR,
pcwchNamespaceUri: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLocalName: fn(
self: *const IXmlReader,
ppwszLocalName: ?*?PWSTR,
pcwchLocalName: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPrefix: fn(
self: *const IXmlReader,
ppwszPrefix: ?*?PWSTR,
pcwchPrefix: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetValue: fn(
self: *const IXmlReader,
ppwszValue: ?*?PWSTR,
pcwchValue: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ReadValueChunk: fn(
self: *const IXmlReader,
pwchBuffer: [*:0]u16,
cwchChunkSize: u32,
pcwchRead: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetBaseUri: fn(
self: *const IXmlReader,
ppwszBaseUri: ?*?PWSTR,
pcwchBaseUri: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IsDefault: fn(
self: *const IXmlReader,
) callconv(@import("std").os.windows.WINAPI) BOOL,
IsEmptyElement: fn(
self: *const IXmlReader,
) callconv(@import("std").os.windows.WINAPI) BOOL,
GetLineNumber: fn(
self: *const IXmlReader,
pnLineNumber: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLinePosition: fn(
self: *const IXmlReader,
pnLinePosition: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetAttributeCount: fn(
self: *const IXmlReader,
pnAttributeCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDepth: fn(
self: *const IXmlReader,
pnDepth: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IsEOF: fn(
self: *const IXmlReader,
) callconv(@import("std").os.windows.WINAPI) BOOL,
};
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 IXmlReader_SetInput(self: *const T, pInput: ?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlReader.VTable, self.vtable).SetInput(@ptrCast(*const IXmlReader, self), pInput);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlReader_GetProperty(self: *const T, nProperty: u32, ppValue: ?*isize) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlReader.VTable, self.vtable).GetProperty(@ptrCast(*const IXmlReader, self), nProperty, ppValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlReader_SetProperty(self: *const T, nProperty: u32, pValue: isize) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlReader.VTable, self.vtable).SetProperty(@ptrCast(*const IXmlReader, self), nProperty, pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlReader_Read(self: *const T, pNodeType: ?*XmlNodeType) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlReader.VTable, self.vtable).Read(@ptrCast(*const IXmlReader, self), pNodeType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlReader_GetNodeType(self: *const T, pNodeType: ?*XmlNodeType) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlReader.VTable, self.vtable).GetNodeType(@ptrCast(*const IXmlReader, self), pNodeType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlReader_MoveToFirstAttribute(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlReader.VTable, self.vtable).MoveToFirstAttribute(@ptrCast(*const IXmlReader, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlReader_MoveToNextAttribute(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlReader.VTable, self.vtable).MoveToNextAttribute(@ptrCast(*const IXmlReader, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlReader_MoveToAttributeByName(self: *const T, pwszLocalName: ?[*:0]const u16, pwszNamespaceUri: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlReader.VTable, self.vtable).MoveToAttributeByName(@ptrCast(*const IXmlReader, self), pwszLocalName, pwszNamespaceUri);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlReader_MoveToElement(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlReader.VTable, self.vtable).MoveToElement(@ptrCast(*const IXmlReader, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlReader_GetQualifiedName(self: *const T, ppwszQualifiedName: ?*?PWSTR, pcwchQualifiedName: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlReader.VTable, self.vtable).GetQualifiedName(@ptrCast(*const IXmlReader, self), ppwszQualifiedName, pcwchQualifiedName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlReader_GetNamespaceUri(self: *const T, ppwszNamespaceUri: ?*?PWSTR, pcwchNamespaceUri: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlReader.VTable, self.vtable).GetNamespaceUri(@ptrCast(*const IXmlReader, self), ppwszNamespaceUri, pcwchNamespaceUri);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlReader_GetLocalName(self: *const T, ppwszLocalName: ?*?PWSTR, pcwchLocalName: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlReader.VTable, self.vtable).GetLocalName(@ptrCast(*const IXmlReader, self), ppwszLocalName, pcwchLocalName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlReader_GetPrefix(self: *const T, ppwszPrefix: ?*?PWSTR, pcwchPrefix: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlReader.VTable, self.vtable).GetPrefix(@ptrCast(*const IXmlReader, self), ppwszPrefix, pcwchPrefix);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlReader_GetValue(self: *const T, ppwszValue: ?*?PWSTR, pcwchValue: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlReader.VTable, self.vtable).GetValue(@ptrCast(*const IXmlReader, self), ppwszValue, pcwchValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlReader_ReadValueChunk(self: *const T, pwchBuffer: [*:0]u16, cwchChunkSize: u32, pcwchRead: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlReader.VTable, self.vtable).ReadValueChunk(@ptrCast(*const IXmlReader, self), pwchBuffer, cwchChunkSize, pcwchRead);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlReader_GetBaseUri(self: *const T, ppwszBaseUri: ?*?PWSTR, pcwchBaseUri: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlReader.VTable, self.vtable).GetBaseUri(@ptrCast(*const IXmlReader, self), ppwszBaseUri, pcwchBaseUri);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlReader_IsDefault(self: *const T) callconv(.Inline) BOOL {
return @ptrCast(*const IXmlReader.VTable, self.vtable).IsDefault(@ptrCast(*const IXmlReader, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlReader_IsEmptyElement(self: *const T) callconv(.Inline) BOOL {
return @ptrCast(*const IXmlReader.VTable, self.vtable).IsEmptyElement(@ptrCast(*const IXmlReader, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlReader_GetLineNumber(self: *const T, pnLineNumber: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlReader.VTable, self.vtable).GetLineNumber(@ptrCast(*const IXmlReader, self), pnLineNumber);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlReader_GetLinePosition(self: *const T, pnLinePosition: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlReader.VTable, self.vtable).GetLinePosition(@ptrCast(*const IXmlReader, self), pnLinePosition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlReader_GetAttributeCount(self: *const T, pnAttributeCount: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlReader.VTable, self.vtable).GetAttributeCount(@ptrCast(*const IXmlReader, self), pnAttributeCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlReader_GetDepth(self: *const T, pnDepth: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlReader.VTable, self.vtable).GetDepth(@ptrCast(*const IXmlReader, self), pnDepth);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlReader_IsEOF(self: *const T) callconv(.Inline) BOOL {
return @ptrCast(*const IXmlReader.VTable, self.vtable).IsEOF(@ptrCast(*const IXmlReader, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXmlResolver_Value = Guid.initString("7279fc82-709d-4095-b63d-69fe4b0d9030");
pub const IID_IXmlResolver = &IID_IXmlResolver_Value;
pub const IXmlResolver = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
ResolveUri: fn(
self: *const IXmlResolver,
pwszBaseUri: ?[*:0]const u16,
pwszPublicIdentifier: ?[*:0]const u16,
pwszSystemIdentifier: ?[*:0]const u16,
ppResolvedInput: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlResolver_ResolveUri(self: *const T, pwszBaseUri: ?[*:0]const u16, pwszPublicIdentifier: ?[*:0]const u16, pwszSystemIdentifier: ?[*:0]const u16, ppResolvedInput: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlResolver.VTable, self.vtable).ResolveUri(@ptrCast(*const IXmlResolver, self), pwszBaseUri, pwszPublicIdentifier, pwszSystemIdentifier, ppResolvedInput);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXmlWriter_Value = Guid.initString("7279fc88-709d-4095-b63d-69fe4b0d9030");
pub const IID_IXmlWriter = &IID_IXmlWriter_Value;
pub const IXmlWriter = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetOutput: fn(
self: *const IXmlWriter,
pOutput: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetProperty: fn(
self: *const IXmlWriter,
nProperty: u32,
ppValue: ?*isize,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetProperty: fn(
self: *const IXmlWriter,
nProperty: u32,
pValue: isize,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteAttributes: fn(
self: *const IXmlWriter,
pReader: ?*IXmlReader,
fWriteDefaultAttributes: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteAttributeString: fn(
self: *const IXmlWriter,
pwszPrefix: ?[*:0]const u16,
pwszLocalName: ?[*:0]const u16,
pwszNamespaceUri: ?[*:0]const u16,
pwszValue: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteCData: fn(
self: *const IXmlWriter,
pwszText: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteCharEntity: fn(
self: *const IXmlWriter,
wch: u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteChars: fn(
self: *const IXmlWriter,
pwch: ?[*:0]const u16,
cwch: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteComment: fn(
self: *const IXmlWriter,
pwszComment: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteDocType: fn(
self: *const IXmlWriter,
pwszName: ?[*:0]const u16,
pwszPublicId: ?[*:0]const u16,
pwszSystemId: ?[*:0]const u16,
pwszSubset: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteElementString: fn(
self: *const IXmlWriter,
pwszPrefix: ?[*:0]const u16,
pwszLocalName: ?[*:0]const u16,
pwszNamespaceUri: ?[*:0]const u16,
pwszValue: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteEndDocument: fn(
self: *const IXmlWriter,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteEndElement: fn(
self: *const IXmlWriter,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteEntityRef: fn(
self: *const IXmlWriter,
pwszName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteFullEndElement: fn(
self: *const IXmlWriter,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteName: fn(
self: *const IXmlWriter,
pwszName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteNmToken: fn(
self: *const IXmlWriter,
pwszNmToken: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteNode: fn(
self: *const IXmlWriter,
pReader: ?*IXmlReader,
fWriteDefaultAttributes: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteNodeShallow: fn(
self: *const IXmlWriter,
pReader: ?*IXmlReader,
fWriteDefaultAttributes: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteProcessingInstruction: fn(
self: *const IXmlWriter,
pwszName: ?[*:0]const u16,
pwszText: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteQualifiedName: fn(
self: *const IXmlWriter,
pwszLocalName: ?[*:0]const u16,
pwszNamespaceUri: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteRaw: fn(
self: *const IXmlWriter,
pwszData: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteRawChars: fn(
self: *const IXmlWriter,
pwch: ?[*:0]const u16,
cwch: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteStartDocument: fn(
self: *const IXmlWriter,
standalone: XmlStandalone,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteStartElement: fn(
self: *const IXmlWriter,
pwszPrefix: ?[*:0]const u16,
pwszLocalName: ?[*:0]const u16,
pwszNamespaceUri: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteString: fn(
self: *const IXmlWriter,
pwszText: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteSurrogateCharEntity: fn(
self: *const IXmlWriter,
wchLow: u16,
wchHigh: u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteWhitespace: fn(
self: *const IXmlWriter,
pwszWhitespace: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Flush: fn(
self: *const IXmlWriter,
) 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 IXmlWriter_SetOutput(self: *const T, pOutput: ?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriter.VTable, self.vtable).SetOutput(@ptrCast(*const IXmlWriter, self), pOutput);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriter_GetProperty(self: *const T, nProperty: u32, ppValue: ?*isize) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriter.VTable, self.vtable).GetProperty(@ptrCast(*const IXmlWriter, self), nProperty, ppValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriter_SetProperty(self: *const T, nProperty: u32, pValue: isize) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriter.VTable, self.vtable).SetProperty(@ptrCast(*const IXmlWriter, self), nProperty, pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriter_WriteAttributes(self: *const T, pReader: ?*IXmlReader, fWriteDefaultAttributes: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriter.VTable, self.vtable).WriteAttributes(@ptrCast(*const IXmlWriter, self), pReader, fWriteDefaultAttributes);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriter_WriteAttributeString(self: *const T, pwszPrefix: ?[*:0]const u16, pwszLocalName: ?[*:0]const u16, pwszNamespaceUri: ?[*:0]const u16, pwszValue: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriter.VTable, self.vtable).WriteAttributeString(@ptrCast(*const IXmlWriter, self), pwszPrefix, pwszLocalName, pwszNamespaceUri, pwszValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriter_WriteCData(self: *const T, pwszText: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriter.VTable, self.vtable).WriteCData(@ptrCast(*const IXmlWriter, self), pwszText);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriter_WriteCharEntity(self: *const T, wch: u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriter.VTable, self.vtable).WriteCharEntity(@ptrCast(*const IXmlWriter, self), wch);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriter_WriteChars(self: *const T, pwch: ?[*:0]const u16, cwch: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriter.VTable, self.vtable).WriteChars(@ptrCast(*const IXmlWriter, self), pwch, cwch);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriter_WriteComment(self: *const T, pwszComment: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriter.VTable, self.vtable).WriteComment(@ptrCast(*const IXmlWriter, self), pwszComment);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriter_WriteDocType(self: *const T, pwszName: ?[*:0]const u16, pwszPublicId: ?[*:0]const u16, pwszSystemId: ?[*:0]const u16, pwszSubset: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriter.VTable, self.vtable).WriteDocType(@ptrCast(*const IXmlWriter, self), pwszName, pwszPublicId, pwszSystemId, pwszSubset);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriter_WriteElementString(self: *const T, pwszPrefix: ?[*:0]const u16, pwszLocalName: ?[*:0]const u16, pwszNamespaceUri: ?[*:0]const u16, pwszValue: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriter.VTable, self.vtable).WriteElementString(@ptrCast(*const IXmlWriter, self), pwszPrefix, pwszLocalName, pwszNamespaceUri, pwszValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriter_WriteEndDocument(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriter.VTable, self.vtable).WriteEndDocument(@ptrCast(*const IXmlWriter, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriter_WriteEndElement(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriter.VTable, self.vtable).WriteEndElement(@ptrCast(*const IXmlWriter, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriter_WriteEntityRef(self: *const T, pwszName: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriter.VTable, self.vtable).WriteEntityRef(@ptrCast(*const IXmlWriter, self), pwszName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriter_WriteFullEndElement(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriter.VTable, self.vtable).WriteFullEndElement(@ptrCast(*const IXmlWriter, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriter_WriteName(self: *const T, pwszName: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriter.VTable, self.vtable).WriteName(@ptrCast(*const IXmlWriter, self), pwszName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriter_WriteNmToken(self: *const T, pwszNmToken: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriter.VTable, self.vtable).WriteNmToken(@ptrCast(*const IXmlWriter, self), pwszNmToken);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriter_WriteNode(self: *const T, pReader: ?*IXmlReader, fWriteDefaultAttributes: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriter.VTable, self.vtable).WriteNode(@ptrCast(*const IXmlWriter, self), pReader, fWriteDefaultAttributes);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriter_WriteNodeShallow(self: *const T, pReader: ?*IXmlReader, fWriteDefaultAttributes: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriter.VTable, self.vtable).WriteNodeShallow(@ptrCast(*const IXmlWriter, self), pReader, fWriteDefaultAttributes);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriter_WriteProcessingInstruction(self: *const T, pwszName: ?[*:0]const u16, pwszText: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriter.VTable, self.vtable).WriteProcessingInstruction(@ptrCast(*const IXmlWriter, self), pwszName, pwszText);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriter_WriteQualifiedName(self: *const T, pwszLocalName: ?[*:0]const u16, pwszNamespaceUri: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriter.VTable, self.vtable).WriteQualifiedName(@ptrCast(*const IXmlWriter, self), pwszLocalName, pwszNamespaceUri);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriter_WriteRaw(self: *const T, pwszData: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriter.VTable, self.vtable).WriteRaw(@ptrCast(*const IXmlWriter, self), pwszData);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriter_WriteRawChars(self: *const T, pwch: ?[*:0]const u16, cwch: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriter.VTable, self.vtable).WriteRawChars(@ptrCast(*const IXmlWriter, self), pwch, cwch);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriter_WriteStartDocument(self: *const T, standalone: XmlStandalone) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriter.VTable, self.vtable).WriteStartDocument(@ptrCast(*const IXmlWriter, self), standalone);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriter_WriteStartElement(self: *const T, pwszPrefix: ?[*:0]const u16, pwszLocalName: ?[*:0]const u16, pwszNamespaceUri: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriter.VTable, self.vtable).WriteStartElement(@ptrCast(*const IXmlWriter, self), pwszPrefix, pwszLocalName, pwszNamespaceUri);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriter_WriteString(self: *const T, pwszText: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriter.VTable, self.vtable).WriteString(@ptrCast(*const IXmlWriter, self), pwszText);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriter_WriteSurrogateCharEntity(self: *const T, wchLow: u16, wchHigh: u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriter.VTable, self.vtable).WriteSurrogateCharEntity(@ptrCast(*const IXmlWriter, self), wchLow, wchHigh);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriter_WriteWhitespace(self: *const T, pwszWhitespace: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriter.VTable, self.vtable).WriteWhitespace(@ptrCast(*const IXmlWriter, self), pwszWhitespace);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriter_Flush(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriter.VTable, self.vtable).Flush(@ptrCast(*const IXmlWriter, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXmlWriterLite_Value = Guid.initString("862494c6-1310-4aad-b3cd-2dbeebf670d3");
pub const IID_IXmlWriterLite = &IID_IXmlWriterLite_Value;
pub const IXmlWriterLite = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetOutput: fn(
self: *const IXmlWriterLite,
pOutput: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetProperty: fn(
self: *const IXmlWriterLite,
nProperty: u32,
ppValue: ?*isize,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetProperty: fn(
self: *const IXmlWriterLite,
nProperty: u32,
pValue: isize,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteAttributes: fn(
self: *const IXmlWriterLite,
pReader: ?*IXmlReader,
fWriteDefaultAttributes: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteAttributeString: fn(
self: *const IXmlWriterLite,
pwszQName: [*:0]const u16,
cwszQName: u32,
pwszValue: ?[*:0]const u16,
cwszValue: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteCData: fn(
self: *const IXmlWriterLite,
pwszText: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteCharEntity: fn(
self: *const IXmlWriterLite,
wch: u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteChars: fn(
self: *const IXmlWriterLite,
pwch: ?[*:0]const u16,
cwch: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteComment: fn(
self: *const IXmlWriterLite,
pwszComment: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteDocType: fn(
self: *const IXmlWriterLite,
pwszName: ?[*:0]const u16,
pwszPublicId: ?[*:0]const u16,
pwszSystemId: ?[*:0]const u16,
pwszSubset: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteElementString: fn(
self: *const IXmlWriterLite,
pwszQName: [*:0]const u16,
cwszQName: u32,
pwszValue: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteEndDocument: fn(
self: *const IXmlWriterLite,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteEndElement: fn(
self: *const IXmlWriterLite,
pwszQName: [*:0]const u16,
cwszQName: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteEntityRef: fn(
self: *const IXmlWriterLite,
pwszName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteFullEndElement: fn(
self: *const IXmlWriterLite,
pwszQName: [*:0]const u16,
cwszQName: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteName: fn(
self: *const IXmlWriterLite,
pwszName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteNmToken: fn(
self: *const IXmlWriterLite,
pwszNmToken: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteNode: fn(
self: *const IXmlWriterLite,
pReader: ?*IXmlReader,
fWriteDefaultAttributes: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteNodeShallow: fn(
self: *const IXmlWriterLite,
pReader: ?*IXmlReader,
fWriteDefaultAttributes: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteProcessingInstruction: fn(
self: *const IXmlWriterLite,
pwszName: ?[*:0]const u16,
pwszText: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteRaw: fn(
self: *const IXmlWriterLite,
pwszData: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteRawChars: fn(
self: *const IXmlWriterLite,
pwch: ?[*:0]const u16,
cwch: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteStartDocument: fn(
self: *const IXmlWriterLite,
standalone: XmlStandalone,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteStartElement: fn(
self: *const IXmlWriterLite,
pwszQName: [*:0]const u16,
cwszQName: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteString: fn(
self: *const IXmlWriterLite,
pwszText: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteSurrogateCharEntity: fn(
self: *const IXmlWriterLite,
wchLow: u16,
wchHigh: u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WriteWhitespace: fn(
self: *const IXmlWriterLite,
pwszWhitespace: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Flush: fn(
self: *const IXmlWriterLite,
) 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 IXmlWriterLite_SetOutput(self: *const T, pOutput: ?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriterLite.VTable, self.vtable).SetOutput(@ptrCast(*const IXmlWriterLite, self), pOutput);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriterLite_GetProperty(self: *const T, nProperty: u32, ppValue: ?*isize) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriterLite.VTable, self.vtable).GetProperty(@ptrCast(*const IXmlWriterLite, self), nProperty, ppValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriterLite_SetProperty(self: *const T, nProperty: u32, pValue: isize) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriterLite.VTable, self.vtable).SetProperty(@ptrCast(*const IXmlWriterLite, self), nProperty, pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriterLite_WriteAttributes(self: *const T, pReader: ?*IXmlReader, fWriteDefaultAttributes: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriterLite.VTable, self.vtable).WriteAttributes(@ptrCast(*const IXmlWriterLite, self), pReader, fWriteDefaultAttributes);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriterLite_WriteAttributeString(self: *const T, pwszQName: [*:0]const u16, cwszQName: u32, pwszValue: ?[*:0]const u16, cwszValue: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriterLite.VTable, self.vtable).WriteAttributeString(@ptrCast(*const IXmlWriterLite, self), pwszQName, cwszQName, pwszValue, cwszValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriterLite_WriteCData(self: *const T, pwszText: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriterLite.VTable, self.vtable).WriteCData(@ptrCast(*const IXmlWriterLite, self), pwszText);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriterLite_WriteCharEntity(self: *const T, wch: u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriterLite.VTable, self.vtable).WriteCharEntity(@ptrCast(*const IXmlWriterLite, self), wch);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriterLite_WriteChars(self: *const T, pwch: ?[*:0]const u16, cwch: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriterLite.VTable, self.vtable).WriteChars(@ptrCast(*const IXmlWriterLite, self), pwch, cwch);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriterLite_WriteComment(self: *const T, pwszComment: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriterLite.VTable, self.vtable).WriteComment(@ptrCast(*const IXmlWriterLite, self), pwszComment);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriterLite_WriteDocType(self: *const T, pwszName: ?[*:0]const u16, pwszPublicId: ?[*:0]const u16, pwszSystemId: ?[*:0]const u16, pwszSubset: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriterLite.VTable, self.vtable).WriteDocType(@ptrCast(*const IXmlWriterLite, self), pwszName, pwszPublicId, pwszSystemId, pwszSubset);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriterLite_WriteElementString(self: *const T, pwszQName: [*:0]const u16, cwszQName: u32, pwszValue: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriterLite.VTable, self.vtable).WriteElementString(@ptrCast(*const IXmlWriterLite, self), pwszQName, cwszQName, pwszValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriterLite_WriteEndDocument(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriterLite.VTable, self.vtable).WriteEndDocument(@ptrCast(*const IXmlWriterLite, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriterLite_WriteEndElement(self: *const T, pwszQName: [*:0]const u16, cwszQName: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriterLite.VTable, self.vtable).WriteEndElement(@ptrCast(*const IXmlWriterLite, self), pwszQName, cwszQName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriterLite_WriteEntityRef(self: *const T, pwszName: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriterLite.VTable, self.vtable).WriteEntityRef(@ptrCast(*const IXmlWriterLite, self), pwszName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriterLite_WriteFullEndElement(self: *const T, pwszQName: [*:0]const u16, cwszQName: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriterLite.VTable, self.vtable).WriteFullEndElement(@ptrCast(*const IXmlWriterLite, self), pwszQName, cwszQName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriterLite_WriteName(self: *const T, pwszName: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriterLite.VTable, self.vtable).WriteName(@ptrCast(*const IXmlWriterLite, self), pwszName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriterLite_WriteNmToken(self: *const T, pwszNmToken: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriterLite.VTable, self.vtable).WriteNmToken(@ptrCast(*const IXmlWriterLite, self), pwszNmToken);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriterLite_WriteNode(self: *const T, pReader: ?*IXmlReader, fWriteDefaultAttributes: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriterLite.VTable, self.vtable).WriteNode(@ptrCast(*const IXmlWriterLite, self), pReader, fWriteDefaultAttributes);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriterLite_WriteNodeShallow(self: *const T, pReader: ?*IXmlReader, fWriteDefaultAttributes: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriterLite.VTable, self.vtable).WriteNodeShallow(@ptrCast(*const IXmlWriterLite, self), pReader, fWriteDefaultAttributes);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriterLite_WriteProcessingInstruction(self: *const T, pwszName: ?[*:0]const u16, pwszText: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriterLite.VTable, self.vtable).WriteProcessingInstruction(@ptrCast(*const IXmlWriterLite, self), pwszName, pwszText);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriterLite_WriteRaw(self: *const T, pwszData: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriterLite.VTable, self.vtable).WriteRaw(@ptrCast(*const IXmlWriterLite, self), pwszData);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriterLite_WriteRawChars(self: *const T, pwch: ?[*:0]const u16, cwch: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriterLite.VTable, self.vtable).WriteRawChars(@ptrCast(*const IXmlWriterLite, self), pwch, cwch);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriterLite_WriteStartDocument(self: *const T, standalone: XmlStandalone) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriterLite.VTable, self.vtable).WriteStartDocument(@ptrCast(*const IXmlWriterLite, self), standalone);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriterLite_WriteStartElement(self: *const T, pwszQName: [*:0]const u16, cwszQName: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriterLite.VTable, self.vtable).WriteStartElement(@ptrCast(*const IXmlWriterLite, self), pwszQName, cwszQName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriterLite_WriteString(self: *const T, pwszText: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriterLite.VTable, self.vtable).WriteString(@ptrCast(*const IXmlWriterLite, self), pwszText);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriterLite_WriteSurrogateCharEntity(self: *const T, wchLow: u16, wchHigh: u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriterLite.VTable, self.vtable).WriteSurrogateCharEntity(@ptrCast(*const IXmlWriterLite, self), wchLow, wchHigh);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriterLite_WriteWhitespace(self: *const T, pwszWhitespace: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriterLite.VTable, self.vtable).WriteWhitespace(@ptrCast(*const IXmlWriterLite, self), pwszWhitespace);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXmlWriterLite_Flush(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXmlWriterLite.VTable, self.vtable).Flush(@ptrCast(*const IXmlWriterLite, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
//--------------------------------------------------------------------------------
// Section: Functions (6)
//--------------------------------------------------------------------------------
pub extern "XmlLite" fn CreateXmlReader(
riid: ?*const Guid,
ppvObject: ?*?*anyopaque,
pMalloc: ?*IMalloc,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "XmlLite" fn CreateXmlReaderInputWithEncodingCodePage(
pInputStream: ?*IUnknown,
pMalloc: ?*IMalloc,
nEncodingCodePage: u32,
fEncodingHint: BOOL,
pwszBaseUri: ?[*:0]const u16,
ppInput: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "XmlLite" fn CreateXmlReaderInputWithEncodingName(
pInputStream: ?*IUnknown,
pMalloc: ?*IMalloc,
pwszEncodingName: ?[*:0]const u16,
fEncodingHint: BOOL,
pwszBaseUri: ?[*:0]const u16,
ppInput: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "XmlLite" fn CreateXmlWriter(
riid: ?*const Guid,
ppvObject: ?*?*anyopaque,
pMalloc: ?*IMalloc,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "XmlLite" fn CreateXmlWriterOutputWithEncodingCodePage(
pOutputStream: ?*IUnknown,
pMalloc: ?*IMalloc,
nEncodingCodePage: u32,
ppOutput: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "XmlLite" fn CreateXmlWriterOutputWithEncodingName(
pOutputStream: ?*IUnknown,
pMalloc: ?*IMalloc,
pwszEncodingName: ?[*:0]const u16,
ppOutput: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (0)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../../zig.zig").unicode_mode) {
.ansi => struct {
},
.wide => struct {
},
.unspecified => if (@import("builtin").is_test) struct {
} else struct {
},
};
//--------------------------------------------------------------------------------
// Section: Imports (6)
//--------------------------------------------------------------------------------
const Guid = @import("../../zig.zig").Guid;
const BOOL = @import("../../foundation.zig").BOOL;
const HRESULT = @import("../../foundation.zig").HRESULT;
const IMalloc = @import("../../system/com.zig").IMalloc;
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/data/xml/xml_lite.zig |
const std = @import("std");
const c = @import("internal/c.zig");
const internal = @import("internal/internal.zig");
const log = std.log.scoped(.git);
const git = @import("git.zig");
pub const DescribeOptions = struct {
max_candidate_tags: c_uint = 10,
describe_strategy: DescribeStrategy = .default,
pattern: ?[:0]const u8,
/// When calculating the distance from the matching tag or reference, only walk down the first-parent ancestry.
only_follow_first_parent: bool = false,
// If no matching tag or reference is found, the describe operation would normally fail. If this option is set, it will
// instead fall back to showing the full id of the commit.
show_commit_oid_as_fallback: bool = false,
/// Reference lookup strategy
///
/// These behave like the --tags and --all options to git-describe, namely they say to look for any reference in either
/// refs/tags/ or refs/ respectively.
pub const DescribeStrategy = enum(c_uint) {
default = 0,
tags,
all,
};
pub fn makeCOptionObject(self: DescribeOptions) c.git_describe_options {
return .{
.version = c.GIT_DESCRIBE_OPTIONS_VERSION,
.max_candidates_tags = self.max_candidate_tags,
.describe_strategy = @enumToInt(self.describe_strategy),
.pattern = if (self.pattern) |slice| slice.ptr else null,
.only_follow_first_parent = @boolToInt(self.only_follow_first_parent),
.show_commit_oid_as_fallback = @boolToInt(self.show_commit_oid_as_fallback),
};
}
comptime {
std.testing.refAllDecls(@This());
}
};
pub const DescribeFormatOptions = struct {
/// Size of the abbreviated commit id to use. This value is the lower bound for the length of the abbreviated string.
abbreviated_size: c_uint = 7,
/// Set to use the long format even when a shorter name could be used.
always_use_long_format: bool = false,
/// If the workdir is dirty and this is set, this string will be appended to the description string.
dirty_suffix: ?[:0]const u8 = null,
pub fn makeCOptionObject(self: DescribeFormatOptions) c.git_describe_format_options {
return .{
.version = c.GIT_DESCRIBE_FORMAT_OPTIONS_VERSION,
.abbreviated_size = self.abbreviated_size,
.always_use_long_format = @boolToInt(self.always_use_long_format),
.dirty_suffix = if (self.dirty_suffix) |slice| slice.ptr else null,
};
}
comptime {
std.testing.refAllDecls(@This());
}
};
pub const DescribeResult = opaque {
pub fn format(self: *const DescribeResult, options: DescribeFormatOptions) !git.Buf {
var buf: git.Buf = .{};
const c_options = options.makeCOptionObject();
try internal.wrapCall("git_describe_format", .{
@ptrCast(*c.git_buf, &buf),
@ptrCast(*const c.git_describe_result, self),
&c_options,
});
log.debug("successfully formatted describe", .{});
return buf;
}
pub fn deinit(self: *DescribeResult) void {
log.debug("DescribeResult.deinit called", .{});
c.git_describe_result_free(@ptrCast(*c.git_describe_result, self));
log.debug("describe result freed successfully", .{});
}
comptime {
std.testing.refAllDecls(@This());
}
};
comptime {
std.testing.refAllDecls(@This());
} | src/describe.zig |
const std = @import("std");
const Answer = struct { @"0": u32 };
const Point = struct { x: usize, y: usize };
const Variable = enum { X, Y };
const Equality = struct { variable: Variable, value: usize };
const Grid = struct {
const Self = @This();
items: []u8,
height: usize,
width: usize,
buffer_height: usize,
buffer_width: usize,
allocator: *std.mem.Allocator,
pub fn init(height: usize, width: usize, allocator: *std.mem.Allocator) !Self {
const items = try allocator.alloc(u8, height * width);
std.mem.set(u8, items, '.');
return Self{
.items = items,
.height = height,
.width = width,
.buffer_height = height,
.buffer_width = width,
.allocator = allocator,
};
}
pub fn deinit(self: Self) void {
self.allocator.free(self.items);
}
pub fn ix(self: Self, row: usize, col: usize) *u8 {
std.debug.assert(col < self.width);
return &self.items[row * self.buffer_width + col];
}
pub fn count(self: Self) u32 {
var total: u32 = 0;
var i: usize = 0;
while (i < self.height) : (i += 1) {
var j: usize = 0;
while (j < self.width) : (j += 1) {
if (self.ix(i, j).* == '#') {
total += 1;
}
}
}
return total;
}
pub fn fold(self: *Self, constraint: Equality) void {
var i: usize = 0;
while (i < self.height) : (i += 1) {
var j: usize = 0;
while (j < self.width) : (j += 1) {
if (self.ix(i, j).* == '#') {
switch (constraint.variable) {
.X => {
if (j > constraint.value) {
self.ix(i, constraint.value - (j - constraint.value)).* = '#';
self.ix(i, j).* = '.';
}
},
.Y => {
if (i > constraint.value) {
self.ix(constraint.value - (i - constraint.value), j).* = '#';
self.ix(i, j).* = '.';
}
},
}
}
}
}
switch (constraint.variable) {
.X => {
self.width = constraint.value;
},
.Y => {
self.height = constraint.value;
},
}
}
};
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: [1024]u8 = undefined;
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
var coords = std.ArrayList(Point).init(&gpa.allocator);
defer coords.deinit();
var folds = std.ArrayList(Equality).init(&gpa.allocator);
defer folds.deinit();
while (try reader.readUntilDelimiterOrEof(&buffer, '\n')) |line| {
if (line.len == 0) {
break;
}
var tokens = std.mem.tokenize(u8, line, ",");
const x = try std.fmt.parseInt(usize, tokens.next().?, 10);
const y = try std.fmt.parseInt(usize, tokens.next().?, 10);
try coords.append(Point{ .x = x, .y = y });
}
while (try reader.readUntilDelimiterOrEof(&buffer, '\n')) |line| {
var i: usize = 0;
while (line[i] != 'x' and line[i] != 'y') : (i += 1) {}
const variable = line[i];
while (!std.ascii.isDigit(line[i])) : (i += 1) {}
try folds.append(switch (variable) {
'x' => Equality{ .variable = .X, .value = try std.fmt.parseInt(usize, line[i..], 10) },
'y' => Equality{ .variable = .Y, .value = try std.fmt.parseInt(usize, line[i..], 10) },
else => unreachable,
});
}
var max_y: usize = 0;
var max_x: usize = 0;
for (coords.items) |coord| {
max_y = @maximum(max_y, @intCast(usize, coord.y));
max_x = @maximum(max_x, @intCast(usize, coord.x));
}
var grid = try Grid.init(max_y + 1, max_x + 1, &gpa.allocator);
defer grid.deinit();
for (coords.items) |coord| {
grid.ix(coord.y, coord.x).* = '#';
}
grid.fold(folds.items[0]);
const answer = Answer{ .@"0" = grid.count() };
for (folds.items[1..]) |fold| {
grid.fold(fold);
}
var i: usize = 0;
while (i < grid.height) : (i += 1) {
std.debug.print("{s}\n", .{grid.items[i * grid.buffer_width .. i * grid.buffer_width + grid.width]});
}
return answer;
}
pub fn main() !void {
const answer = try run("inputs/" ++ @typeName(@This()) ++ ".txt");
std.debug.print("{d}\n", .{answer.@"0"});
}
test {
const answer = try run("test-inputs/" ++ @typeName(@This()) ++ ".txt");
try std.testing.expectEqual(answer.@"0", 17);
} | src/day13.zig |
const std = @import("../std.zig");
const CpuFeature = std.Target.Cpu.Feature;
const CpuModel = std.Target.Cpu.Model;
pub const Feature = enum {
abs2008,
cnmips,
cnmipsp,
crc,
dsp,
dspr2,
dspr3,
eva,
fp64,
fpxx,
ginv,
gp64,
long_calls,
micromips,
mips1,
mips16,
mips2,
mips3,
mips32,
mips32r2,
mips32r3,
mips32r5,
mips32r6,
mips3_32,
mips3_32r2,
mips4,
mips4_32,
mips4_32r2,
mips5,
mips5_32r2,
mips64,
mips64r2,
mips64r3,
mips64r5,
mips64r6,
msa,
mt,
nan2008,
noabicalls,
nomadd4,
nooddspreg,
p5600,
ptr64,
single_float,
soft_float,
sym32,
use_indirect_jump_hazard,
use_tcc_in_div,
vfpu,
virt,
xgot,
};
pub usingnamespace CpuFeature.feature_set_fns(Feature);
pub const all_features = blk: {
const len = @typeInfo(Feature).Enum.fields.len;
std.debug.assert(len <= CpuFeature.Set.needed_bit_count);
var result: [len]CpuFeature = undefined;
result[@enumToInt(Feature.abs2008)] = .{
.llvm_name = "abs2008",
.description = "Disable IEEE 754-2008 abs.fmt mode",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.cnmips)] = .{
.llvm_name = "cnmips",
.description = "Octeon cnMIPS Support",
.dependencies = featureSet(&[_]Feature{
.mips64r2,
}),
};
result[@enumToInt(Feature.cnmipsp)] = .{
.llvm_name = "cnmipsp",
.description = "Octeon+ cnMIPS Support",
.dependencies = featureSet(&[_]Feature{
.cnmips,
}),
};
result[@enumToInt(Feature.crc)] = .{
.llvm_name = "crc",
.description = "Mips R6 CRC ASE",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.dsp)] = .{
.llvm_name = "dsp",
.description = "Mips DSP ASE",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.dspr2)] = .{
.llvm_name = "dspr2",
.description = "Mips DSP-R2 ASE",
.dependencies = featureSet(&[_]Feature{
.dsp,
}),
};
result[@enumToInt(Feature.dspr3)] = .{
.llvm_name = "dspr3",
.description = "Mips DSP-R3 ASE",
.dependencies = featureSet(&[_]Feature{
.dsp,
.dspr2,
}),
};
result[@enumToInt(Feature.eva)] = .{
.llvm_name = "eva",
.description = "Mips EVA ASE",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.fp64)] = .{
.llvm_name = "fp64",
.description = "Support 64-bit FP registers",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.fpxx)] = .{
.llvm_name = "fpxx",
.description = "Support for FPXX",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.ginv)] = .{
.llvm_name = "ginv",
.description = "Mips Global Invalidate ASE",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.gp64)] = .{
.llvm_name = "gp64",
.description = "General Purpose Registers are 64-bit wide",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.long_calls)] = .{
.llvm_name = "long-calls",
.description = "Disable use of the jal instruction",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.micromips)] = .{
.llvm_name = "micromips",
.description = "microMips mode",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.mips1)] = .{
.llvm_name = "mips1",
.description = "Mips I ISA Support [highly experimental]",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.mips16)] = .{
.llvm_name = "mips16",
.description = "Mips16 mode",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.mips2)] = .{
.llvm_name = "mips2",
.description = "Mips II ISA Support [highly experimental]",
.dependencies = featureSet(&[_]Feature{
.mips1,
}),
};
result[@enumToInt(Feature.mips3)] = .{
.llvm_name = "mips3",
.description = "MIPS III ISA Support [highly experimental]",
.dependencies = featureSet(&[_]Feature{
.fp64,
.gp64,
.mips2,
.mips3_32,
.mips3_32r2,
}),
};
result[@enumToInt(Feature.mips32)] = .{
.llvm_name = "mips32",
.description = "Mips32 ISA Support",
.dependencies = featureSet(&[_]Feature{
.mips2,
.mips3_32,
.mips4_32,
}),
};
result[@enumToInt(Feature.mips32r2)] = .{
.llvm_name = "mips32r2",
.description = "Mips32r2 ISA Support",
.dependencies = featureSet(&[_]Feature{
.mips32,
.mips3_32r2,
.mips4_32r2,
.mips5_32r2,
}),
};
result[@enumToInt(Feature.mips32r3)] = .{
.llvm_name = "mips32r3",
.description = "Mips32r3 ISA Support",
.dependencies = featureSet(&[_]Feature{
.mips32r2,
}),
};
result[@enumToInt(Feature.mips32r5)] = .{
.llvm_name = "mips32r5",
.description = "Mips32r5 ISA Support",
.dependencies = featureSet(&[_]Feature{
.mips32r3,
}),
};
result[@enumToInt(Feature.mips32r6)] = .{
.llvm_name = "mips32r6",
.description = "Mips32r6 ISA Support [experimental]",
.dependencies = featureSet(&[_]Feature{
.abs2008,
.fp64,
.mips32r5,
.nan2008,
}),
};
result[@enumToInt(Feature.mips3_32)] = .{
.llvm_name = "mips3_32",
.description = "Subset of MIPS-III that is also in MIPS32 [highly experimental]",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.mips3_32r2)] = .{
.llvm_name = "mips3_32r2",
.description = "Subset of MIPS-III that is also in MIPS32r2 [highly experimental]",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.mips4)] = .{
.llvm_name = "mips4",
.description = "MIPS IV ISA Support",
.dependencies = featureSet(&[_]Feature{
.mips3,
.mips4_32,
.mips4_32r2,
}),
};
result[@enumToInt(Feature.mips4_32)] = .{
.llvm_name = "mips4_32",
.description = "Subset of MIPS-IV that is also in MIPS32 [highly experimental]",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.mips4_32r2)] = .{
.llvm_name = "mips4_32r2",
.description = "Subset of MIPS-IV that is also in MIPS32r2 [highly experimental]",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.mips5)] = .{
.llvm_name = "mips5",
.description = "MIPS V ISA Support [highly experimental]",
.dependencies = featureSet(&[_]Feature{
.mips4,
.mips5_32r2,
}),
};
result[@enumToInt(Feature.mips5_32r2)] = .{
.llvm_name = "mips5_32r2",
.description = "Subset of MIPS-V that is also in MIPS32r2 [highly experimental]",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.mips64)] = .{
.llvm_name = "mips64",
.description = "Mips64 ISA Support",
.dependencies = featureSet(&[_]Feature{
.mips32,
.mips5,
}),
};
result[@enumToInt(Feature.mips64r2)] = .{
.llvm_name = "mips64r2",
.description = "Mips64r2 ISA Support",
.dependencies = featureSet(&[_]Feature{
.mips32r2,
.mips64,
}),
};
result[@enumToInt(Feature.mips64r3)] = .{
.llvm_name = "mips64r3",
.description = "Mips64r3 ISA Support",
.dependencies = featureSet(&[_]Feature{
.mips32r3,
.mips64r2,
}),
};
result[@enumToInt(Feature.mips64r5)] = .{
.llvm_name = "mips64r5",
.description = "Mips64r5 ISA Support",
.dependencies = featureSet(&[_]Feature{
.mips32r5,
.mips64r3,
}),
};
result[@enumToInt(Feature.mips64r6)] = .{
.llvm_name = "mips64r6",
.description = "Mips64r6 ISA Support [experimental]",
.dependencies = featureSet(&[_]Feature{
.abs2008,
.mips32r6,
.mips64r5,
.nan2008,
}),
};
result[@enumToInt(Feature.msa)] = .{
.llvm_name = "msa",
.description = "Mips MSA ASE",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.mt)] = .{
.llvm_name = "mt",
.description = "Mips MT ASE",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.nan2008)] = .{
.llvm_name = "nan2008",
.description = "IEEE 754-2008 NaN encoding",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.noabicalls)] = .{
.llvm_name = "noabicalls",
.description = "Disable SVR4-style position-independent code",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.nomadd4)] = .{
.llvm_name = "nomadd4",
.description = "Disable 4-operand madd.fmt and related instructions",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.nooddspreg)] = .{
.llvm_name = "nooddspreg",
.description = "Disable odd numbered single-precision registers",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.p5600)] = .{
.llvm_name = "p5600",
.description = "The P5600 Processor",
.dependencies = featureSet(&[_]Feature{
.mips32r5,
}),
};
result[@enumToInt(Feature.ptr64)] = .{
.llvm_name = "ptr64",
.description = "Pointers are 64-bit wide",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.single_float)] = .{
.llvm_name = "single-float",
.description = "Only supports single precision float",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.soft_float)] = .{
.llvm_name = "soft-float",
.description = "Does not support floating point instructions",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.sym32)] = .{
.llvm_name = "sym32",
.description = "Symbols are 32 bit on Mips64",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.use_indirect_jump_hazard)] = .{
.llvm_name = "use-indirect-jump-hazard",
.description = "Use indirect jump guards to prevent certain speculation based attacks",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.use_tcc_in_div)] = .{
.llvm_name = "use-tcc-in-div",
.description = "Force the assembler to use trapping",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.vfpu)] = .{
.llvm_name = "vfpu",
.description = "Enable vector FPU instructions",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.virt)] = .{
.llvm_name = "virt",
.description = "Mips Virtualization ASE",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.xgot)] = .{
.llvm_name = "xgot",
.description = "Assume 32-bit GOT",
.dependencies = featureSet(&[_]Feature{}),
};
const ti = @typeInfo(Feature);
for (result) |*elem, i| {
elem.index = i;
elem.name = ti.Enum.fields[i].name;
}
break :blk result;
};
pub const cpu = struct {
pub const generic = CpuModel{
.name = "generic",
.llvm_name = "generic",
.features = featureSet(&[_]Feature{
.mips32,
}),
};
pub const mips1 = CpuModel{
.name = "mips1",
.llvm_name = "mips1",
.features = featureSet(&[_]Feature{
.mips1,
}),
};
pub const mips2 = CpuModel{
.name = "mips2",
.llvm_name = "mips2",
.features = featureSet(&[_]Feature{
.mips2,
}),
};
pub const mips3 = CpuModel{
.name = "mips3",
.llvm_name = "mips3",
.features = featureSet(&[_]Feature{
.mips3,
}),
};
pub const mips32 = CpuModel{
.name = "mips32",
.llvm_name = "mips32",
.features = featureSet(&[_]Feature{
.mips32,
}),
};
pub const mips32r2 = CpuModel{
.name = "mips32r2",
.llvm_name = "mips32r2",
.features = featureSet(&[_]Feature{
.mips32r2,
}),
};
pub const mips32r3 = CpuModel{
.name = "mips32r3",
.llvm_name = "mips32r3",
.features = featureSet(&[_]Feature{
.mips32r3,
}),
};
pub const mips32r5 = CpuModel{
.name = "mips32r5",
.llvm_name = "mips32r5",
.features = featureSet(&[_]Feature{
.mips32r5,
}),
};
pub const mips32r6 = CpuModel{
.name = "mips32r6",
.llvm_name = "mips32r6",
.features = featureSet(&[_]Feature{
.mips32r6,
}),
};
pub const mips4 = CpuModel{
.name = "mips4",
.llvm_name = "mips4",
.features = featureSet(&[_]Feature{
.mips4,
}),
};
pub const mips5 = CpuModel{
.name = "mips5",
.llvm_name = "mips5",
.features = featureSet(&[_]Feature{
.mips5,
}),
};
pub const mips64 = CpuModel{
.name = "mips64",
.llvm_name = "mips64",
.features = featureSet(&[_]Feature{
.mips64,
}),
};
pub const mips64r2 = CpuModel{
.name = "mips64r2",
.llvm_name = "mips64r2",
.features = featureSet(&[_]Feature{
.mips64r2,
}),
};
pub const mips64r3 = CpuModel{
.name = "mips64r3",
.llvm_name = "mips64r3",
.features = featureSet(&[_]Feature{
.mips64r3,
}),
};
pub const mips64r5 = CpuModel{
.name = "mips64r5",
.llvm_name = "mips64r5",
.features = featureSet(&[_]Feature{
.mips64r5,
}),
};
pub const mips64r6 = CpuModel{
.name = "mips64r6",
.llvm_name = "mips64r6",
.features = featureSet(&[_]Feature{
.mips64r6,
}),
};
pub const octeon = CpuModel{
.name = "octeon",
.llvm_name = "octeon",
.features = featureSet(&[_]Feature{
.cnmips,
.mips64r2,
}),
};
pub const @"octeon+" = CpuModel{
.name = "octeon+",
.llvm_name = "octeon+",
.features = featureSet(&[_]Feature{
.cnmips,
.cnmipsp,
.mips64r2,
}),
};
pub const p5600 = CpuModel{
.name = "p5600",
.llvm_name = "p5600",
.features = featureSet(&[_]Feature{
.p5600,
}),
};
}; | lib/std/target/mips.zig |
const std = @import("std");
const warn = std.debug.warn;
const File = std.fs.File;
const files = @import("../Files.zig");
const loadFile = files.loadFile;
pub const c = @cImport({
@cInclude("zstd.h");
});
fn writeCompressed(path: []const u8, data: []const u8, original_size: u32) !void {
var file = try std.fs.cwd().openFile(path, std.fs.File.OpenFlags{ .write = true });
defer file.close();
const header = [12]u8{ 0x88, 0x7c, 0x77, 0x6a, 0xee, 0x55, 0xdd, 0xcc, 0x37, 0x9a, 0x8b, 0xef };
_ = try file.write(header[0..]);
_ = try file.write(@ptrCast([*c]const u8, &original_size)[0..4]);
_ = try file.write(data);
}
pub fn compressFile(input_file_path: []const u8, output_file_path: []const u8, allocator: *std.mem.Allocator) !void {
var input_file_data = try loadFile(input_file_path, allocator);
defer allocator.free(input_file_data);
if (input_file_data.len == 0) {
return error.EmptyFile;
}
const max_size = c.ZSTD_compressBound(input_file_data.len);
var compressed_data = try allocator.alignedAlloc(u8, 16, max_size);
const compressed_size = c.ZSTD_compress(compressed_data.ptr, max_size, input_file_data.ptr, input_file_data.len, 22);
if (compressed_size == 0) {
return error.ZSTDError;
}
if (@intCast(usize, compressed_size) >= input_file_data.len) {
return error.CompressedBiggerThanOriginal;
} else {
try writeCompressed(output_file_path, compressed_data[0..@intCast(usize, compressed_size)], @intCast(u32, input_file_data.len));
}
}
pub fn isCompressedFile(file_data: []const u8, original_data_size: ?*u32) !bool {
const data_u32 = std.mem.bytesAsSlice(u32, file_data);
if (file_data.len <= 16) {
return false;
}
if (data_u32[0] != 0x6a777c88 or data_u32[1] != 0xccdd55ee or data_u32[2] != 0xef8b9a37) {
return false;
}
if (original_data_size != null) {
const originalDataSize = data_u32[3];
if (originalDataSize == 0) {
return error.InvalidFile;
} else {
original_data_size.?.* = originalDataSize;
}
}
return true;
}
pub fn decompress(file_data: []align(4) u8, allocator: *std.mem.Allocator) ![]align(4) u8 {
if (file_data.len <= 16 or file_data.len >= 2147483663) {
return error.InvalidFile;
}
const data_u32 = std.mem.bytesAsSlice(u32, file_data[0..16]);
if (data_u32[0] != 0x6a777c88 or data_u32[1] != 0xccdd55ee or data_u32[2] != 0xef8b9a37) {
return file_data;
}
const originalDataSize = data_u32[3];
if (originalDataSize == 0 or originalDataSize > 2147483647) {
return error.InvalidFile;
}
var decompressed_data = try allocator.alignedAlloc(u8, 16, originalDataSize);
errdefer allocator.free(decompressed_data);
const r = c.ZSTD_decompress(decompressed_data.ptr, @intCast(usize, originalDataSize), file_data[16..].ptr, file_data.len - 16);
if (r != originalDataSize) {
return error.ZSTDError;
}
return decompressed_data;
}
test "isCompressedFile" {
var original_data_size: u32 = 0;
var file_data = [5]u32{ 0x6a777c88, 0xccdd55ee, 0xef8b9a37, 0, 111 };
std.testing.expectError(error.InvalidFile, isCompressedFile(std.mem.sliceAsBytes(file_data[0..]), &original_data_size));
} | src/Compress/Compress.zig |
usingnamespace @import("root").preamble;
const Order = std.math.Order;
const rb = lib.containers.rbtree;
const AddrNode = rb.Node(rb_features);
const SizeNode = rb.Node(rb_features);
const AddrTree = rb.Tree(Range, "addr_node", addr_config);
const SizeTree = rb.Tree(Range, "size_node", size_config);
const PlacementResult = struct {
effective_size: u64,
offset: u64,
};
const RangePlacement = struct {
range: *Range,
placement: PlacementResult,
};
const Range = struct {
size_node: SizeNode = undefined,
addr_node: AddrNode = undefined,
base: usize,
size: usize,
fn getReturnedBase(self: *const @This(), alignment: usize) usize {
if (alignment == 0)
return self.base;
return ((self.base + alignment - 1) / alignment) * alignment;
}
fn getEffectiveSize(size: usize, size_alignment: usize) usize {
if (size_alignment == 0)
return size;
return ((size + size_alignment - 1) / size_alignment) * size_alignment;
}
pub fn tryPlace(
self: *const @This(),
size: usize,
alignment: usize,
size_alignment: usize,
) ?PlacementResult {
const rbase = self.getReturnedBase(alignment);
const es = getEffectiveSize(size, size_alignment);
const offset = rbase - self.base;
if (offset + es <= self.size) {
return PlacementResult{
.effective_size = es,
.offset = offset,
};
}
return null;
}
fn contains(self: *const @This(), addr: usize) bool {
return addr >= self.base and addr < self.base + self.size;
}
};
const AddressComparator = struct {
pub fn compare(self: *const @This(), left: *const Range, right: *const Range) bool {
return left.base >= right.base;
}
};
const SizeComparator = struct {
pub fn compare(self: *const @This(), left: *const Range, right: *const Range) bool {
return left.size >= right.size;
}
};
pub fn RangeAllocator(comptime LockType: type) type {
return struct {
ra: RangeAlloc,
allocator: std.mem.Allocator = .{
.allocFn = alloc,
.resizeFn = resize,
},
lock: LockType = .{},
pub fn init(backing_allocator: *std.mem.Allocator) @This() {
return .{
.ra = .{
.backing_allocator = backing_allocator,
},
};
}
fn alloc(
allocator: *std.mem.Allocator,
len: usize,
ptr_align: u29,
len_align: u29,
ret_addr: usize,
) std.mem.Allocator.Error![]u8 {
const self = @fieldParentPtr(@This(), "allocator", allocator);
self.lock.lock();
defer self.lock.unlock();
return self.ra.allocateAnywhere(len, ptr_align, len_align) catch |err| {
switch (err) {
error.OutOfMemory => return error.OutOfMemory,
else => unreachable,
}
};
}
fn resize(
allocator: *std.mem.Allocator,
old_mem: []u8,
old_align: u29,
new_size: usize,
len_align: u29,
ret_addr: usize,
) std.mem.Allocator.Error!usize {
const self = @fieldParentPtr(@This(), "allocator", allocator);
self.lock.lock();
defer self.lock.unlock();
if (new_size != 0) {
@panic("Todo: RangeAllocator.resize(): actually resize");
}
// Free this address
const new_range = self.ra.giveRange(.{
.base = @ptrToInt(old_mem.ptr),
.size = old_mem.len,
}) catch |err| {
switch (err) {
error.OutOfMemory => return error.OutOfMemory,
else => unreachable,
}
};
return 0;
}
};
}
pub const RangeAlloc = struct {
range_node_head: ?*Range = null,
by_addr: AddrTree = AddrTree.init(.{}, {}),
by_size: SizeTree = SizeTree.init(.{}, {}),
backing_allocator: *std.mem.Allocator,
pub fn allocateAnywhere(
self: *@This(),
len: usize,
ptr_align: usize,
len_align: usize,
) ![]u8 {
const placement = try self.findPlacementAnywhere(len, ptr_align, len_align);
const range = placement.range;
const pmt = placement.placement;
const ret = @intToPtr([*]u8, range.base + pmt.offset)[0..len];
self.maintainTree(range, pmt);
return ret;
}
pub fn allocateAt(
self: *@This(),
addr: usize,
len: usize,
) ![]u8 {
const placement = try self.findPlacementAt(addr, len);
const range = placement.range;
const pmt = placement.placement;
const ret = @intToPtr([*]u8, range.base + pmt.offset)[0..len];
self.maintainTree(range, pmt);
return ret;
}
fn maintainTree(self: *@This(), range: *Range, pmt: PlacementResult) void {
// Node maintenance
const has_data_before = pmt.offset != 0;
const has_data_after = pmt.offset + pmt.effective_size < range.size;
if (has_data_before and has_data_after) {
// Add the new range
const new_range_offset = pmt.offset + pmt.effective_size;
const new_range = self.addRange(.{
.base = range.base + new_range_offset,
.size = range.size - new_range_offset,
});
// Overwrite the old entry
// Update size node (requires reinsertion)
self.by_size.remove(range);
range.size = pmt.offset;
self.by_size.insert(range);
} else if (has_data_after or has_data_before) {
// Reuse the single node
if (has_data_before) {
// Cool, only the size has changed, no reinsertion on the addr node
range.size = pmt.offset;
} else {
// Update addr node and reinsert
self.by_addr.remove(range);
range.size -= pmt.effective_size;
range.base += pmt.effective_size;
self.by_addr.insert(range);
}
// No matter what, we have to update the size node.
self.by_size.remove(range);
self.by_size.insert(range);
} else {
// Remove the node entirely
self.by_addr.remove(range);
self.by_size.remove(range);
self.freeRange(range);
}
if (debug)
self.dumpState();
}
fn locateAddressNode(self: *@This(), size_node: *Range) *Range {
const node = self.by_addr.lookup(&size_node.node);
if (node) |n| {
return @fieldParentPtr(Range, "node", n);
}
unreachable;
}
fn findPlacementAnywhere(
self: *@This(),
size: usize,
alignment: usize,
size_alignment: usize,
) !RangePlacement {
{
const size_finder: struct {
size: usize,
pub fn check(finder: *const @This(), range: *const Range) bool {
return range.size >= finder.size;
}
} = .{ .size = size };
var current_range = self.by_size.lowerBound(@TypeOf(size_finder), &size_finder);
while (current_range) |range| {
if (range.tryPlace(size, alignment, size_alignment)) |placement| {
return RangePlacement{
.range = range,
.placement = placement,
};
}
current_range = self.by_size.iterators.next(range);
}
}
// We found nothing
return error.OutOfMemory;
}
fn findPlacementAt(
self: *@This(),
addr: usize,
size: usize,
) !RangePlacement {
{
const addr_finder: struct {
addr: usize,
pub fn check(finder: *const @This(), range: *const Range) bool {
return range.base + range.size >= finder.addr;
}
} = .{ .addr = addr };
var range = self.by_addr.lowerBound(@TypeOf(addr_finder), &addr_finder);
if (range) |r| {
if (r.contains(addr) and r.contains(addr + size - 1)) {
return RangePlacement{
.range = r,
.placement = .{
.offset = addr - r.base,
.effective_size = size,
},
};
}
}
}
return error.OutOfMemory;
}
fn freeRange(self: *@This(), node: *Range) void {
const new_head = @ptrCast(*?*Range, node);
new_head.* = self.range_node_head;
self.range_node_head = node;
}
fn consumeNodeBytes(self: *@This()) !void {
const nodes = try self.backing_allocator.alloc(Range, 0x1000 / @sizeOf(Range));
//const nodes = try os.memory.pmm.phys_heap.alloc(Range, 0x1000 / @sizeOf(Range));
for (nodes) |*n| {
self.freeRange(n);
}
}
pub fn giveRange(self: *@This(), in_range: Range) !void {
const range = try self.addRange(in_range);
self.mergeRanges(range);
}
fn addRange(self: *@This(), in_range: Range) !*Range {
const range = try self.allocRange();
range.* = in_range;
self.by_size.insert(range);
self.by_addr.insert(range);
return range;
}
fn allocRange(self: *@This()) !*Range {
if (self.range_node_head == null) {
try self.consumeNodeBytes();
}
if (self.range_node_head) |head| {
const ret = head;
self.range_node_head = @ptrCast(*?*Range, head).*;
return ret;
}
unreachable;
}
// Needs to be a node in the addr tree
fn mergeRanges(self: *@This(), range_in: *Range) void {
var current = range_in;
// Try to merge to the left
while (self.by_addr.iterators.prev(current)) |prev| {
if (self.tryMerge(prev, current)) {
self.by_addr.remove(current);
self.by_size.remove(current);
self.freeRange(current);
current = prev;
} else {
break;
}
}
// Try to merge to the right
while (self.by_addr.iterators.next(current)) |next| {
if (self.tryMerge(current, next)) {
self.by_addr.remove(next);
self.by_size.remove(next);
self.freeRange(next);
} else {
break;
}
}
}
fn tryMerge(self: *@This(), low: *Range, high: *const Range) bool {
if (low.base + low.size == high.base) {
low.size += high.size;
return true;
}
return false;
}
};
const min_materialize_size = 64 * 1024;
const node_block_size = 0x1000 * @sizeOf(Range) / 16;
const debug = false;
const rb_features: rb.Features = .{
.enable_iterators_cache = true,
.enable_kth_queries = false,
.enable_not_associatve_augment = false,
};
const addr_config: rb.Config = .{
.features = rb_features,
.augment_callback = null,
.comparator = AddressComparator,
};
const size_config: rb.Config = .{
.features = rb_features,
.augment_callback = null,
.comparator = SizeComparator,
}; | lib/memory/range_alloc.zig |
const uefi = @import("std").os.uefi;
const Guid = uefi.Guid;
const Status = uefi.Status;
const hii = uefi.protocols.hii;
/// Database manager for HII-related data structures.
pub const HIIDatabaseProtocol = extern struct {
_new_package_list: Status, // TODO
_remove_package_list: fn (*const HIIDatabaseProtocol, hii.HIIHandle) callconv(.C) Status,
_update_package_list: fn (*const HIIDatabaseProtocol, hii.HIIHandle, *const hii.HIIPackageList) callconv(.C) Status,
_list_package_lists: fn (*const HIIDatabaseProtocol, u8, ?*const Guid, *usize, [*]hii.HIIHandle) callconv(.C) Status,
_export_package_lists: fn (*const HIIDatabaseProtocol, ?hii.HIIHandle, *usize, *hii.HIIPackageList) callconv(.C) Status,
_register_package_notify: Status, // TODO
_unregister_package_notify: Status, // TODO
_find_keyboard_layouts: Status, // TODO
_get_keyboard_layout: Status, // TODO
_set_keyboard_layout: Status, // TODO
_get_package_list_handle: Status, // TODO
/// Removes a package list from the HII database.
pub fn removePackageList(self: *const HIIDatabaseProtocol, handle: hii.HIIHandle) Status {
return self._remove_package_list(self, handle);
}
/// Update a package list in the HII database.
pub fn updatePackageList(self: *const HIIDatabaseProtocol, handle: hii.HIIHandle, buffer: *const hii.HIIPackageList) Status {
return self._update_package_list(self, handle, buffer);
}
/// Determines the handles that are currently active in the database.
pub fn listPackageLists(self: *const HIIDatabaseProtocol, package_type: u8, package_guid: ?*const Guid, buffer_length: *usize, handles: [*]hii.HIIHandle) Status {
return self._list_package_lists(self, package_type, package_guid, buffer_length, handles);
}
/// Exports the contents of one or all package lists in the HII database into a buffer.
pub fn exportPackageLists(self: *const HIIDatabaseProtocol, handle: ?hii.HIIHandle, buffer_size: *usize, buffer: *hii.HIIPackageList) Status {
return self._export_package_lists(self, handle, buffer_size, buffer);
}
pub const guid align(8) = Guid{
.time_low = 0xef9fc172,
.time_mid = 0xa1b2,
.time_high_and_version = 0x4693,
.clock_seq_high_and_reserved = 0xb3,
.clock_seq_low = 0x27,
.node = [_]u8{ 0x6d, 0x32, 0xfc, 0x41, 0x60, 0x42 },
};
}; | lib/std/os/uefi/protocols/hii_database_protocol.zig |
const std = @import("std");
const builtin = @import("builtin");
const tvg = @import("tinyvg.zig");
const parsing = tvg.parsing;
/// Renders a TinyVG graphic and returns the rendered image.
/// - `temporary_allocator` is used for temporary allocations.
/// - `image_allocator` is used to allocate the final image.
/// - `size_hint` determines the way how the final graphic is specified
/// - `anti_alias` determines the level of anti-aliasing if not `null`
/// - `data` is a slice providing the TinyVG graphic
pub fn renderBuffer(
temporary_allocator: std.mem.Allocator,
image_allocator: std.mem.Allocator,
size_hint: SizeHint,
anti_alias: ?AntiAliasing,
data: []const u8,
) !Image {
var stream = std.io.fixedBufferStream(data);
return try renderStream(
temporary_allocator,
image_allocator,
size_hint,
anti_alias,
stream.reader(),
);
}
/// Renders a TinyVG graphic and returns the rendered image.
/// - `temporary_allocator` is used for temporary allocations.
/// - `image_allocator` is used to allocate the final image.
/// - `size_hint` determines the way how the final graphic is specified
/// - `anti_alias` determines the level of anti-aliasing if not `null`
/// - `reader` is a stream providing the TinyVG graphic
pub fn renderStream(
temporary_allocator: std.mem.Allocator,
image_allocator: std.mem.Allocator,
size_hint: SizeHint,
anti_alias: ?AntiAliasing,
reader: anytype,
) !Image {
var parser = try tvg.parse(temporary_allocator, reader);
defer parser.deinit();
const target_size: Size = switch (size_hint) {
.inherit => Size{ .width = parser.header.width, .height = parser.header.height },
.size => |size| size,
.width => |width| Size{
.width = width,
.height = (parser.header.width * parser.header.height) / width,
},
.height => |height| Size{
.width = (parser.header.height * parser.header.width) / height,
.height = height,
},
};
const super_scale: u32 = if (anti_alias) |factor|
@enumToInt(factor)
else
1;
const render_size = Size{
.width = target_size.width * super_scale,
.height = target_size.height * super_scale,
};
const target_pixel_count = @as(usize, target_size.width) * @as(usize, target_size.height);
const render_pixel_count = @as(usize, render_size.width) * @as(usize, render_size.height);
const framebuffer = Framebuffer{
.slice = try temporary_allocator.alloc(Color, render_pixel_count),
.stride = render_size.width,
.width = render_size.width,
.height = render_size.height,
};
defer temporary_allocator.free(framebuffer.slice);
// Fill the destination buffer with magic magenta. None if this will be visible
// in the end, but it will show users where they do wrong alpha interpolation
// by bleeding in magenta
std.mem.set(Color, framebuffer.slice, Color{ .r = 1, .g = 0, .b = 1, .a = 0 });
while (try parser.next()) |cmd| {
try renderCommand(&framebuffer, parser.header, parser.color_table, cmd, temporary_allocator);
}
var image = Image{
.pixels = try image_allocator.alloc(Color8, target_pixel_count),
.width = target_size.width,
.height = target_size.height,
};
errdefer image_allocator.free(image.pixels);
// resolve anti-aliasing
for (image.pixels) |*pixel, i| {
const x = i % image.width;
const y = i / image.width;
// stores premultiplied rgb + linear alpha
// premultiplication is necessary as
// (1,1,1,50%) over (0,0,0,0%) must result in (1,1,1,25%) and not (0.5,0.5,0.5,25%).
// This will only happen if we fully ignore the fraction of transparent colors in the final result.
// The average must also be computed in linear space, as we would get invalid color blending otherwise.
var color = std.mem.zeroes([4]f32);
var dy: usize = 0;
while (dy < super_scale) : (dy += 1) {
var dx: usize = 0;
while (dx < super_scale) : (dx += 1) {
const sx = x * super_scale + dx;
const sy = y * super_scale + dy;
const src_color = framebuffer.slice[sy * framebuffer.stride + sx];
const a = src_color.a;
// Create premultiplied linear colors
color[0] += a * mapToLinear(src_color.r);
color[1] += a * mapToLinear(src_color.g);
color[2] += a * mapToLinear(src_color.b);
color[3] += a;
}
}
// Compute average
for (color) |*chan| {
chan.* = chan.* / @intToFloat(f32, super_scale * super_scale);
}
const final_a = color[3];
if (final_a > 0.0) {
pixel.* = Color8{
// unmultiply the alpha and apply the gamma
.r = mapToGamma8(color[0] / final_a),
.g = mapToGamma8(color[1] / final_a),
.b = mapToGamma8(color[2] / final_a),
.a = @floatToInt(u8, 255.0 * color[3]),
};
} else {
pixel.* = Color8{ .r = 0xFF, .g = 0x00, .b = 0xFF, .a = 0x00 };
}
}
return image;
}
const gamma = 2.2;
fn mapToLinear(val: f32) f32 {
return std.math.pow(f32, val, gamma);
}
fn mapToGamma(val: f32) f32 {
return std.math.pow(f32, val, 1.0 / gamma);
}
fn mapToGamma8(val: f32) u8 {
return @floatToInt(u8, 255.0 * mapToGamma(val));
}
const Framebuffer = struct {
const Self = @This();
// private API
slice: []Color,
stride: usize,
// public API
width: usize,
height: usize,
pub fn setPixel(self: Self, x: isize, y: isize, src_color: tvg.Color) void {
if (x < 0 or y < 0)
return;
if (x >= self.width or y >= self.height)
return;
const offset = (std.math.cast(usize, y) catch return) * self.stride + (std.math.cast(usize, x) catch return);
const destination_pixel = &self.slice[offset];
const dst_color = destination_pixel.*;
if (src_color.a == 0) {
return;
}
if (src_color.a == 255) {
destination_pixel.* = src_color;
return;
}
// src over dst
// a over b
const src_alpha = src_color.a;
const dst_alpha = dst_color.a;
const fin_alpha = src_alpha + (1.0 - src_alpha) * dst_alpha;
destination_pixel.* = Color{
.r = lerpColor(src_color.r, dst_color.r, src_alpha, dst_alpha, fin_alpha),
.g = lerpColor(src_color.g, dst_color.g, src_alpha, dst_alpha, fin_alpha),
.b = lerpColor(src_color.b, dst_color.b, src_alpha, dst_alpha, fin_alpha),
.a = fin_alpha,
};
}
fn lerpColor(src: f32, dst: f32, src_alpha: f32, dst_alpha: f32, fin_alpha: f32) f32 {
const src_val = mapToLinear(src);
const dst_val = mapToLinear(dst);
const value = (1.0 / fin_alpha) * (src_alpha * src_val + (1.0 - src_alpha) * dst_alpha * dst_val);
return mapToGamma(value);
}
};
pub const Color8 = extern struct { r: u8, g: u8, b: u8, a: u8 };
pub const SizeHint = union(enum) {
inherit,
width: u32,
height: u32,
size: Size,
};
pub const Size = struct {
width: u32,
height: u32,
};
pub const AntiAliasing = enum(u32) {
x1 = 1,
x4 = 2,
x9 = 3,
x16 = 4,
x25 = 6,
x49 = 7,
x64 = 8,
_,
};
pub const Image = struct {
width: u32,
height: u32,
pixels: []Color8,
pub fn deinit(self: *Image, allocator: std.mem.Allocator) void {
allocator.free(self.pixels);
self.* = undefined;
}
};
pub fn isFramebuffer(comptime T: type) bool {
const FbType = if (@typeInfo(T) == .Pointer)
std.meta.Child(T)
else
T;
return std.meta.trait.hasFn("setPixel")(FbType) and
std.meta.trait.hasField("width")(FbType) and
std.meta.trait.hasField("height")(FbType);
}
const Point = tvg.Point;
const Rectangle = tvg.Rectangle;
const Color = tvg.Color;
const Style = tvg.Style;
// TODO: Make these configurable
const circle_divs = 100;
const bezier_divs = 16;
const max_path_len = 512;
const IndexSlice = struct { offset: usize, len: usize };
// this is the allocation threshold for images.
// when we go over this, we require `allocator` to be set.
const temp_buffer_size = 256;
/// Renders a single TinyVG command. Performs no aliasing, super sampling or blending.
/// - `framebuffer` implements the backing storage for rendering, must provide function `setPixel(x:usize,y:usize,TvgColor)` and fields `width` and `height`.
/// - `header` is the TinyVG header
/// - `color_table` is the color table that is used for rendering.
/// - `cmd` is the draw command that should be rendered.
pub fn renderCommand(
/// A struct that exports a single function `setPixel(x: isize, y: isize, color: [4]u8) void` as well as two fields width and height
framebuffer: anytype,
/// The parsed header of a TVG
header: parsing.Header,
/// The color lookup table
color_table: []const tvg.Color,
/// The command that should be executed.
cmd: parsing.DrawCommand,
/// When given, the `renderCommand` is able to render complexer graphics
allocator: ?std.mem.Allocator,
) !void {
if (!comptime isFramebuffer(@TypeOf(framebuffer)))
@compileError("framebuffer needs fields width, height and function setPixel!");
const fb_width = @intToFloat(f32, framebuffer.width);
const fb_height = @intToFloat(f32, framebuffer.height);
// std.debug.print("render {}\n", .{cmd});#
var painter = Painter{
.scale_x = fb_width / @intToFloat(f32, header.width),
.scale_y = fb_height / @intToFloat(f32, header.height),
};
switch (cmd) {
.fill_polygon => |data| {
painter.fillPolygonList(framebuffer, color_table, data.style, &[_][]const Point{data.vertices}, .even_odd);
},
.fill_rectangles => |data| {
for (data.rectangles) |rect| {
painter.fillRectangle(framebuffer, rect.x, rect.y, rect.width, rect.height, color_table, data.style);
}
},
.fill_path => |data| {
var point_store = FixedBufferList(Point, temp_buffer_size).init(allocator);
defer point_store.deinit();
var slice_store = FixedBufferList(IndexSlice, temp_buffer_size).init(allocator);
defer slice_store.deinit();
try renderPath(&point_store, null, &slice_store, data.path, 0.0);
var slices: [max_path_len][]const Point = undefined;
for (slice_store.items()) |src, i| {
slices[i] = point_store.items()[src.offset..][0..src.len];
}
painter.fillPolygonList(
framebuffer,
color_table,
data.style,
slices[0..slice_store.items().len],
.even_odd,
);
},
.draw_lines => |data| {
for (data.lines) |line| {
painter.drawLine(framebuffer, color_table, data.style, data.line_width, data.line_width, line);
}
},
.draw_line_strip => |data| {
for (data.vertices[1..]) |end, i| {
const start = data.vertices[i]; // is actually [i-1], but we access the slice off-by-one!
painter.drawLine(framebuffer, color_table, data.style, data.line_width, data.line_width, .{
.start = start,
.end = end,
});
}
},
.draw_line_loop => |data| {
var start_index: usize = data.vertices.len - 1;
for (data.vertices) |end, end_index| {
const start = data.vertices[start_index];
painter.drawLine(framebuffer, color_table, data.style, data.line_width, data.line_width, .{
.start = start,
.end = end,
});
start_index = end_index;
}
},
.draw_line_path => |data| {
var point_store = FixedBufferList(Point, temp_buffer_size).init(allocator);
defer point_store.deinit();
var width_store = FixedBufferList(f32, temp_buffer_size).init(allocator);
defer width_store.deinit();
var slice_store = FixedBufferList(IndexSlice, temp_buffer_size).init(allocator);
defer slice_store.deinit();
try renderPath(&point_store, &width_store, &slice_store, data.path, data.line_width);
var slices: [slice_store.buffer.len][]const Point = undefined;
for (slice_store.items()) |src, i| {
slices[i] = point_store.items()[src.offset..][0..src.len];
}
const line_widths = width_store.items();
for (slices[0..slice_store.items().len]) |vertices| {
for (vertices[1..]) |end, i| {
const start = vertices[i]; // is actually [i-1], but we access the slice off-by-one!
painter.drawLine(framebuffer, color_table, data.style, line_widths[i], line_widths[i + 1], .{
.start = start,
.end = end,
});
}
}
},
.outline_fill_polygon => |data| {
painter.fillPolygonList(framebuffer, color_table, data.fill_style, &[_][]const Point{data.vertices}, .even_odd);
var start_index: usize = data.vertices.len - 1;
for (data.vertices) |end, end_index| {
const start = data.vertices[start_index];
painter.drawLine(framebuffer, color_table, data.line_style, data.line_width, data.line_width, .{
.start = start,
.end = end,
});
start_index = end_index;
}
},
.outline_fill_rectangles => |data| {
for (data.rectangles) |rect| {
painter.fillRectangle(framebuffer, rect.x, rect.y, rect.width, rect.height, color_table, data.fill_style);
var tl = Point{ .x = rect.x, .y = rect.y };
var tr = Point{ .x = rect.x + rect.width, .y = rect.y };
var bl = Point{ .x = rect.x, .y = rect.y + rect.height };
var br = Point{ .x = rect.x + rect.width, .y = rect.y + rect.height };
painter.drawLine(framebuffer, color_table, data.line_style, data.line_width, data.line_width, .{ .start = tl, .end = tr });
painter.drawLine(framebuffer, color_table, data.line_style, data.line_width, data.line_width, .{ .start = tr, .end = br });
painter.drawLine(framebuffer, color_table, data.line_style, data.line_width, data.line_width, .{ .start = br, .end = bl });
painter.drawLine(framebuffer, color_table, data.line_style, data.line_width, data.line_width, .{ .start = bl, .end = tl });
}
},
.outline_fill_path => |data| {
var point_store = FixedBufferList(Point, temp_buffer_size).init(allocator);
defer point_store.deinit();
var width_store = FixedBufferList(f32, temp_buffer_size).init(allocator);
defer width_store.deinit();
var slice_store = FixedBufferList(IndexSlice, temp_buffer_size).init(allocator);
defer slice_store.deinit();
try renderPath(&point_store, &width_store, &slice_store, data.path, data.line_width);
var slices: [max_path_len][]const Point = undefined;
for (slice_store.items()) |src, i| {
slices[i] = point_store.items()[src.offset..][0..src.len];
}
painter.fillPolygonList(framebuffer, color_table, data.fill_style, slices[0..slice_store.items().len], .even_odd);
const line_widths = width_store.items();
for (slices[0..slice_store.items().len]) |vertices| {
for (vertices[1..]) |end, i| {
const start = vertices[i]; // is actually [i-1], but we access the slice off-by-one!
painter.drawLine(framebuffer, color_table, data.line_style, line_widths[i], line_widths[i + 1], .{
.start = start,
.end = end,
});
}
}
},
}
}
pub fn renderPath(
point_list: *FixedBufferList(Point, temp_buffer_size),
width_list: ?*FixedBufferList(f32, temp_buffer_size),
slice_list: *FixedBufferList(IndexSlice, temp_buffer_size),
path: tvg.Path,
line_width: f32,
) !void {
const Helper = struct {
list: @TypeOf(point_list),
last: Point,
count: usize,
width_list: ?*FixedBufferList(f32, temp_buffer_size),
// Discard when point is in the vicinity of the last point (same pixel)
const pixel_delta = 0.25;
fn approxEqual(p0: Point, p1: Point, delta: f32) bool {
return std.math.approxEqAbs(f32, p0.x, p1.x, delta) and std.math.approxEqAbs(f32, p0.y, p1.y, delta);
}
fn append(self: *@This(), pt: Point, lw: f32) !void {
std.debug.assert(!std.math.isNan(pt.x));
std.debug.assert(!std.math.isNan(pt.y));
if (approxEqual(self.last, pt, pixel_delta))
return;
try self.list.append(pt);
if (self.width_list) |wl| {
errdefer _ = self.list.popBack();
try wl.append(lw);
}
self.last = pt;
self.count += 1;
}
fn back(self: @This()) Point {
return self.last;
}
};
var point_store = Helper{
.list = point_list,
.last = undefined,
.count = 0,
.width_list = width_list,
};
for (path.segments) |segment| {
const start_index = point_store.count;
var last_width = line_width;
try point_store.append(segment.start, last_width);
for (segment.commands) |node| {
const new_width = switch (node) {
.line => |val| val.line_width,
.horiz => |val| val.line_width,
.vert => |val| val.line_width,
.bezier => |val| val.line_width,
.arc_circle => |val| val.line_width,
.arc_ellipse => |val| val.line_width,
.close => |val| val.line_width,
.quadratic_bezier => |val| val.line_width,
} orelse last_width;
defer last_width = new_width;
switch (node) {
.line => |pt| try point_store.append(pt.data, pt.line_width orelse last_width),
.horiz => |x| try point_store.append(Point{ .x = x.data, .y = point_store.back().y }, x.line_width orelse last_width),
.vert => |y| try point_store.append(Point{ .x = point_store.back().x, .y = y.data }, y.line_width orelse last_width),
.bezier => |bezier| {
var previous = point_store.back();
const oct0_x = [4]f32{ previous.x, bezier.data.c0.x, bezier.data.c1.x, bezier.data.p1.x };
const oct0_y = [4]f32{ previous.y, bezier.data.c0.y, bezier.data.c1.y, bezier.data.p1.y };
var i: usize = 1;
while (i < bezier_divs) : (i += 1) {
const f = @intToFloat(f32, i) / @intToFloat(f32, bezier_divs);
const x = lerpAndReduceToOne(4, oct0_x, f);
const y = lerpAndReduceToOne(4, oct0_y, f);
try point_store.append(Point{ .x = x, .y = y }, lerp(last_width, new_width, f));
}
try point_store.append(bezier.data.p1, new_width);
},
.quadratic_bezier => |bezier| {
var previous = point_store.back();
const oct0_x = [3]f32{ previous.x, bezier.data.c.x, bezier.data.p1.x };
const oct0_y = [3]f32{ previous.y, bezier.data.c.y, bezier.data.p1.y };
var i: usize = 1;
while (i < bezier_divs) : (i += 1) {
const f = @intToFloat(f32, i) / @intToFloat(f32, bezier_divs);
const x = lerpAndReduceToOne(3, oct0_x, f);
const y = lerpAndReduceToOne(3, oct0_y, f);
try point_store.append(Point{ .x = x, .y = y }, lerp(last_width, new_width, f));
}
try point_store.append(bezier.data.p1, new_width);
},
// /home/felix/projects/forks/svg-curve-lib/src/js/svg-curve-lib.js
.arc_circle => |circle| {
// Filter out too-tiny ellipses so we don't go into NaN land
if (Helper.approxEqual(point_store.back(), circle.data.target, 1e-5))
continue;
try renderCircle(
&point_store,
point_store.back(),
circle.data.target,
circle.data.radius,
circle.data.large_arc,
circle.data.sweep,
last_width,
new_width,
);
},
.arc_ellipse => |ellipse| {
// Filter out too-tiny ellipses so we don't go into NaN land
if (Helper.approxEqual(point_store.back(), ellipse.data.target, 1e-5))
continue;
try renderEllipse(
&point_store,
point_store.back(),
ellipse.data.target,
ellipse.data.radius_x,
ellipse.data.radius_y,
ellipse.data.rotation,
ellipse.data.large_arc,
ellipse.data.sweep,
last_width,
new_width,
);
},
.close => |close| {
// if (node_index != (nodes.len - 1)) {
// // .close must be last!
// return error.InvalidData;
// }
try point_store.append(segment.start, close.line_width orelse last_width);
},
}
}
const end_index = point_store.count;
if (end_index > start_index) {
try slice_list.append(IndexSlice{
.offset = start_index,
.len = end_index - start_index,
});
}
}
}
inline fn toRadians(a: f32) f32 {
return std.math.pi / 180.0 * a;
}
inline fn cos(val: anytype) @TypeOf(val) {
// Workaround for https://github.com/ziglang/zig/issues/10318
if (builtin.os.tag.isDarwin()) {
return std.math.cos(val);
} else {
return @cos(val);
}
}
inline fn sin(val: anytype) @TypeOf(val) {
// Workaround for https://github.com/ziglang/zig/issues/10318
if (builtin.os.tag.isDarwin()) {
return std.math.sin(val);
} else {
return @sin(val);
}
}
inline fn sqrt(val: anytype) @TypeOf(val) {
return @sqrt(val);
}
inline fn abs(val: anytype) @TypeOf(val) {
return @fabs(val);
}
pub fn renderEllipse(
point_list: anytype,
p0: Point,
p1: Point,
radius_x: f32,
radius_y: f32,
rotation: f32,
large_arc: bool,
turn_left: bool,
start_width: f32,
end_width: f32,
) !void {
// std.debug.print("renderEllipse(({d:.3} {d:.3}), ({d:.3} {d:.3}), {d:.2}, {d:.2}, {d:.4}, large={}, left={})\n", .{
// p0.x,
// p0.y,
// p1.x,
// p1.y,
// radius_x,
// radius_y,
// rotation,
// large_arc,
// turn_left,
// });
const radius_min = distance(p0, p1) / 2.0;
const radius_lim = sqrt(radius_x * radius_x + radius_y * radius_y); // std.math.min(std.math.fabs(radius_x), std.math.fabs(radius_y));
const up_scale = if (radius_lim < radius_min)
radius_min / radius_lim
else
1.0;
// std.debug.print("radius_min={d} radius_lim={d} up_scale={d}\n", .{ radius_min, radius_lim, up_scale });
// std.debug.print("{d} {d} {d}, {d} => {d}\n", .{ radius_x, radius_y, radius_lim, radius_min, up_scale });
const ratio = radius_x / radius_y;
const rot = rotationMat(toRadians(-rotation));
const transform = [2][2]f32{
.{ rot[0][0] / up_scale, rot[0][1] / up_scale },
.{ rot[1][0] / up_scale * ratio, rot[1][1] / up_scale * ratio },
};
const transform_back = [2][2]f32{
.{ rot[1][1] * up_scale, -rot[0][1] / ratio * up_scale },
.{ -rot[1][0] * up_scale, rot[0][0] / ratio * up_scale },
};
const Helper = struct {
point_list: FixedBufferList(Point, circle_divs),
width_list: FixedBufferList(f32, circle_divs),
fn append(self: *@This(), pt: Point, lw: f32) !void {
try self.point_list.append(pt);
try self.width_list.append(lw);
}
};
var tmp = Helper{
.point_list = FixedBufferList(Point, circle_divs).init(null),
.width_list = FixedBufferList(f32, circle_divs).init(null),
};
renderCircle(
&tmp,
applyMat(transform, p0),
applyMat(transform, p1),
radius_x * up_scale,
large_arc,
turn_left,
start_width,
end_width,
) catch unreachable; // buffer is correctly sized
for (tmp.point_list.items()) |p, i| {
try point_list.append(applyMat(transform_back, p), tmp.width_list.items()[i]);
}
}
fn renderCircle(
point_list: anytype,
p0: Point,
p1: Point,
radius: f32,
large_arc: bool,
turn_left: bool,
start_width: f32,
end_width: f32,
) !void {
var r = radius;
// Whether the center should be to the left of the vector from p0 to p1
const left_side = (turn_left and large_arc) or (!turn_left and !large_arc);
const delta = scale(sub(p1, p0), 0.5);
const midpoint = add(p0, delta);
// Vector from midpoint to center, but incorrect length
const radius_vec = if (left_side)
Point{ .x = -delta.y, .y = delta.x }
else
Point{ .x = delta.y, .y = -delta.x };
const len_squared = length2(radius_vec);
if (len_squared - 0.03 > r * r or r < 0) {
r = @sqrt(len_squared);
// std.log.err("{d} > {d}", .{ std.math.sqrt(len_squared), std.math.sqrt(r * r) });
// return error.InvalidRadius;
}
const to_center = scale(radius_vec, sqrt(std.math.max(0, r * r / len_squared - 1)));
const center = add(midpoint, to_center);
const angle = std.math.asin(std.math.clamp(sqrt(len_squared) / r, -1.0, 1.0)) * 2;
const arc = if (large_arc) (std.math.tau - angle) else angle;
var pos = sub(p0, center);
var i: usize = 0;
while (i < circle_divs - 1) : (i += 1) {
const step_mat = rotationMat(@intToFloat(f32, i) * (if (turn_left) -arc else arc) / circle_divs);
const point = add(applyMat(step_mat, pos), center);
try point_list.append(point, lerp(start_width, end_width, @intToFloat(f32, i) / circle_divs));
}
try point_list.append(p1, end_width);
}
fn rotationMat(angle: f32) [2][2]f32 {
const s = sin(angle);
const c = cos(angle);
return .{
.{ c, -s },
.{ s, c },
};
}
fn applyMat(mat: [2][2]f32, p: Point) Point {
return .{
.x = p.x * mat[0][0] + p.y * mat[0][1],
.y = p.x * mat[1][0] + p.y * mat[1][1],
};
}
fn pointFromInts(x: i16, y: i16) Point {
return Point{ .x = @intToFloat(f32, x) + 0.5, .y = @intToFloat(f32, y) + 0.5 };
}
const IntPoint = struct { x: i16, y: i16 };
fn pointToInts(point: Point) IntPoint {
return IntPoint{
.x = floatToIntClamped(i16, std.math.round(point.x)),
.y = floatToIntClamped(i16, std.math.round(point.y)),
};
}
fn xy(x: f32, y: f32) Point {
return Point{ .x = x, .y = y };
}
test "point conversion" {
const TestData = struct { point: Point, x: i16, y: i16 };
const pt2int = [_]TestData{
.{ .point = xy(0, 0), .x = 0, .y = 0 },
.{ .point = xy(1, 0), .x = 1, .y = 0 },
.{ .point = xy(2, 0), .x = 2, .y = 0 },
.{ .point = xy(0, 1), .x = 0, .y = 1 },
.{ .point = xy(0, 2), .x = 0, .y = 2 },
.{ .point = xy(1, 3), .x = 1, .y = 3 },
.{ .point = xy(2, 4), .x = 2, .y = 4 },
};
const int2pt = [_]TestData{
.{ .point = xy(0, 0), .x = 0, .y = 0 },
.{ .point = xy(1, 0), .x = 1, .y = 0 },
.{ .point = xy(2, 0), .x = 2, .y = 0 },
.{ .point = xy(0, 1), .x = 0, .y = 1 },
.{ .point = xy(0, 2), .x = 0, .y = 2 },
.{ .point = xy(1, 3), .x = 1, .y = 3 },
.{ .point = xy(2, 4), .x = 2, .y = 4 },
};
for (pt2int) |data| {
const ints = pointToInts(data.point);
//std.debug.print("{d} {d} => {d} {d}\n", .{
// data.point.x, data.point.y,
// ints.x, ints.y,
//});
try std.testing.expectEqual(data.x, ints.x);
try std.testing.expectEqual(data.y, ints.y);
}
for (int2pt) |data| {
const pt = pointFromInts(data.x, data.y);
try std.testing.expectApproxEqAbs(@as(f32, 0.0), distance(pt, data.point), sqrt(2.0) / 2.0);
}
}
fn add(a: Point, b: Point) Point {
return .{ .x = a.x + b.x, .y = a.y + b.y };
}
fn sub(p1: Point, p2: Point) Point {
return Point{ .x = p1.x - p2.x, .y = p1.y - p2.y };
}
fn dot(p1: Point, p2: Point) f32 {
return p1.x * p2.x + p1.y * p2.y;
}
fn cross(a: Point, b: Point) f32 {
return a.x * b.y - a.y * b.x;
}
fn scale(a: Point, s: f32) Point {
return .{ .x = a.x * s, .y = a.y * s };
}
fn length2(p: Point) f32 {
return dot(p, p);
}
fn length(p: Point) f32 {
return sqrt(length2(p));
}
fn distance(p1: Point, p2: Point) f32 {
return length(sub(p1, p2));
}
fn getProjectedPointOnLine(v1: Point, v2: Point, p: Point) Point {
var l1 = sub(v2, v1);
var l2 = sub(p, v1);
var proj = dot(l1, l2) / length2(l1);
return add(v1, scale(l1, proj));
}
const Painter = struct {
scale_x: f32,
scale_y: f32,
// fn fillPolygon(self: Painter, framebuffer: anytype, color_table: []const Color, style: Style, points: []const Point) void {
// fillPolygonList(self, framebuffer, color_table, style, &[_][]const Point{points}, .nonzero);
// }
const FillRule = enum { even_odd, nonzero };
fn fillPolygonList(self: Painter, framebuffer: anytype, color_table: []const Color, style: Style, points_lists: []const []const Point, rule: FillRule) void {
std.debug.assert(points_lists.len > 0);
var min_x: i16 = std.math.maxInt(i16);
var min_y: i16 = std.math.maxInt(i16);
var max_x: i16 = std.math.minInt(i16);
var max_y: i16 = std.math.minInt(i16);
for (points_lists) |points| {
// std.debug.assert(points.len >= 3);
for (points) |pt| {
min_x = std.math.min(min_x, floatToIntClamped(i16, std.math.floor(self.scale_x * pt.x)));
min_y = std.math.min(min_y, floatToIntClamped(i16, std.math.floor(self.scale_y * pt.y)));
max_x = std.math.max(max_x, floatToIntClamped(i16, std.math.ceil(self.scale_x * pt.x)));
max_y = std.math.max(max_y, floatToIntClamped(i16, std.math.ceil(self.scale_y * pt.y)));
}
}
// limit to valid screen area
min_x = std.math.max(min_x, 0);
min_y = std.math.max(min_y, 0);
max_x = std.math.min(max_x, @intCast(i16, framebuffer.width - 1));
max_y = std.math.min(max_y, @intCast(i16, framebuffer.height - 1));
var y: i16 = min_y;
while (y <= max_y) : (y += 1) {
var x: i16 = min_x;
while (x <= max_x) : (x += 1) {
// compute "center" of the pixel
var p = self.mapPointToImage(pointFromInts(x, y));
var inside_count: usize = 0;
for (points_lists) |points| {
if (points.len < 2) continue;
var inside = false;
// free after https://stackoverflow.com/a/17490923
var j = points.len - 1;
for (points) |p0, i| {
defer j = i;
const p1 = points[j];
if ((p0.y > p.y) != (p1.y > p.y) and p.x < (p1.x - p0.x) * (p.y - p0.y) / (p1.y - p0.y) + p0.x) {
inside = !inside;
}
}
if (inside) {
inside_count += 1;
}
}
const set = switch (rule) {
.nonzero => (inside_count > 0),
.even_odd => (inside_count % 2) == 1,
};
if (set) {
framebuffer.setPixel(x, y, self.sampleStlye(color_table, style, x, y));
}
}
}
}
fn fillRectangle(self: Painter, framebuffer: anytype, x: f32, y: f32, width: f32, height: f32, color_table: []const Color, style: Style) void {
const xlimit = @floatToInt(i16, std.math.ceil(self.scale_x * (x + width)));
const ylimit = @floatToInt(i16, std.math.ceil(self.scale_y * (y + height)));
var py = @floatToInt(i16, std.math.floor(self.scale_y * y));
while (py < ylimit) : (py += 1) {
var px = @floatToInt(i16, std.math.floor(self.scale_x * x));
while (px < xlimit) : (px += 1) {
framebuffer.setPixel(px, py, self.sampleStlye(color_table, style, px, py));
}
}
}
fn sdUnevenCapsule(_p: Point, pa: Point, _pb: Point, ra: f32, rb: f32) f32 {
const p = sub(_p, pa);
const pb = sub(_pb, pa);
const h = dot(pb, pb);
var q = scale(tvg.point(dot(p, tvg.point(pb.y, -pb.x)), dot(p, pb)), 1.0 / h);
//-----------
q.x = @fabs(q.x);
const b = ra - rb;
const c = tvg.point(@sqrt(h - b * b), b);
const k = cross(c, q);
const m = dot(c, q);
const n = dot(q, q);
if (k < 0.0) {
return @sqrt(h * (n)) - ra;
} else if (k > c.x) {
return @sqrt(h * (n + 1.0 - 2.0 * q.y)) - rb;
} else {
return m - ra;
}
}
/// render round-capped line via SDF: https://iquilezles.org/www/articles/distfunctions2d/distfunctions2d.htm (Uneven Capsule - exact )
/// ```
/// float sdUnevenCapsule( in vec2 p, in vec2 pa, in vec2 pb, in float ra, in float rb )
/// {
/// p -= pa;
/// pb -= pa;
/// float h = dot(pb,pb);
/// vec2 q = vec2( dot(p,vec2(pb.y,-pb.x)), dot(p,pb) )/h;
///
/// //-----------
///
/// q.x = abs(q.x);
///
/// float b = ra-rb;
/// vec2 c = vec2(sqrt(h-b*b),b);
///
/// float k = cro(c,q);
/// float m = dot(c,q);
/// float n = dot(q,q);
///
/// if( k < 0.0 ) return sqrt(h*(n )) - ra;
/// else if( k > c.x ) return sqrt(h*(n+1.0-2.0*q.y)) - rb;
/// return m - ra;
/// }
/// ```
fn drawLine(self: Painter, framebuffer: anytype, color_table: []const Color, style: Style, width_start: f32, width_end: f32, line: tvg.Line) void {
var min_x: i16 = std.math.maxInt(i16);
var min_y: i16 = std.math.maxInt(i16);
var max_x: i16 = std.math.minInt(i16);
var max_y: i16 = std.math.minInt(i16);
const max_width = std.math.max(width_start, width_end);
const points = [_]tvg.Point{ line.start, line.end };
for (points) |pt| {
min_x = std.math.min(min_x, @floatToInt(i16, std.math.floor(self.scale_x * (pt.x - max_width))));
min_y = std.math.min(min_y, @floatToInt(i16, std.math.floor(self.scale_y * (pt.y - max_width))));
max_x = std.math.max(max_x, @floatToInt(i16, std.math.ceil(self.scale_x * (pt.x + max_width))));
max_y = std.math.max(max_y, @floatToInt(i16, std.math.ceil(self.scale_y * (pt.y + max_width))));
}
// limit to valid screen area
min_x = std.math.max(min_x, 0);
min_y = std.math.max(min_y, 0);
max_x = std.math.min(max_x, @intCast(i16, framebuffer.width - 1));
max_y = std.math.min(max_y, @intCast(i16, framebuffer.height - 1));
var y: i16 = min_y;
while (y <= max_y) : (y += 1) {
var x: i16 = min_x;
while (x <= max_x) : (x += 1) {
// compute "center" of the pixel
var p = self.mapPointToImage(pointFromInts(x, y));
const dist = sdUnevenCapsule(
p,
line.start,
line.end,
std.math.max(0.35, width_start / 2),
std.math.max(0.35, width_end / 2),
);
if (dist <= 0.0) {
framebuffer.setPixel(x, y, self.sampleStlye(color_table, style, x, y));
}
}
}
}
fn mapPointToImage(self: Painter, pt: Point) Point {
return Point{
.x = pt.x / self.scale_x,
.y = pt.y / self.scale_y,
};
}
fn sampleStlye(self: Painter, color_table: []const Color, style: Style, x: i16, y: i16) Color {
return switch (style) {
.flat => |index| color_table[index],
.linear => |grad| blk: {
const c0 = color_table[grad.color_0];
const c1 = color_table[grad.color_1];
const p0 = grad.point_0;
const p1 = grad.point_1;
const pt = self.mapPointToImage(pointFromInts(x, y));
const direction = sub(p1, p0);
const delta_pt = sub(pt, p0);
const dot_0 = dot(direction, delta_pt);
if (dot_0 <= 0.0)
break :blk c0;
const dot_1 = dot(direction, sub(pt, p1));
if (dot_1 >= 0.0)
break :blk c1;
const len_grad = length(direction);
const pos_grad = length(getProjectedPointOnLine(
Point{ .x = 0, .y = 0 },
direction,
delta_pt,
));
break :blk lerp_sRGB(c0, c1, pos_grad / len_grad);
},
.radial => |grad| blk: {
const dist_max = distance(grad.point_0, grad.point_1);
const dist_is = distance(grad.point_0, self.mapPointToImage(pointFromInts(x, y)));
const c0 = color_table[grad.color_0];
const c1 = color_table[grad.color_1];
break :blk lerp_sRGB(c0, c1, dist_is / dist_max);
},
};
}
};
const sRGB_gamma = 2.2;
fn gamma2linear(v: f32) f32 {
std.debug.assert(v >= 0 and v <= 1);
return 255.0 * std.math.pow(f32, v, 1.0 / sRGB_gamma);
}
fn linear2gamma(v: f32) f32 {
return std.math.pow(f32, v / 255.0, sRGB_gamma);
}
fn lerp_sRGB(c0: Color, c1: Color, f_unchecked: f32) Color {
const f = std.math.clamp(f_unchecked, 0, 1);
return Color{
.r = gamma2linear(lerp(linear2gamma(c0.r), linear2gamma(c1.r), f)),
.g = gamma2linear(lerp(linear2gamma(c0.g), linear2gamma(c1.g), f)),
.b = gamma2linear(lerp(linear2gamma(c0.b), linear2gamma(c1.b), f)),
.a = lerp(c0.a, c0.a, f),
};
}
fn lerp(a: f32, b: f32, x: f32) f32 {
return a + (b - a) * x;
}
fn lerpAndReduce(comptime n: comptime_int, vals: [n]f32, f: f32) [n - 1]f32 {
var result: [n - 1]f32 = undefined;
for (result) |*r, i| {
r.* = lerp(vals[i + 0], vals[i + 1], f);
}
return result;
}
fn lerpAndReduceToOne(comptime n: comptime_int, vals: [n]f32, f: f32) f32 {
if (n == 1) {
return vals[0];
} else {
return lerpAndReduceToOne(n - 1, lerpAndReduce(n, vals, f), f);
}
}
pub fn FixedBufferList(comptime T: type, comptime N: usize) type {
return struct {
const Self = @This();
buffer: [N]T = undefined,
count: usize = 0,
large: ?std.ArrayList(T),
pub fn init(allocator: ?std.mem.Allocator) Self {
return Self{
.large = if (allocator) |allo|
std.ArrayList(T).init(allo)
else
null,
};
}
pub fn deinit(self: *Self) void {
if (self.large) |*large| {
large.deinit();
}
}
pub fn append(self: *Self, value: T) !void {
if (self.large) |*large| {
try large.append(value);
return;
}
if (self.count == N)
return error.OutOfMemory;
self.buffer[self.count] = value;
self.count += 1;
}
pub fn popBack(self: *Self) ?T {
if (self.large) |*large| {
return large.popOrNull();
}
if (self.count == 0)
return null;
self.count -= 1;
return self.buffer[self.count];
}
pub fn itemsMut(self: *Self) []T {
if (self.large) |*large| {
return large.items;
}
return self.buffer[0..self.count];
}
pub fn items(self: Self) []const T {
if (self.large) |*large| {
return large.items;
}
return self.buffer[0..self.count];
}
pub fn front(self: Self) ?T {
if (self.large) |*large| {
if (large.items.len > 0) {
return large.items[0];
} else {
return null;
}
}
if (self.count == 0)
return null;
return self.buffer[0];
}
pub fn back(self: Self) ?T {
if (self.large) |*large| {
if (large.items.len > 0) {
return large.items[large.items.len - 1];
} else {
return null;
}
}
if (self.count == 0)
return null;
return self.buffer[self.count - 1];
}
};
}
fn floatToInt(comptime I: type, f: anytype) error{Overflow}!I {
if (f < std.math.minInt(I))
return error.Overflow;
if (f > std.math.maxInt(I))
return error.Overflow;
return @floatToInt(I, f);
}
fn floatToIntClamped(comptime I: type, f: anytype) I {
if (std.math.isNan(f))
@panic("NaN passed to floatToIntClamped!");
if (f < std.math.minInt(I))
return std.math.minInt(I);
if (f > std.math.maxInt(I))
return std.math.maxInt(I);
return @floatToInt(I, f);
} | src/lib/rendering.zig |
const std = @import("std");
pub fn build(b: *std.build.Builder) !void {
// Standard target options allows the person running `zig build` to choose
// what target to build for. Here we do not override the defaults, which
// means any target is allowed, and the default is native. Other options
// for restricting supported target set are available.
const target = b.standardTargetOptions(.{});
// Standard release options allow the person running `zig build` to select
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall.
const mode = b.standardReleaseOptions();
const exe = b.addExecutable("codegen", "src/main.zig");
exe.addPackagePath("smithy", "../smithy/src/smithy.zig");
exe.setTarget(target);
exe.setBuildMode(mode);
// This line works as of c5d412268
// Earliest nightly is 05b5e49bc on 2021-06-12
// https://ziglang.org/builds/zig-linux-x86_64-0.9.0-dev.113+05b5e49bc.tar.xz
// exe.override_dest_dir = .{ .Custom = ".." };
exe.override_dest_dir = .{ .custom = ".." };
// Static linkage flag was nonfunctional until 2b2efa24d0855
// Did not notice this until 2021-06-28, and that nightly is:
// https://ziglang.org/builds/zig-linux-x86_64-0.9.0-dev.321+15a030ef3.tar.xz
exe.linkage = .static;
const is_strip = b.option(bool, "strip", "strip exe") orelse true;
exe.strip = !is_strip;
exe.install();
const run_cmd = exe.run();
run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_cmd.addArgs(args);
}
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
const test_step = b.step("test", "Run library tests");
var build_dir = try std.fs.openDirAbsolute(b.build_root, .{});
defer build_dir.close();
var src_dir = try build_dir.openDir("src", .{ .iterate = true });
defer src_dir.close();
var iterator = src_dir.iterate();
while (try iterator.next()) |entry| {
if (std.mem.endsWith(u8, entry.name, ".zig") and
!std.mem.eql(u8, entry.name, "main.zig"))
{
const name = try std.fmt.allocPrint(b.allocator, "src/{s}", .{entry.name});
defer b.allocator.free(name);
const t = b.addTest(name);
t.setBuildMode(mode);
test_step.dependOn(&t.step);
}
}
} | codegen/build.zig |
usingnamespace @import("psptypes.zig");
pub const clock_t = u32;
pub const suseconds_t = u32;
pub const timeval = extern struct {
tv_sec: time_t,
tv_usec: suseconds_t,
};
pub const timezone = extern struct {
tz_minuteswest: c_int,
tz_dsttime: c_int,
};
pub const SceKernelUtilsMt19937Context = extern struct {
count: c_uint,
state: [624]c_uint,
};
pub const SceKernelUtilsMd5Context = extern struct {
h: [4]c_uint,
pad: c_uint,
usRemains: SceUShort16,
usComputed: SceUShort16,
ullTotalLen: SceULong64,
buf: [64]u8,
};
pub const SceKernelUtilsSha1Context = extern struct {
h: [5]c_uint,
usRemains: SceUShort16,
usComputed: SceUShort16,
ullTotalLen: SceULong64,
buf: [64]u8,
};
// Function to initialise a mersenne twister context.
//
// @param ctx - Pointer to a context
// @param seed - A seed for the random function.
//
// @par Example:
// @code
// SceKernelUtilsMt19937Context ctx;
// sceKernelUtilsMt19937Init(&ctx, time(NULL));
// u23 rand_val = sceKernelUtilsMt19937UInt(&ctx);
// @endcode
//
// @return < 0 on error.
pub extern fn sceKernelUtilsMt19937Init(ctx: *SceKernelUtilsMt19937Context, seed: u32) c_int;
pub fn kernelUtilsMt19937Init(ctx: *SceKernelUtilsMt19937Context, seed: u32) !i32 {
var res = sceKernelUtilsMt19937Init(ctx, seed);
if (res < 0) {
return error.Unexpected;
}
return res;
}
// Function to return a new psuedo random number.
//
// @param ctx - Pointer to a pre-initialised context.
// @return A pseudo random number (between 0 and MAX_INT).
pub extern fn sceKernelUtilsMt19937UInt(ctx: *SceKernelUtilsMt19937Context) u32;
// Function to perform an MD5 digest of a data block.
//
// @param data - Pointer to a data block to make a digest of.
// @param size - Size of the data block.
// @param digest - Pointer to a 16byte buffer to store the resulting digest
//
// @return < 0 on error.
pub extern fn sceKernelUtilsMd5Digest(data: [*]u8, size: u32, digest: [*]u8) c_int;
pub fn kernelUtilsMd5Digest(data: [*]u8, size: u32, digest: [*]u8) !i32 {
var res = sceKernelUtilsMd5Digest(data, size, digest);
if (res < 0) {
return error.Unexpected;
}
return res;
}
// Function to initialise a MD5 digest context
//
// @param ctx - A context block to initialise
//
// @return < 0 on error.
// C Example
// SceKernelUtilsMd5Context ctx;
// u8 digest[16];
// sceKernelUtilsMd5BlockInit(&ctx);
// sceKernelUtilsMd5BlockUpdate(&ctx, (u8*) "Hello", 5);
// sceKernelUtilsMd5BlockResult(&ctx, digest);
pub extern fn sceKernelUtilsMd5BlockInit(ctx: *SceKernelUtilsMd5Context) c_int;
pub fn kernelUtilsMd5BlockInit(ctx: *SceKernelUtilsMd5Context) !i32 {
var res = sceKernelUtilsMd5BlockInit(ctx);
if (res < 0) {
return error.Unexpected;
}
return res;
}
// Function to update the MD5 digest with a block of data.
//
// @param ctx - A filled in context block.
// @param data - The data block to hash.
// @param size - The size of the data to hash
//
// @return < 0 on error.
pub extern fn sceKernelUtilsMd5BlockUpdate(ctx: *SceKernelUtilsMd5Context, data: [*]u8, size: u32) c_int;
pub fn kernelUtilsMd5BlockUpdate(ctx: *SceKernelUtilsMd5Context, data: [*]u8, size: u32) !i32 {
var res = sceKernelUtilsMd5BlockUpdate(ctx, data, size);
if (res < 0) {
return error.Unexpected;
}
return res;
}
// Function to get the digest result of the MD5 hash.
//
// @param ctx - A filled in context block.
// @param digest - A 16 byte array to hold the digest.
//
// @return < 0 on error.
pub extern fn sceKernelUtilsMd5BlockResult(ctx: *SceKernelUtilsMd5Context, digest: [*]u8) c_int;
pub fn kernelUtilsMd5BlockResult(ctx: *SceKernelUtilsMd5Context, digest: [*]u8) !i32 {
var res = sceKernelUtilsMd5BlockResult(ctx, digest);
if (res < 0) {
return error.Unexpected;
}
return res;
}
// Function to SHA1 hash a data block.
//
// @param data - The data to hash.
// @param size - The size of the data.
// @param digest - Pointer to a 20 byte array for storing the digest
//
// @return < 0 on error.
pub extern fn sceKernelUtilsSha1Digest(data: [*]u8, size: u32, digest: [*]u8) c_int;
pub fn kernelUtilsSha1Digest(data: [*]u8, size: u32, digest: [*]u8) !i32 {
var res = sceKernelUtilsSha1Digest(data, size, digest);
if (res < 0) {
return error.Unexpected;
}
return res;
}
// Function to initialise a context for SHA1 hashing.
//
// @param ctx - Pointer to a context.
//
// @return < 0 on error.
// C Code Example
// SceKernelUtilsSha1Context ctx;
// u8 digest[20];
// sceKernelUtilsSha1BlockInit(&ctx);
// sceKernelUtilsSha1BlockUpdate(&ctx, (u8*) "Hello", 5);
// sceKernelUtilsSha1BlockResult(&ctx, digest);
pub extern fn sceKernelUtilsSha1BlockInit(ctx: *SceKernelUtilsSha1Context) c_int;
pub fn kernelUtilsSha1BlockInit(ctx: *SceKernelUtilsSha1Context) !i32 {
var res = sceKernelUtilsSha1BlockInit(ctx);
if (res < 0) {
return error.Unexpected;
}
return res;
}
// Function to update the current hash.
//
// @param ctx - Pointer to a prefilled context.
// @param data - The data block to hash.
// @param size - The size of the data block
//
// @return < 0 on error.
pub extern fn sceKernelUtilsSha1BlockUpdate(ctx: *SceKernelUtilsSha1Context, data: [*]u8, size: u32) c_int;
pub fn kernelUtilsSha1BlockUpdate(ctx: *SceKernelUtilsSha1Context, data: [*]u8, size: u32) !i32 {
var res = sceKernelUtilsSha1BlockUpdate(ctx, data, size);
if (res < 0) {
return error.Unexpected;
}
return res;
}
// Function to get the result of the SHA1 hash.
//
// @param ctx - Pointer to a prefilled context.
// @param digest - A pointer to a 20 byte array to contain the digest.
//
// @return < 0 on error.
pub extern fn sceKernelUtilsSha1BlockResult(ctx: *SceKernelUtilsSha1Context, digest: [*]u8) c_int;
pub fn kernelUtilsSha1BlockResult(ctx: *SceKernelUtilsSha1Context, digest: [*]u8) !i32 {
var res = sceKernelUtilsSha1BlockResult(ctx, digest);
if (res < 0) {
return error.Unexpected;
}
return res;
}
// Get the time in seconds since the epoc (1st Jan 1970)
pub extern fn sceKernelLibcTime(t: *time_t) time_t;
// Get the processor clock used since the start of the process
pub extern fn sceKernelLibcClock() clock_t;
// Get the current time of time and time zone information
pub extern fn sceKernelLibcGettimeofday(tp: *timeval, tzp: *timezone) c_int;
//Write back the data cache to memory
pub extern fn sceKernelDcacheWritebackAll() void;
//Write back and invalidate the data cache
pub extern fn sceKernelDcacheWritebackInvalidateAll() void;
//Write back a range of addresses from the data cache to memory
pub extern fn sceKernelDcacheWritebackRange(p: ?*const c_void, size: c_uint) void;
//Write back and invalidate a range of addresses in the data cache
pub extern fn sceKernelDcacheWritebackInvalidateRange(p: ?*const c_void, size: c_uint) void;
//Invalidate a range of addresses in data cache
pub extern fn sceKernelDcacheInvalidateRange(p: ?*const c_void, size: c_uint) void;
//Invalidate the instruction cache
pub extern fn sceKernelIcacheInvalidateAll() void;
//Invalidate a range of addresses in the instruction cache
pub extern fn sceKernelIcacheInvalidateRange(p: ?*const c_void, size: c_uint) void; | src/psp/sdk/psputils.zig |
const std = @import("std");
pub const c = @cImport({
@cInclude("libpq-fe.h");
});
const build_options = @import("build_options");
pub const Builder = @import("./sql_builder.zig").Builder;
pub const Parser = @import("./parser.zig");
const helpers = @import("./helpers.zig");
const Definitions = @import("./definitions.zig");
const Error = Definitions.Error;
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
pub const Result = @import("./result.zig").Result;
pub const FieldInfo = @import("./result.zig").FieldInfo;
const print = std.debug.print;
pub const Pg = struct {
const Self = @This();
connection: *c.PGconn,
allocator: *std.mem.Allocator,
pub fn connect(allocator: *std.mem.Allocator, address: []const u8) !Self {
var conn_info = try std.cstr.addNullByte(allocator, address);
var connection: *c.PGconn = undefined;
defer allocator.free(conn_info);
if (c.PQconnectdb(conn_info)) |conn| {
connection = conn;
}
if (@enumToInt(c.PQstatus(connection)) != c.CONNECTION_OK) {
return Error.ConnectionFailure;
}
return Self{
.allocator = allocator,
.connection = connection,
};
}
pub fn insert(self: Self, data: anytype) !Result {
var temp_memory = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const allocator = &temp_memory.allocator;
var builder = Builder.new(.Insert, allocator);
const type_info = @typeInfo(@TypeOf(data));
defer {
builder.deinit();
temp_memory.deinit();
}
switch (type_info) {
.Pointer => {
const pointer_info = @typeInfo(type_info.Pointer.child);
if (pointer_info == .Array) {
// For each item in inserted array
for (data) |child, child_index| {
//Set table name as first items struct name.
if (child_index == 0) {
const struct_name = @typeName(@TypeOf(child));
_ = builder.table(helpers.toLowerCase(struct_name.len, struct_name)[0..]);
}
const struct_fields = @typeInfo(@TypeOf(child)).Struct.fields;
const is_extended = @hasDecl(@TypeOf(child), "onSave");
inline for (struct_fields) |field, index| {
const field_type_info = @typeInfo(field.field_type);
const field_value = @field(child, field.name);
//Add first child struct keys as column value
if (field_type_info == .Optional) {
if (field_value != null) try builder.addColumn(field.name);
} else if (child_index == 0) {
try builder.addColumn(field.name);
}
builder.autoAdd(child, FieldInfo{ .name = field.name, .type = field.field_type }, field_value, is_extended) catch unreachable;
}
}
}
if (pointer_info == .Struct) {
//Struct pointer
const struct_info = @typeInfo(type_info.Pointer.child).Struct;
const struct_name = @typeName(type_info.Pointer.child);
const is_extended = @hasDecl(type_info.Pointer.child, "onSave");
_ = builder.table(helpers.toLowerCase(struct_name.len, struct_name)[0..]);
inline for (struct_info.fields) |field, index| {
const field_type_info = @typeInfo(field.field_type);
const field_value = @field(data, field.name);
if (field_type_info == .Optional) {
if (field_value != null) try builder.addColumn(field.name);
} else {
try builder.addColumn(field.name);
}
builder.autoAdd(data, FieldInfo{ .name = field.name, .type = field.field_type }, field_value, is_extended) catch unreachable;
}
}
},
.Struct => {
const struct_info = @typeInfo(@TypeOf(data)).Struct;
const struct_name = @typeName(@TypeOf(data));
const is_extended = @hasDecl(@TypeOf(data), "onSave");
_ = builder.table(helpers.toLowerCase(struct_name.len, struct_name)[0..]);
inline for (struct_info.fields) |field, index| {
const field_type_info = @typeInfo(field.field_type);
const field_value = @field(data, field.name);
if (field_type_info == .Optional) {
if (field_value != null) try builder.addColumn(field.name);
} else {
try builder.addColumn(field.name);
}
builder.autoAdd(data, FieldInfo{ .name = field.name, .type = field.field_type }, field_value, is_extended) catch unreachable;
}
},
else => {},
}
try builder.end();
//Exec command
return try self.exec(builder.command());
}
pub fn exec(self: Self, query: []const u8) !Result {
var cstr_query = try std.cstr.addNullByte(self.allocator, query);
defer self.allocator.free(cstr_query);
var res: ?*c.PGresult = c.PQexec(self.connection, cstr_query);
var response_code = @enumToInt(c.PQresultStatus(res));
if (response_code != c.PGRES_TUPLES_OK and response_code != c.PGRES_COMMAND_OK and response_code != c.PGRES_NONFATAL_ERROR) {
std.debug.warn("Error {s}\n", .{c.PQresultErrorMessage(res)});
c.PQclear(res);
return Error.QueryFailure;
}
if (res) |result| {
return Result.new(result);
} else {
return Error.QueryFailure;
}
}
pub fn execValues(self: Self, comptime query: []const u8, values: anytype) !Result {
var temp_memory = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer temp_memory.deinit();
const allocator = &temp_memory.allocator;
return self.exec(try Builder.buildQuery(query, values, allocator));
}
pub fn deinit(self: *Self) void {
c.PQfinish(self.connection);
}
}; | src/postgres.zig |
pub const E_XML_NOTWF = @as(i32, -1072897501);
pub const E_XML_NODTD = @as(i32, -1072897500);
pub const E_XML_INVALID = @as(i32, -1072897499);
pub const E_XML_BUFFERTOOSMALL = @as(i32, -1072897498);
pub const XHR_PROP_ONDATA_ALWAYS = @as(u32, 0);
pub const XHR_PROP_ONDATA_NEVER = @as(u64, 18446744073709551615);
//--------------------------------------------------------------------------------
// Section: Types (127)
//--------------------------------------------------------------------------------
const CLSID_DOMDocument_Value = @import("../../zig.zig").Guid.initString("2933bf90-7b36-11d2-b20e-00c04f983e60");
pub const CLSID_DOMDocument = &CLSID_DOMDocument_Value;
const CLSID_DOMFreeThreadedDocument_Value = @import("../../zig.zig").Guid.initString("2933bf91-7b36-11d2-b20e-00c04f983e60");
pub const CLSID_DOMFreeThreadedDocument = &CLSID_DOMFreeThreadedDocument_Value;
const CLSID_XMLHTTPRequest_Value = @import("../../zig.zig").Guid.initString("ed8c108e-4349-11d2-91a4-00c04f7969e8");
pub const CLSID_XMLHTTPRequest = &CLSID_XMLHTTPRequest_Value;
const CLSID_XMLDSOControl_Value = @import("../../zig.zig").Guid.initString("550dda30-0541-11d2-9ca9-0060b0ec3d39");
pub const CLSID_XMLDSOControl = &CLSID_XMLDSOControl_Value;
const CLSID_XMLDocument_Value = @import("../../zig.zig").Guid.initString("cfc399af-d876-11d0-9c10-00c04fc99c8e");
pub const CLSID_XMLDocument = &CLSID_XMLDocument_Value;
pub const XML_ERROR = extern struct {
_nLine: u32,
_pchBuf: ?BSTR,
_cchBuf: u32,
_ich: u32,
_pszFound: ?BSTR,
_pszExpected: ?BSTR,
_reserved1: u32,
_reserved2: u32,
};
pub const DOMNodeType = enum(i32) {
INVALID = 0,
ELEMENT = 1,
ATTRIBUTE = 2,
TEXT = 3,
CDATA_SECTION = 4,
ENTITY_REFERENCE = 5,
ENTITY = 6,
PROCESSING_INSTRUCTION = 7,
COMMENT = 8,
DOCUMENT = 9,
DOCUMENT_TYPE = 10,
DOCUMENT_FRAGMENT = 11,
NOTATION = 12,
};
pub const NODE_INVALID = DOMNodeType.INVALID;
pub const NODE_ELEMENT = DOMNodeType.ELEMENT;
pub const NODE_ATTRIBUTE = DOMNodeType.ATTRIBUTE;
pub const NODE_TEXT = DOMNodeType.TEXT;
pub const NODE_CDATA_SECTION = DOMNodeType.CDATA_SECTION;
pub const NODE_ENTITY_REFERENCE = DOMNodeType.ENTITY_REFERENCE;
pub const NODE_ENTITY = DOMNodeType.ENTITY;
pub const NODE_PROCESSING_INSTRUCTION = DOMNodeType.PROCESSING_INSTRUCTION;
pub const NODE_COMMENT = DOMNodeType.COMMENT;
pub const NODE_DOCUMENT = DOMNodeType.DOCUMENT;
pub const NODE_DOCUMENT_TYPE = DOMNodeType.DOCUMENT_TYPE;
pub const NODE_DOCUMENT_FRAGMENT = DOMNodeType.DOCUMENT_FRAGMENT;
pub const NODE_NOTATION = DOMNodeType.NOTATION;
pub const XMLEMEM_TYPE = enum(i32) {
ELEMENT = 0,
TEXT = 1,
COMMENT = 2,
DOCUMENT = 3,
DTD = 4,
PI = 5,
OTHER = 6,
};
pub const XMLELEMTYPE_ELEMENT = XMLEMEM_TYPE.ELEMENT;
pub const XMLELEMTYPE_TEXT = XMLEMEM_TYPE.TEXT;
pub const XMLELEMTYPE_COMMENT = XMLEMEM_TYPE.COMMENT;
pub const XMLELEMTYPE_DOCUMENT = XMLEMEM_TYPE.DOCUMENT;
pub const XMLELEMTYPE_DTD = XMLEMEM_TYPE.DTD;
pub const XMLELEMTYPE_PI = XMLEMEM_TYPE.PI;
pub const XMLELEMTYPE_OTHER = XMLEMEM_TYPE.OTHER;
const IID_IXMLDOMImplementation_Value = @import("../../zig.zig").Guid.initString("2933bf8f-7b36-11d2-b20e-00c04f983e60");
pub const IID_IXMLDOMImplementation = &IID_IXMLDOMImplementation_Value;
pub const IXMLDOMImplementation = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
hasFeature: fn(
self: *const IXMLDOMImplementation,
feature: ?BSTR,
version: ?BSTR,
hasFeature: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMImplementation_hasFeature(self: *const T, feature: ?BSTR, version: ?BSTR, hasFeature: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMImplementation.VTable, self.vtable).hasFeature(@ptrCast(*const IXMLDOMImplementation, self), feature, version, hasFeature);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXMLDOMNode_Value = @import("../../zig.zig").Guid.initString("2933bf80-7b36-11d2-b20e-00c04f983e60");
pub const IID_IXMLDOMNode = &IID_IXMLDOMNode_Value;
pub const IXMLDOMNode = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_nodeName: fn(
self: *const IXMLDOMNode,
name: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_nodeValue: fn(
self: *const IXMLDOMNode,
value: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_nodeValue: fn(
self: *const IXMLDOMNode,
value: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_nodeType: fn(
self: *const IXMLDOMNode,
type: ?*DOMNodeType,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_parentNode: fn(
self: *const IXMLDOMNode,
parent: ?*?*IXMLDOMNode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_childNodes: fn(
self: *const IXMLDOMNode,
childList: ?*?*IXMLDOMNodeList,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_firstChild: fn(
self: *const IXMLDOMNode,
firstChild: ?*?*IXMLDOMNode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_lastChild: fn(
self: *const IXMLDOMNode,
lastChild: ?*?*IXMLDOMNode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_previousSibling: fn(
self: *const IXMLDOMNode,
previousSibling: ?*?*IXMLDOMNode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_nextSibling: fn(
self: *const IXMLDOMNode,
nextSibling: ?*?*IXMLDOMNode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_attributes: fn(
self: *const IXMLDOMNode,
attributeMap: ?*?*IXMLDOMNamedNodeMap,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
insertBefore: fn(
self: *const IXMLDOMNode,
newChild: ?*IXMLDOMNode,
refChild: VARIANT,
outNewChild: ?*?*IXMLDOMNode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
replaceChild: fn(
self: *const IXMLDOMNode,
newChild: ?*IXMLDOMNode,
oldChild: ?*IXMLDOMNode,
outOldChild: ?*?*IXMLDOMNode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
removeChild: fn(
self: *const IXMLDOMNode,
childNode: ?*IXMLDOMNode,
oldChild: ?*?*IXMLDOMNode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
appendChild: fn(
self: *const IXMLDOMNode,
newChild: ?*IXMLDOMNode,
outNewChild: ?*?*IXMLDOMNode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
hasChildNodes: fn(
self: *const IXMLDOMNode,
hasChild: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ownerDocument: fn(
self: *const IXMLDOMNode,
XMLDOMDocument: ?*?*IXMLDOMDocument,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
cloneNode: fn(
self: *const IXMLDOMNode,
deep: i16,
cloneRoot: ?*?*IXMLDOMNode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_nodeTypeString: fn(
self: *const IXMLDOMNode,
nodeType: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_text: fn(
self: *const IXMLDOMNode,
text: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_text: fn(
self: *const IXMLDOMNode,
text: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_specified: fn(
self: *const IXMLDOMNode,
isSpecified: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_definition: fn(
self: *const IXMLDOMNode,
definitionNode: ?*?*IXMLDOMNode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_nodeTypedValue: fn(
self: *const IXMLDOMNode,
typedValue: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_nodeTypedValue: fn(
self: *const IXMLDOMNode,
typedValue: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_dataType: fn(
self: *const IXMLDOMNode,
dataTypeName: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_dataType: fn(
self: *const IXMLDOMNode,
dataTypeName: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_xml: fn(
self: *const IXMLDOMNode,
xmlString: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
transformNode: fn(
self: *const IXMLDOMNode,
stylesheet: ?*IXMLDOMNode,
xmlString: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
selectNodes: fn(
self: *const IXMLDOMNode,
queryString: ?BSTR,
resultList: ?*?*IXMLDOMNodeList,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
selectSingleNode: fn(
self: *const IXMLDOMNode,
queryString: ?BSTR,
resultNode: ?*?*IXMLDOMNode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_parsed: fn(
self: *const IXMLDOMNode,
isParsed: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_namespaceURI: fn(
self: *const IXMLDOMNode,
namespaceURI: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_prefix: fn(
self: *const IXMLDOMNode,
prefixString: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_baseName: fn(
self: *const IXMLDOMNode,
nameString: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
transformNodeToObject: fn(
self: *const IXMLDOMNode,
stylesheet: ?*IXMLDOMNode,
outputObject: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNode_get_nodeName(self: *const T, name: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNode.VTable, self.vtable).get_nodeName(@ptrCast(*const IXMLDOMNode, self), name);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNode_get_nodeValue(self: *const T, value: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNode.VTable, self.vtable).get_nodeValue(@ptrCast(*const IXMLDOMNode, self), value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNode_put_nodeValue(self: *const T, value: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNode.VTable, self.vtable).put_nodeValue(@ptrCast(*const IXMLDOMNode, self), value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNode_get_nodeType(self: *const T, type_: ?*DOMNodeType) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNode.VTable, self.vtable).get_nodeType(@ptrCast(*const IXMLDOMNode, self), type_);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNode_get_parentNode(self: *const T, parent: ?*?*IXMLDOMNode) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNode.VTable, self.vtable).get_parentNode(@ptrCast(*const IXMLDOMNode, self), parent);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNode_get_childNodes(self: *const T, childList: ?*?*IXMLDOMNodeList) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNode.VTable, self.vtable).get_childNodes(@ptrCast(*const IXMLDOMNode, self), childList);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNode_get_firstChild(self: *const T, firstChild: ?*?*IXMLDOMNode) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNode.VTable, self.vtable).get_firstChild(@ptrCast(*const IXMLDOMNode, self), firstChild);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNode_get_lastChild(self: *const T, lastChild: ?*?*IXMLDOMNode) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNode.VTable, self.vtable).get_lastChild(@ptrCast(*const IXMLDOMNode, self), lastChild);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNode_get_previousSibling(self: *const T, previousSibling: ?*?*IXMLDOMNode) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNode.VTable, self.vtable).get_previousSibling(@ptrCast(*const IXMLDOMNode, self), previousSibling);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNode_get_nextSibling(self: *const T, nextSibling: ?*?*IXMLDOMNode) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNode.VTable, self.vtable).get_nextSibling(@ptrCast(*const IXMLDOMNode, self), nextSibling);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNode_get_attributes(self: *const T, attributeMap: ?*?*IXMLDOMNamedNodeMap) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNode.VTable, self.vtable).get_attributes(@ptrCast(*const IXMLDOMNode, self), attributeMap);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNode_insertBefore(self: *const T, newChild: ?*IXMLDOMNode, refChild: VARIANT, outNewChild: ?*?*IXMLDOMNode) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNode.VTable, self.vtable).insertBefore(@ptrCast(*const IXMLDOMNode, self), newChild, refChild, outNewChild);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNode_replaceChild(self: *const T, newChild: ?*IXMLDOMNode, oldChild: ?*IXMLDOMNode, outOldChild: ?*?*IXMLDOMNode) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNode.VTable, self.vtable).replaceChild(@ptrCast(*const IXMLDOMNode, self), newChild, oldChild, outOldChild);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNode_removeChild(self: *const T, childNode: ?*IXMLDOMNode, oldChild: ?*?*IXMLDOMNode) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNode.VTable, self.vtable).removeChild(@ptrCast(*const IXMLDOMNode, self), childNode, oldChild);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNode_appendChild(self: *const T, newChild: ?*IXMLDOMNode, outNewChild: ?*?*IXMLDOMNode) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNode.VTable, self.vtable).appendChild(@ptrCast(*const IXMLDOMNode, self), newChild, outNewChild);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNode_hasChildNodes(self: *const T, hasChild: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNode.VTable, self.vtable).hasChildNodes(@ptrCast(*const IXMLDOMNode, self), hasChild);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNode_get_ownerDocument(self: *const T, XMLDOMDocument: ?*?*IXMLDOMDocument) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNode.VTable, self.vtable).get_ownerDocument(@ptrCast(*const IXMLDOMNode, self), XMLDOMDocument);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNode_cloneNode(self: *const T, deep: i16, cloneRoot: ?*?*IXMLDOMNode) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNode.VTable, self.vtable).cloneNode(@ptrCast(*const IXMLDOMNode, self), deep, cloneRoot);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNode_get_nodeTypeString(self: *const T, nodeType: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNode.VTable, self.vtable).get_nodeTypeString(@ptrCast(*const IXMLDOMNode, self), nodeType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNode_get_text(self: *const T, text: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNode.VTable, self.vtable).get_text(@ptrCast(*const IXMLDOMNode, self), text);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNode_put_text(self: *const T, text: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNode.VTable, self.vtable).put_text(@ptrCast(*const IXMLDOMNode, self), text);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNode_get_specified(self: *const T, isSpecified: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNode.VTable, self.vtable).get_specified(@ptrCast(*const IXMLDOMNode, self), isSpecified);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNode_get_definition(self: *const T, definitionNode: ?*?*IXMLDOMNode) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNode.VTable, self.vtable).get_definition(@ptrCast(*const IXMLDOMNode, self), definitionNode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNode_get_nodeTypedValue(self: *const T, typedValue: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNode.VTable, self.vtable).get_nodeTypedValue(@ptrCast(*const IXMLDOMNode, self), typedValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNode_put_nodeTypedValue(self: *const T, typedValue: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNode.VTable, self.vtable).put_nodeTypedValue(@ptrCast(*const IXMLDOMNode, self), typedValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNode_get_dataType(self: *const T, dataTypeName: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNode.VTable, self.vtable).get_dataType(@ptrCast(*const IXMLDOMNode, self), dataTypeName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNode_put_dataType(self: *const T, dataTypeName: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNode.VTable, self.vtable).put_dataType(@ptrCast(*const IXMLDOMNode, self), dataTypeName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNode_get_xml(self: *const T, xmlString: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNode.VTable, self.vtable).get_xml(@ptrCast(*const IXMLDOMNode, self), xmlString);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNode_transformNode(self: *const T, stylesheet: ?*IXMLDOMNode, xmlString: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNode.VTable, self.vtable).transformNode(@ptrCast(*const IXMLDOMNode, self), stylesheet, xmlString);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNode_selectNodes(self: *const T, queryString: ?BSTR, resultList: ?*?*IXMLDOMNodeList) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNode.VTable, self.vtable).selectNodes(@ptrCast(*const IXMLDOMNode, self), queryString, resultList);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNode_selectSingleNode(self: *const T, queryString: ?BSTR, resultNode: ?*?*IXMLDOMNode) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNode.VTable, self.vtable).selectSingleNode(@ptrCast(*const IXMLDOMNode, self), queryString, resultNode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNode_get_parsed(self: *const T, isParsed: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNode.VTable, self.vtable).get_parsed(@ptrCast(*const IXMLDOMNode, self), isParsed);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNode_get_namespaceURI(self: *const T, namespaceURI: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNode.VTable, self.vtable).get_namespaceURI(@ptrCast(*const IXMLDOMNode, self), namespaceURI);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNode_get_prefix(self: *const T, prefixString: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNode.VTable, self.vtable).get_prefix(@ptrCast(*const IXMLDOMNode, self), prefixString);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNode_get_baseName(self: *const T, nameString: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNode.VTable, self.vtable).get_baseName(@ptrCast(*const IXMLDOMNode, self), nameString);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNode_transformNodeToObject(self: *const T, stylesheet: ?*IXMLDOMNode, outputObject: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNode.VTable, self.vtable).transformNodeToObject(@ptrCast(*const IXMLDOMNode, self), stylesheet, outputObject);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXMLDOMDocumentFragment_Value = @import("../../zig.zig").Guid.initString("3efaa413-272f-11d2-836f-0000f87a7782");
pub const IID_IXMLDOMDocumentFragment = &IID_IXMLDOMDocumentFragment_Value;
pub const IXMLDOMDocumentFragment = extern struct {
pub const VTable = extern struct {
base: IXMLDOMNode.VTable,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IXMLDOMNode.MethodMixin(T);
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXMLDOMDocument_Value = @import("../../zig.zig").Guid.initString("2933bf81-7b36-11d2-b20e-00c04f983e60");
pub const IID_IXMLDOMDocument = &IID_IXMLDOMDocument_Value;
pub const IXMLDOMDocument = extern struct {
pub const VTable = extern struct {
base: IXMLDOMNode.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_doctype: fn(
self: *const IXMLDOMDocument,
documentType: ?*?*IXMLDOMDocumentType,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_implementation: fn(
self: *const IXMLDOMDocument,
impl: ?*?*IXMLDOMImplementation,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_documentElement: fn(
self: *const IXMLDOMDocument,
DOMElement: ?*?*IXMLDOMElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
putref_documentElement: fn(
self: *const IXMLDOMDocument,
DOMElement: ?*IXMLDOMElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
createElement: fn(
self: *const IXMLDOMDocument,
tagName: ?BSTR,
element: ?*?*IXMLDOMElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
createDocumentFragment: fn(
self: *const IXMLDOMDocument,
docFrag: ?*?*IXMLDOMDocumentFragment,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
createTextNode: fn(
self: *const IXMLDOMDocument,
data: ?BSTR,
text: ?*?*IXMLDOMText,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
createComment: fn(
self: *const IXMLDOMDocument,
data: ?BSTR,
comment: ?*?*IXMLDOMComment,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
createCDATASection: fn(
self: *const IXMLDOMDocument,
data: ?BSTR,
cdata: ?*?*IXMLDOMCDATASection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
createProcessingInstruction: fn(
self: *const IXMLDOMDocument,
target: ?BSTR,
data: ?BSTR,
pi: ?*?*IXMLDOMProcessingInstruction,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
createAttribute: fn(
self: *const IXMLDOMDocument,
name: ?BSTR,
attribute: ?*?*IXMLDOMAttribute,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
createEntityReference: fn(
self: *const IXMLDOMDocument,
name: ?BSTR,
entityRef: ?*?*IXMLDOMEntityReference,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getElementsByTagName: fn(
self: *const IXMLDOMDocument,
tagName: ?BSTR,
resultList: ?*?*IXMLDOMNodeList,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
createNode: fn(
self: *const IXMLDOMDocument,
Type: VARIANT,
name: ?BSTR,
namespaceURI: ?BSTR,
node: ?*?*IXMLDOMNode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
nodeFromID: fn(
self: *const IXMLDOMDocument,
idString: ?BSTR,
node: ?*?*IXMLDOMNode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
load: fn(
self: *const IXMLDOMDocument,
xmlSource: VARIANT,
isSuccessful: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_readyState: fn(
self: *const IXMLDOMDocument,
value: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_parseError: fn(
self: *const IXMLDOMDocument,
errorObj: ?*?*IXMLDOMParseError,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_url: fn(
self: *const IXMLDOMDocument,
urlString: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_async: fn(
self: *const IXMLDOMDocument,
isAsync: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_async: fn(
self: *const IXMLDOMDocument,
isAsync: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
abort: fn(
self: *const IXMLDOMDocument,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
loadXML: fn(
self: *const IXMLDOMDocument,
bstrXML: ?BSTR,
isSuccessful: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
save: fn(
self: *const IXMLDOMDocument,
destination: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_validateOnParse: fn(
self: *const IXMLDOMDocument,
isValidating: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_validateOnParse: fn(
self: *const IXMLDOMDocument,
isValidating: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_resolveExternals: fn(
self: *const IXMLDOMDocument,
isResolving: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_resolveExternals: fn(
self: *const IXMLDOMDocument,
isResolving: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_preserveWhiteSpace: fn(
self: *const IXMLDOMDocument,
isPreserving: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_preserveWhiteSpace: fn(
self: *const IXMLDOMDocument,
isPreserving: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_onreadystatechange: fn(
self: *const IXMLDOMDocument,
readystatechangeSink: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_ondataavailable: fn(
self: *const IXMLDOMDocument,
ondataavailableSink: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_ontransformnode: fn(
self: *const IXMLDOMDocument,
ontransformnodeSink: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IXMLDOMNode.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument_get_doctype(self: *const T, documentType: ?*?*IXMLDOMDocumentType) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument.VTable, self.vtable).get_doctype(@ptrCast(*const IXMLDOMDocument, self), documentType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument_get_implementation(self: *const T, impl: ?*?*IXMLDOMImplementation) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument.VTable, self.vtable).get_implementation(@ptrCast(*const IXMLDOMDocument, self), impl);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument_get_documentElement(self: *const T, DOMElement: ?*?*IXMLDOMElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument.VTable, self.vtable).get_documentElement(@ptrCast(*const IXMLDOMDocument, self), DOMElement);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument_putref_documentElement(self: *const T, DOMElement: ?*IXMLDOMElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument.VTable, self.vtable).putref_documentElement(@ptrCast(*const IXMLDOMDocument, self), DOMElement);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument_createElement(self: *const T, tagName: ?BSTR, element: ?*?*IXMLDOMElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument.VTable, self.vtable).createElement(@ptrCast(*const IXMLDOMDocument, self), tagName, element);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument_createDocumentFragment(self: *const T, docFrag: ?*?*IXMLDOMDocumentFragment) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument.VTable, self.vtable).createDocumentFragment(@ptrCast(*const IXMLDOMDocument, self), docFrag);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument_createTextNode(self: *const T, data: ?BSTR, text: ?*?*IXMLDOMText) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument.VTable, self.vtable).createTextNode(@ptrCast(*const IXMLDOMDocument, self), data, text);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument_createComment(self: *const T, data: ?BSTR, comment: ?*?*IXMLDOMComment) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument.VTable, self.vtable).createComment(@ptrCast(*const IXMLDOMDocument, self), data, comment);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument_createCDATASection(self: *const T, data: ?BSTR, cdata: ?*?*IXMLDOMCDATASection) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument.VTable, self.vtable).createCDATASection(@ptrCast(*const IXMLDOMDocument, self), data, cdata);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument_createProcessingInstruction(self: *const T, target: ?BSTR, data: ?BSTR, pi: ?*?*IXMLDOMProcessingInstruction) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument.VTable, self.vtable).createProcessingInstruction(@ptrCast(*const IXMLDOMDocument, self), target, data, pi);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument_createAttribute(self: *const T, name: ?BSTR, attribute: ?*?*IXMLDOMAttribute) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument.VTable, self.vtable).createAttribute(@ptrCast(*const IXMLDOMDocument, self), name, attribute);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument_createEntityReference(self: *const T, name: ?BSTR, entityRef: ?*?*IXMLDOMEntityReference) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument.VTable, self.vtable).createEntityReference(@ptrCast(*const IXMLDOMDocument, self), name, entityRef);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument_getElementsByTagName(self: *const T, tagName: ?BSTR, resultList: ?*?*IXMLDOMNodeList) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument.VTable, self.vtable).getElementsByTagName(@ptrCast(*const IXMLDOMDocument, self), tagName, resultList);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument_createNode(self: *const T, Type: VARIANT, name: ?BSTR, namespaceURI: ?BSTR, node: ?*?*IXMLDOMNode) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument.VTable, self.vtable).createNode(@ptrCast(*const IXMLDOMDocument, self), Type, name, namespaceURI, node);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument_nodeFromID(self: *const T, idString: ?BSTR, node: ?*?*IXMLDOMNode) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument.VTable, self.vtable).nodeFromID(@ptrCast(*const IXMLDOMDocument, self), idString, node);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument_load(self: *const T, xmlSource: VARIANT, isSuccessful: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument.VTable, self.vtable).load(@ptrCast(*const IXMLDOMDocument, self), xmlSource, isSuccessful);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument_get_readyState(self: *const T, value: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument.VTable, self.vtable).get_readyState(@ptrCast(*const IXMLDOMDocument, self), value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument_get_parseError(self: *const T, errorObj: ?*?*IXMLDOMParseError) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument.VTable, self.vtable).get_parseError(@ptrCast(*const IXMLDOMDocument, self), errorObj);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument_get_url(self: *const T, urlString: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument.VTable, self.vtable).get_url(@ptrCast(*const IXMLDOMDocument, self), urlString);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument_get_async(self: *const T, isAsync: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument.VTable, self.vtable).get_async(@ptrCast(*const IXMLDOMDocument, self), isAsync);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument_put_async(self: *const T, isAsync: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument.VTable, self.vtable).put_async(@ptrCast(*const IXMLDOMDocument, self), isAsync);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument_abort(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument.VTable, self.vtable).abort(@ptrCast(*const IXMLDOMDocument, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument_loadXML(self: *const T, bstrXML: ?BSTR, isSuccessful: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument.VTable, self.vtable).loadXML(@ptrCast(*const IXMLDOMDocument, self), bstrXML, isSuccessful);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument_save(self: *const T, destination: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument.VTable, self.vtable).save(@ptrCast(*const IXMLDOMDocument, self), destination);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument_get_validateOnParse(self: *const T, isValidating: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument.VTable, self.vtable).get_validateOnParse(@ptrCast(*const IXMLDOMDocument, self), isValidating);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument_put_validateOnParse(self: *const T, isValidating: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument.VTable, self.vtable).put_validateOnParse(@ptrCast(*const IXMLDOMDocument, self), isValidating);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument_get_resolveExternals(self: *const T, isResolving: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument.VTable, self.vtable).get_resolveExternals(@ptrCast(*const IXMLDOMDocument, self), isResolving);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument_put_resolveExternals(self: *const T, isResolving: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument.VTable, self.vtable).put_resolveExternals(@ptrCast(*const IXMLDOMDocument, self), isResolving);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument_get_preserveWhiteSpace(self: *const T, isPreserving: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument.VTable, self.vtable).get_preserveWhiteSpace(@ptrCast(*const IXMLDOMDocument, self), isPreserving);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument_put_preserveWhiteSpace(self: *const T, isPreserving: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument.VTable, self.vtable).put_preserveWhiteSpace(@ptrCast(*const IXMLDOMDocument, self), isPreserving);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument_put_onreadystatechange(self: *const T, readystatechangeSink: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument.VTable, self.vtable).put_onreadystatechange(@ptrCast(*const IXMLDOMDocument, self), readystatechangeSink);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument_put_ondataavailable(self: *const T, ondataavailableSink: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument.VTable, self.vtable).put_ondataavailable(@ptrCast(*const IXMLDOMDocument, self), ondataavailableSink);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument_put_ontransformnode(self: *const T, ontransformnodeSink: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument.VTable, self.vtable).put_ontransformnode(@ptrCast(*const IXMLDOMDocument, self), ontransformnodeSink);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXMLDOMNodeList_Value = @import("../../zig.zig").Guid.initString("2933bf82-7b36-11d2-b20e-00c04f983e60");
pub const IID_IXMLDOMNodeList = &IID_IXMLDOMNodeList_Value;
pub const IXMLDOMNodeList = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_item: fn(
self: *const IXMLDOMNodeList,
index: i32,
listItem: ?*?*IXMLDOMNode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_length: fn(
self: *const IXMLDOMNodeList,
listLength: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
nextNode: fn(
self: *const IXMLDOMNodeList,
nextItem: ?*?*IXMLDOMNode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
reset: fn(
self: *const IXMLDOMNodeList,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get__newEnum: fn(
self: *const IXMLDOMNodeList,
ppUnk: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNodeList_get_item(self: *const T, index: i32, listItem: ?*?*IXMLDOMNode) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNodeList.VTable, self.vtable).get_item(@ptrCast(*const IXMLDOMNodeList, self), index, listItem);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNodeList_get_length(self: *const T, listLength: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNodeList.VTable, self.vtable).get_length(@ptrCast(*const IXMLDOMNodeList, self), listLength);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNodeList_nextNode(self: *const T, nextItem: ?*?*IXMLDOMNode) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNodeList.VTable, self.vtable).nextNode(@ptrCast(*const IXMLDOMNodeList, self), nextItem);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNodeList_reset(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNodeList.VTable, self.vtable).reset(@ptrCast(*const IXMLDOMNodeList, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNodeList_get__newEnum(self: *const T, ppUnk: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNodeList.VTable, self.vtable).get__newEnum(@ptrCast(*const IXMLDOMNodeList, self), ppUnk);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXMLDOMNamedNodeMap_Value = @import("../../zig.zig").Guid.initString("2933bf83-7b36-11d2-b20e-00c04f983e60");
pub const IID_IXMLDOMNamedNodeMap = &IID_IXMLDOMNamedNodeMap_Value;
pub const IXMLDOMNamedNodeMap = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
getNamedItem: fn(
self: *const IXMLDOMNamedNodeMap,
name: ?BSTR,
namedItem: ?*?*IXMLDOMNode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
setNamedItem: fn(
self: *const IXMLDOMNamedNodeMap,
newItem: ?*IXMLDOMNode,
nameItem: ?*?*IXMLDOMNode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
removeNamedItem: fn(
self: *const IXMLDOMNamedNodeMap,
name: ?BSTR,
namedItem: ?*?*IXMLDOMNode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_item: fn(
self: *const IXMLDOMNamedNodeMap,
index: i32,
listItem: ?*?*IXMLDOMNode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_length: fn(
self: *const IXMLDOMNamedNodeMap,
listLength: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getQualifiedItem: fn(
self: *const IXMLDOMNamedNodeMap,
baseName: ?BSTR,
namespaceURI: ?BSTR,
qualifiedItem: ?*?*IXMLDOMNode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
removeQualifiedItem: fn(
self: *const IXMLDOMNamedNodeMap,
baseName: ?BSTR,
namespaceURI: ?BSTR,
qualifiedItem: ?*?*IXMLDOMNode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
nextNode: fn(
self: *const IXMLDOMNamedNodeMap,
nextItem: ?*?*IXMLDOMNode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
reset: fn(
self: *const IXMLDOMNamedNodeMap,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get__newEnum: fn(
self: *const IXMLDOMNamedNodeMap,
ppUnk: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNamedNodeMap_getNamedItem(self: *const T, name: ?BSTR, namedItem: ?*?*IXMLDOMNode) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNamedNodeMap.VTable, self.vtable).getNamedItem(@ptrCast(*const IXMLDOMNamedNodeMap, self), name, namedItem);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNamedNodeMap_setNamedItem(self: *const T, newItem: ?*IXMLDOMNode, nameItem: ?*?*IXMLDOMNode) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNamedNodeMap.VTable, self.vtable).setNamedItem(@ptrCast(*const IXMLDOMNamedNodeMap, self), newItem, nameItem);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNamedNodeMap_removeNamedItem(self: *const T, name: ?BSTR, namedItem: ?*?*IXMLDOMNode) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNamedNodeMap.VTable, self.vtable).removeNamedItem(@ptrCast(*const IXMLDOMNamedNodeMap, self), name, namedItem);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNamedNodeMap_get_item(self: *const T, index: i32, listItem: ?*?*IXMLDOMNode) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNamedNodeMap.VTable, self.vtable).get_item(@ptrCast(*const IXMLDOMNamedNodeMap, self), index, listItem);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNamedNodeMap_get_length(self: *const T, listLength: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNamedNodeMap.VTable, self.vtable).get_length(@ptrCast(*const IXMLDOMNamedNodeMap, self), listLength);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNamedNodeMap_getQualifiedItem(self: *const T, baseName: ?BSTR, namespaceURI: ?BSTR, qualifiedItem: ?*?*IXMLDOMNode) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNamedNodeMap.VTable, self.vtable).getQualifiedItem(@ptrCast(*const IXMLDOMNamedNodeMap, self), baseName, namespaceURI, qualifiedItem);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNamedNodeMap_removeQualifiedItem(self: *const T, baseName: ?BSTR, namespaceURI: ?BSTR, qualifiedItem: ?*?*IXMLDOMNode) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNamedNodeMap.VTable, self.vtable).removeQualifiedItem(@ptrCast(*const IXMLDOMNamedNodeMap, self), baseName, namespaceURI, qualifiedItem);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNamedNodeMap_nextNode(self: *const T, nextItem: ?*?*IXMLDOMNode) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNamedNodeMap.VTable, self.vtable).nextNode(@ptrCast(*const IXMLDOMNamedNodeMap, self), nextItem);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNamedNodeMap_reset(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNamedNodeMap.VTable, self.vtable).reset(@ptrCast(*const IXMLDOMNamedNodeMap, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNamedNodeMap_get__newEnum(self: *const T, ppUnk: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNamedNodeMap.VTable, self.vtable).get__newEnum(@ptrCast(*const IXMLDOMNamedNodeMap, self), ppUnk);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXMLDOMCharacterData_Value = @import("../../zig.zig").Guid.initString("2933bf84-7b36-11d2-b20e-00c04f983e60");
pub const IID_IXMLDOMCharacterData = &IID_IXMLDOMCharacterData_Value;
pub const IXMLDOMCharacterData = extern struct {
pub const VTable = extern struct {
base: IXMLDOMNode.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_data: fn(
self: *const IXMLDOMCharacterData,
data: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_data: fn(
self: *const IXMLDOMCharacterData,
data: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_length: fn(
self: *const IXMLDOMCharacterData,
dataLength: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
substringData: fn(
self: *const IXMLDOMCharacterData,
offset: i32,
count: i32,
data: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
appendData: fn(
self: *const IXMLDOMCharacterData,
data: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
insertData: fn(
self: *const IXMLDOMCharacterData,
offset: i32,
data: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
deleteData: fn(
self: *const IXMLDOMCharacterData,
offset: i32,
count: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
replaceData: fn(
self: *const IXMLDOMCharacterData,
offset: i32,
count: i32,
data: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IXMLDOMNode.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMCharacterData_get_data(self: *const T, data: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMCharacterData.VTable, self.vtable).get_data(@ptrCast(*const IXMLDOMCharacterData, self), data);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMCharacterData_put_data(self: *const T, data: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMCharacterData.VTable, self.vtable).put_data(@ptrCast(*const IXMLDOMCharacterData, self), data);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMCharacterData_get_length(self: *const T, dataLength: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMCharacterData.VTable, self.vtable).get_length(@ptrCast(*const IXMLDOMCharacterData, self), dataLength);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMCharacterData_substringData(self: *const T, offset: i32, count: i32, data: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMCharacterData.VTable, self.vtable).substringData(@ptrCast(*const IXMLDOMCharacterData, self), offset, count, data);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMCharacterData_appendData(self: *const T, data: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMCharacterData.VTable, self.vtable).appendData(@ptrCast(*const IXMLDOMCharacterData, self), data);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMCharacterData_insertData(self: *const T, offset: i32, data: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMCharacterData.VTable, self.vtable).insertData(@ptrCast(*const IXMLDOMCharacterData, self), offset, data);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMCharacterData_deleteData(self: *const T, offset: i32, count: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMCharacterData.VTable, self.vtable).deleteData(@ptrCast(*const IXMLDOMCharacterData, self), offset, count);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMCharacterData_replaceData(self: *const T, offset: i32, count: i32, data: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMCharacterData.VTable, self.vtable).replaceData(@ptrCast(*const IXMLDOMCharacterData, self), offset, count, data);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXMLDOMAttribute_Value = @import("../../zig.zig").Guid.initString("2933bf85-7b36-11d2-b20e-00c04f983e60");
pub const IID_IXMLDOMAttribute = &IID_IXMLDOMAttribute_Value;
pub const IXMLDOMAttribute = extern struct {
pub const VTable = extern struct {
base: IXMLDOMNode.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_name: fn(
self: *const IXMLDOMAttribute,
attributeName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_value: fn(
self: *const IXMLDOMAttribute,
attributeValue: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_value: fn(
self: *const IXMLDOMAttribute,
attributeValue: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IXMLDOMNode.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMAttribute_get_name(self: *const T, attributeName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMAttribute.VTable, self.vtable).get_name(@ptrCast(*const IXMLDOMAttribute, self), attributeName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMAttribute_get_value(self: *const T, attributeValue: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMAttribute.VTable, self.vtable).get_value(@ptrCast(*const IXMLDOMAttribute, self), attributeValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMAttribute_put_value(self: *const T, attributeValue: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMAttribute.VTable, self.vtable).put_value(@ptrCast(*const IXMLDOMAttribute, self), attributeValue);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXMLDOMElement_Value = @import("../../zig.zig").Guid.initString("2933bf86-7b36-11d2-b20e-00c04f983e60");
pub const IID_IXMLDOMElement = &IID_IXMLDOMElement_Value;
pub const IXMLDOMElement = extern struct {
pub const VTable = extern struct {
base: IXMLDOMNode.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_tagName: fn(
self: *const IXMLDOMElement,
tagName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getAttribute: fn(
self: *const IXMLDOMElement,
name: ?BSTR,
value: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
setAttribute: fn(
self: *const IXMLDOMElement,
name: ?BSTR,
value: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
removeAttribute: fn(
self: *const IXMLDOMElement,
name: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getAttributeNode: fn(
self: *const IXMLDOMElement,
name: ?BSTR,
attributeNode: ?*?*IXMLDOMAttribute,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
setAttributeNode: fn(
self: *const IXMLDOMElement,
DOMAttribute: ?*IXMLDOMAttribute,
attributeNode: ?*?*IXMLDOMAttribute,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
removeAttributeNode: fn(
self: *const IXMLDOMElement,
DOMAttribute: ?*IXMLDOMAttribute,
attributeNode: ?*?*IXMLDOMAttribute,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getElementsByTagName: fn(
self: *const IXMLDOMElement,
tagName: ?BSTR,
resultList: ?*?*IXMLDOMNodeList,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
normalize: fn(
self: *const IXMLDOMElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IXMLDOMNode.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMElement_get_tagName(self: *const T, tagName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMElement.VTable, self.vtable).get_tagName(@ptrCast(*const IXMLDOMElement, self), tagName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMElement_getAttribute(self: *const T, name: ?BSTR, value: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMElement.VTable, self.vtable).getAttribute(@ptrCast(*const IXMLDOMElement, self), name, value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMElement_setAttribute(self: *const T, name: ?BSTR, value: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMElement.VTable, self.vtable).setAttribute(@ptrCast(*const IXMLDOMElement, self), name, value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMElement_removeAttribute(self: *const T, name: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMElement.VTable, self.vtable).removeAttribute(@ptrCast(*const IXMLDOMElement, self), name);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMElement_getAttributeNode(self: *const T, name: ?BSTR, attributeNode: ?*?*IXMLDOMAttribute) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMElement.VTable, self.vtable).getAttributeNode(@ptrCast(*const IXMLDOMElement, self), name, attributeNode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMElement_setAttributeNode(self: *const T, DOMAttribute: ?*IXMLDOMAttribute, attributeNode: ?*?*IXMLDOMAttribute) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMElement.VTable, self.vtable).setAttributeNode(@ptrCast(*const IXMLDOMElement, self), DOMAttribute, attributeNode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMElement_removeAttributeNode(self: *const T, DOMAttribute: ?*IXMLDOMAttribute, attributeNode: ?*?*IXMLDOMAttribute) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMElement.VTable, self.vtable).removeAttributeNode(@ptrCast(*const IXMLDOMElement, self), DOMAttribute, attributeNode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMElement_getElementsByTagName(self: *const T, tagName: ?BSTR, resultList: ?*?*IXMLDOMNodeList) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMElement.VTable, self.vtable).getElementsByTagName(@ptrCast(*const IXMLDOMElement, self), tagName, resultList);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMElement_normalize(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMElement.VTable, self.vtable).normalize(@ptrCast(*const IXMLDOMElement, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXMLDOMText_Value = @import("../../zig.zig").Guid.initString("2933bf87-7b36-11d2-b20e-00c04f983e60");
pub const IID_IXMLDOMText = &IID_IXMLDOMText_Value;
pub const IXMLDOMText = extern struct {
pub const VTable = extern struct {
base: IXMLDOMCharacterData.VTable,
splitText: fn(
self: *const IXMLDOMText,
offset: i32,
rightHandTextNode: ?*?*IXMLDOMText,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IXMLDOMCharacterData.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMText_splitText(self: *const T, offset: i32, rightHandTextNode: ?*?*IXMLDOMText) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMText.VTable, self.vtable).splitText(@ptrCast(*const IXMLDOMText, self), offset, rightHandTextNode);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXMLDOMComment_Value = @import("../../zig.zig").Guid.initString("2933bf88-7b36-11d2-b20e-00c04f983e60");
pub const IID_IXMLDOMComment = &IID_IXMLDOMComment_Value;
pub const IXMLDOMComment = extern struct {
pub const VTable = extern struct {
base: IXMLDOMCharacterData.VTable,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IXMLDOMCharacterData.MethodMixin(T);
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXMLDOMProcessingInstruction_Value = @import("../../zig.zig").Guid.initString("2933bf89-7b36-11d2-b20e-00c04f983e60");
pub const IID_IXMLDOMProcessingInstruction = &IID_IXMLDOMProcessingInstruction_Value;
pub const IXMLDOMProcessingInstruction = extern struct {
pub const VTable = extern struct {
base: IXMLDOMNode.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_target: fn(
self: *const IXMLDOMProcessingInstruction,
name: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_data: fn(
self: *const IXMLDOMProcessingInstruction,
value: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_data: fn(
self: *const IXMLDOMProcessingInstruction,
value: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IXMLDOMNode.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMProcessingInstruction_get_target(self: *const T, name: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMProcessingInstruction.VTable, self.vtable).get_target(@ptrCast(*const IXMLDOMProcessingInstruction, self), name);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMProcessingInstruction_get_data(self: *const T, value: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMProcessingInstruction.VTable, self.vtable).get_data(@ptrCast(*const IXMLDOMProcessingInstruction, self), value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMProcessingInstruction_put_data(self: *const T, value: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMProcessingInstruction.VTable, self.vtable).put_data(@ptrCast(*const IXMLDOMProcessingInstruction, self), value);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXMLDOMCDATASection_Value = @import("../../zig.zig").Guid.initString("2933bf8a-7b36-11d2-b20e-00c04f983e60");
pub const IID_IXMLDOMCDATASection = &IID_IXMLDOMCDATASection_Value;
pub const IXMLDOMCDATASection = extern struct {
pub const VTable = extern struct {
base: IXMLDOMText.VTable,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IXMLDOMText.MethodMixin(T);
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXMLDOMDocumentType_Value = @import("../../zig.zig").Guid.initString("2933bf8b-7b36-11d2-b20e-00c04f983e60");
pub const IID_IXMLDOMDocumentType = &IID_IXMLDOMDocumentType_Value;
pub const IXMLDOMDocumentType = extern struct {
pub const VTable = extern struct {
base: IXMLDOMNode.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_name: fn(
self: *const IXMLDOMDocumentType,
rootName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_entities: fn(
self: *const IXMLDOMDocumentType,
entityMap: ?*?*IXMLDOMNamedNodeMap,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_notations: fn(
self: *const IXMLDOMDocumentType,
notationMap: ?*?*IXMLDOMNamedNodeMap,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IXMLDOMNode.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocumentType_get_name(self: *const T, rootName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocumentType.VTable, self.vtable).get_name(@ptrCast(*const IXMLDOMDocumentType, self), rootName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocumentType_get_entities(self: *const T, entityMap: ?*?*IXMLDOMNamedNodeMap) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocumentType.VTable, self.vtable).get_entities(@ptrCast(*const IXMLDOMDocumentType, self), entityMap);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocumentType_get_notations(self: *const T, notationMap: ?*?*IXMLDOMNamedNodeMap) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocumentType.VTable, self.vtable).get_notations(@ptrCast(*const IXMLDOMDocumentType, self), notationMap);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXMLDOMNotation_Value = @import("../../zig.zig").Guid.initString("2933bf8c-7b36-11d2-b20e-00c04f983e60");
pub const IID_IXMLDOMNotation = &IID_IXMLDOMNotation_Value;
pub const IXMLDOMNotation = extern struct {
pub const VTable = extern struct {
base: IXMLDOMNode.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_publicId: fn(
self: *const IXMLDOMNotation,
publicID: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_systemId: fn(
self: *const IXMLDOMNotation,
systemID: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IXMLDOMNode.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNotation_get_publicId(self: *const T, publicID: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNotation.VTable, self.vtable).get_publicId(@ptrCast(*const IXMLDOMNotation, self), publicID);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMNotation_get_systemId(self: *const T, systemID: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMNotation.VTable, self.vtable).get_systemId(@ptrCast(*const IXMLDOMNotation, self), systemID);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXMLDOMEntity_Value = @import("../../zig.zig").Guid.initString("2933bf8d-7b36-11d2-b20e-00c04f983e60");
pub const IID_IXMLDOMEntity = &IID_IXMLDOMEntity_Value;
pub const IXMLDOMEntity = extern struct {
pub const VTable = extern struct {
base: IXMLDOMNode.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_publicId: fn(
self: *const IXMLDOMEntity,
publicID: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_systemId: fn(
self: *const IXMLDOMEntity,
systemID: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_notationName: fn(
self: *const IXMLDOMEntity,
name: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IXMLDOMNode.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMEntity_get_publicId(self: *const T, publicID: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMEntity.VTable, self.vtable).get_publicId(@ptrCast(*const IXMLDOMEntity, self), publicID);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMEntity_get_systemId(self: *const T, systemID: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMEntity.VTable, self.vtable).get_systemId(@ptrCast(*const IXMLDOMEntity, self), systemID);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMEntity_get_notationName(self: *const T, name: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMEntity.VTable, self.vtable).get_notationName(@ptrCast(*const IXMLDOMEntity, self), name);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXMLDOMEntityReference_Value = @import("../../zig.zig").Guid.initString("2933bf8e-7b36-11d2-b20e-00c04f983e60");
pub const IID_IXMLDOMEntityReference = &IID_IXMLDOMEntityReference_Value;
pub const IXMLDOMEntityReference = extern struct {
pub const VTable = extern struct {
base: IXMLDOMNode.VTable,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IXMLDOMNode.MethodMixin(T);
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXMLDOMParseError_Value = @import("../../zig.zig").Guid.initString("3efaa426-272f-11d2-836f-0000f87a7782");
pub const IID_IXMLDOMParseError = &IID_IXMLDOMParseError_Value;
pub const IXMLDOMParseError = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_errorCode: fn(
self: *const IXMLDOMParseError,
errorCode: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_url: fn(
self: *const IXMLDOMParseError,
urlString: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_reason: fn(
self: *const IXMLDOMParseError,
reasonString: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_srcText: fn(
self: *const IXMLDOMParseError,
sourceString: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_line: fn(
self: *const IXMLDOMParseError,
lineNumber: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_linepos: fn(
self: *const IXMLDOMParseError,
linePosition: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_filepos: fn(
self: *const IXMLDOMParseError,
filePosition: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMParseError_get_errorCode(self: *const T, errorCode: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMParseError.VTable, self.vtable).get_errorCode(@ptrCast(*const IXMLDOMParseError, self), errorCode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMParseError_get_url(self: *const T, urlString: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMParseError.VTable, self.vtable).get_url(@ptrCast(*const IXMLDOMParseError, self), urlString);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMParseError_get_reason(self: *const T, reasonString: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMParseError.VTable, self.vtable).get_reason(@ptrCast(*const IXMLDOMParseError, self), reasonString);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMParseError_get_srcText(self: *const T, sourceString: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMParseError.VTable, self.vtable).get_srcText(@ptrCast(*const IXMLDOMParseError, self), sourceString);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMParseError_get_line(self: *const T, lineNumber: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMParseError.VTable, self.vtable).get_line(@ptrCast(*const IXMLDOMParseError, self), lineNumber);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMParseError_get_linepos(self: *const T, linePosition: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMParseError.VTable, self.vtable).get_linepos(@ptrCast(*const IXMLDOMParseError, self), linePosition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMParseError_get_filepos(self: *const T, filePosition: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMParseError.VTable, self.vtable).get_filepos(@ptrCast(*const IXMLDOMParseError, self), filePosition);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXTLRuntime_Value = @import("../../zig.zig").Guid.initString("3efaa425-272f-11d2-836f-0000f87a7782");
pub const IID_IXTLRuntime = &IID_IXTLRuntime_Value;
pub const IXTLRuntime = extern struct {
pub const VTable = extern struct {
base: IXMLDOMNode.VTable,
uniqueID: fn(
self: *const IXTLRuntime,
pNode: ?*IXMLDOMNode,
pID: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
depth: fn(
self: *const IXTLRuntime,
pNode: ?*IXMLDOMNode,
pDepth: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
childNumber: fn(
self: *const IXTLRuntime,
pNode: ?*IXMLDOMNode,
pNumber: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ancestorChildNumber: fn(
self: *const IXTLRuntime,
bstrNodeName: ?BSTR,
pNode: ?*IXMLDOMNode,
pNumber: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
absoluteChildNumber: fn(
self: *const IXTLRuntime,
pNode: ?*IXMLDOMNode,
pNumber: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
formatIndex: fn(
self: *const IXTLRuntime,
lIndex: i32,
bstrFormat: ?BSTR,
pbstrFormattedString: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
formatNumber: fn(
self: *const IXTLRuntime,
dblNumber: f64,
bstrFormat: ?BSTR,
pbstrFormattedString: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
formatDate: fn(
self: *const IXTLRuntime,
varDate: VARIANT,
bstrFormat: ?BSTR,
varDestLocale: VARIANT,
pbstrFormattedString: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
formatTime: fn(
self: *const IXTLRuntime,
varTime: VARIANT,
bstrFormat: ?BSTR,
varDestLocale: VARIANT,
pbstrFormattedString: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IXMLDOMNode.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXTLRuntime_uniqueID(self: *const T, pNode: ?*IXMLDOMNode, pID: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXTLRuntime.VTable, self.vtable).uniqueID(@ptrCast(*const IXTLRuntime, self), pNode, pID);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXTLRuntime_depth(self: *const T, pNode: ?*IXMLDOMNode, pDepth: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXTLRuntime.VTable, self.vtable).depth(@ptrCast(*const IXTLRuntime, self), pNode, pDepth);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXTLRuntime_childNumber(self: *const T, pNode: ?*IXMLDOMNode, pNumber: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXTLRuntime.VTable, self.vtable).childNumber(@ptrCast(*const IXTLRuntime, self), pNode, pNumber);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXTLRuntime_ancestorChildNumber(self: *const T, bstrNodeName: ?BSTR, pNode: ?*IXMLDOMNode, pNumber: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXTLRuntime.VTable, self.vtable).ancestorChildNumber(@ptrCast(*const IXTLRuntime, self), bstrNodeName, pNode, pNumber);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXTLRuntime_absoluteChildNumber(self: *const T, pNode: ?*IXMLDOMNode, pNumber: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXTLRuntime.VTable, self.vtable).absoluteChildNumber(@ptrCast(*const IXTLRuntime, self), pNode, pNumber);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXTLRuntime_formatIndex(self: *const T, lIndex: i32, bstrFormat: ?BSTR, pbstrFormattedString: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXTLRuntime.VTable, self.vtable).formatIndex(@ptrCast(*const IXTLRuntime, self), lIndex, bstrFormat, pbstrFormattedString);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXTLRuntime_formatNumber(self: *const T, dblNumber: f64, bstrFormat: ?BSTR, pbstrFormattedString: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXTLRuntime.VTable, self.vtable).formatNumber(@ptrCast(*const IXTLRuntime, self), dblNumber, bstrFormat, pbstrFormattedString);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXTLRuntime_formatDate(self: *const T, varDate: VARIANT, bstrFormat: ?BSTR, varDestLocale: VARIANT, pbstrFormattedString: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXTLRuntime.VTable, self.vtable).formatDate(@ptrCast(*const IXTLRuntime, self), varDate, bstrFormat, varDestLocale, pbstrFormattedString);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXTLRuntime_formatTime(self: *const T, varTime: VARIANT, bstrFormat: ?BSTR, varDestLocale: VARIANT, pbstrFormattedString: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXTLRuntime.VTable, self.vtable).formatTime(@ptrCast(*const IXTLRuntime, self), varTime, bstrFormat, varDestLocale, pbstrFormattedString);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_XMLDOMDocumentEvents_Value = @import("../../zig.zig").Guid.initString("3efaa427-272f-11d2-836f-0000f87a7782");
pub const IID_XMLDOMDocumentEvents = &IID_XMLDOMDocumentEvents_Value;
pub const XMLDOMDocumentEvents = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXMLHttpRequest_Value = @import("../../zig.zig").Guid.initString("ed8c108d-4349-11d2-91a4-00c04f7969e8");
pub const IID_IXMLHttpRequest = &IID_IXMLHttpRequest_Value;
pub const IXMLHttpRequest = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
open: fn(
self: *const IXMLHttpRequest,
bstrMethod: ?BSTR,
bstrUrl: ?BSTR,
varAsync: VARIANT,
bstrUser: VARIANT,
bstrPassword: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
setRequestHeader: fn(
self: *const IXMLHttpRequest,
bstrHeader: ?BSTR,
bstrValue: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getResponseHeader: fn(
self: *const IXMLHttpRequest,
bstrHeader: ?BSTR,
pbstrValue: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getAllResponseHeaders: fn(
self: *const IXMLHttpRequest,
pbstrHeaders: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
send: fn(
self: *const IXMLHttpRequest,
varBody: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
abort: fn(
self: *const IXMLHttpRequest,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_status: fn(
self: *const IXMLHttpRequest,
plStatus: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_statusText: fn(
self: *const IXMLHttpRequest,
pbstrStatus: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_responseXML: fn(
self: *const IXMLHttpRequest,
ppBody: ?*?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_responseText: fn(
self: *const IXMLHttpRequest,
pbstrBody: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_responseBody: fn(
self: *const IXMLHttpRequest,
pvarBody: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_responseStream: fn(
self: *const IXMLHttpRequest,
pvarBody: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_readyState: fn(
self: *const IXMLHttpRequest,
plState: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_onreadystatechange: fn(
self: *const IXMLHttpRequest,
pReadyStateSink: ?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHttpRequest_open(self: *const T, bstrMethod: ?BSTR, bstrUrl: ?BSTR, varAsync: VARIANT, bstrUser: VARIANT, bstrPassword: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHttpRequest.VTable, self.vtable).open(@ptrCast(*const IXMLHttpRequest, self), bstrMethod, bstrUrl, varAsync, bstrUser, bstrPassword);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHttpRequest_setRequestHeader(self: *const T, bstrHeader: ?BSTR, bstrValue: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHttpRequest.VTable, self.vtable).setRequestHeader(@ptrCast(*const IXMLHttpRequest, self), bstrHeader, bstrValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHttpRequest_getResponseHeader(self: *const T, bstrHeader: ?BSTR, pbstrValue: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHttpRequest.VTable, self.vtable).getResponseHeader(@ptrCast(*const IXMLHttpRequest, self), bstrHeader, pbstrValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHttpRequest_getAllResponseHeaders(self: *const T, pbstrHeaders: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHttpRequest.VTable, self.vtable).getAllResponseHeaders(@ptrCast(*const IXMLHttpRequest, self), pbstrHeaders);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHttpRequest_send(self: *const T, varBody: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHttpRequest.VTable, self.vtable).send(@ptrCast(*const IXMLHttpRequest, self), varBody);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHttpRequest_abort(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHttpRequest.VTable, self.vtable).abort(@ptrCast(*const IXMLHttpRequest, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHttpRequest_get_status(self: *const T, plStatus: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHttpRequest.VTable, self.vtable).get_status(@ptrCast(*const IXMLHttpRequest, self), plStatus);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHttpRequest_get_statusText(self: *const T, pbstrStatus: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHttpRequest.VTable, self.vtable).get_statusText(@ptrCast(*const IXMLHttpRequest, self), pbstrStatus);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHttpRequest_get_responseXML(self: *const T, ppBody: ?*?*IDispatch) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHttpRequest.VTable, self.vtable).get_responseXML(@ptrCast(*const IXMLHttpRequest, self), ppBody);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHttpRequest_get_responseText(self: *const T, pbstrBody: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHttpRequest.VTable, self.vtable).get_responseText(@ptrCast(*const IXMLHttpRequest, self), pbstrBody);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHttpRequest_get_responseBody(self: *const T, pvarBody: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHttpRequest.VTable, self.vtable).get_responseBody(@ptrCast(*const IXMLHttpRequest, self), pvarBody);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHttpRequest_get_responseStream(self: *const T, pvarBody: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHttpRequest.VTable, self.vtable).get_responseStream(@ptrCast(*const IXMLHttpRequest, self), pvarBody);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHttpRequest_get_readyState(self: *const T, plState: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHttpRequest.VTable, self.vtable).get_readyState(@ptrCast(*const IXMLHttpRequest, self), plState);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHttpRequest_put_onreadystatechange(self: *const T, pReadyStateSink: ?*IDispatch) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHttpRequest.VTable, self.vtable).put_onreadystatechange(@ptrCast(*const IXMLHttpRequest, self), pReadyStateSink);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXMLDSOControl_Value = @import("../../zig.zig").Guid.initString("310afa62-0575-11d2-9ca9-0060b0ec3d39");
pub const IID_IXMLDSOControl = &IID_IXMLDSOControl_Value;
pub const IXMLDSOControl = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_XMLDocument: fn(
self: *const IXMLDSOControl,
ppDoc: ?*?*IXMLDOMDocument,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_XMLDocument: fn(
self: *const IXMLDSOControl,
ppDoc: ?*IXMLDOMDocument,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_JavaDSOCompatible: fn(
self: *const IXMLDSOControl,
fJavaDSOCompatible: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_JavaDSOCompatible: fn(
self: *const IXMLDSOControl,
fJavaDSOCompatible: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_readyState: fn(
self: *const IXMLDSOControl,
state: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDSOControl_get_XMLDocument(self: *const T, ppDoc: ?*?*IXMLDOMDocument) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDSOControl.VTable, self.vtable).get_XMLDocument(@ptrCast(*const IXMLDSOControl, self), ppDoc);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDSOControl_put_XMLDocument(self: *const T, ppDoc: ?*IXMLDOMDocument) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDSOControl.VTable, self.vtable).put_XMLDocument(@ptrCast(*const IXMLDSOControl, self), ppDoc);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDSOControl_get_JavaDSOCompatible(self: *const T, fJavaDSOCompatible: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDSOControl.VTable, self.vtable).get_JavaDSOCompatible(@ptrCast(*const IXMLDSOControl, self), fJavaDSOCompatible);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDSOControl_put_JavaDSOCompatible(self: *const T, fJavaDSOCompatible: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDSOControl.VTable, self.vtable).put_JavaDSOCompatible(@ptrCast(*const IXMLDSOControl, self), fJavaDSOCompatible);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDSOControl_get_readyState(self: *const T, state: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDSOControl.VTable, self.vtable).get_readyState(@ptrCast(*const IXMLDSOControl, self), state);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXMLElementCollection_Value = @import("../../zig.zig").Guid.initString("65725580-9b5d-11d0-9bfe-00c04fc99c8e");
pub const IID_IXMLElementCollection = &IID_IXMLElementCollection_Value;
pub const IXMLElementCollection = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_length: fn(
self: *const IXMLElementCollection,
v: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_length: fn(
self: *const IXMLElementCollection,
p: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get__newEnum: fn(
self: *const IXMLElementCollection,
ppUnk: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
item: fn(
self: *const IXMLElementCollection,
var1: VARIANT,
var2: VARIANT,
ppDisp: ?*?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLElementCollection_put_length(self: *const T, v: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLElementCollection.VTable, self.vtable).put_length(@ptrCast(*const IXMLElementCollection, self), v);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLElementCollection_get_length(self: *const T, p: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLElementCollection.VTable, self.vtable).get_length(@ptrCast(*const IXMLElementCollection, self), p);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLElementCollection_get__newEnum(self: *const T, ppUnk: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLElementCollection.VTable, self.vtable).get__newEnum(@ptrCast(*const IXMLElementCollection, self), ppUnk);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLElementCollection_item(self: *const T, var1: VARIANT, var2: VARIANT, ppDisp: ?*?*IDispatch) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLElementCollection.VTable, self.vtable).item(@ptrCast(*const IXMLElementCollection, self), var1, var2, ppDisp);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXMLDocument_Value = @import("../../zig.zig").Guid.initString("f52e2b61-18a1-11d1-b105-00805f49916b");
pub const IID_IXMLDocument = &IID_IXMLDocument_Value;
pub const IXMLDocument = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_root: fn(
self: *const IXMLDocument,
p: ?*?*IXMLElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_fileSize: fn(
self: *const IXMLDocument,
p: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_fileModifiedDate: fn(
self: *const IXMLDocument,
p: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_fileUpdatedDate: fn(
self: *const IXMLDocument,
p: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_URL: fn(
self: *const IXMLDocument,
p: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_URL: fn(
self: *const IXMLDocument,
p: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_mimeType: fn(
self: *const IXMLDocument,
p: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_readyState: fn(
self: *const IXMLDocument,
pl: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_charset: fn(
self: *const IXMLDocument,
p: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_charset: fn(
self: *const IXMLDocument,
p: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_version: fn(
self: *const IXMLDocument,
p: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_doctype: fn(
self: *const IXMLDocument,
p: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_dtdURL: fn(
self: *const IXMLDocument,
p: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
createElement: fn(
self: *const IXMLDocument,
vType: VARIANT,
var1: VARIANT,
ppElem: ?*?*IXMLElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDocument_get_root(self: *const T, p: ?*?*IXMLElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDocument.VTable, self.vtable).get_root(@ptrCast(*const IXMLDocument, self), p);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDocument_get_fileSize(self: *const T, p: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDocument.VTable, self.vtable).get_fileSize(@ptrCast(*const IXMLDocument, self), p);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDocument_get_fileModifiedDate(self: *const T, p: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDocument.VTable, self.vtable).get_fileModifiedDate(@ptrCast(*const IXMLDocument, self), p);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDocument_get_fileUpdatedDate(self: *const T, p: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDocument.VTable, self.vtable).get_fileUpdatedDate(@ptrCast(*const IXMLDocument, self), p);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDocument_get_URL(self: *const T, p: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDocument.VTable, self.vtable).get_URL(@ptrCast(*const IXMLDocument, self), p);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDocument_put_URL(self: *const T, p: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDocument.VTable, self.vtable).put_URL(@ptrCast(*const IXMLDocument, self), p);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDocument_get_mimeType(self: *const T, p: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDocument.VTable, self.vtable).get_mimeType(@ptrCast(*const IXMLDocument, self), p);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDocument_get_readyState(self: *const T, pl: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDocument.VTable, self.vtable).get_readyState(@ptrCast(*const IXMLDocument, self), pl);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDocument_get_charset(self: *const T, p: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDocument.VTable, self.vtable).get_charset(@ptrCast(*const IXMLDocument, self), p);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDocument_put_charset(self: *const T, p: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDocument.VTable, self.vtable).put_charset(@ptrCast(*const IXMLDocument, self), p);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDocument_get_version(self: *const T, p: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDocument.VTable, self.vtable).get_version(@ptrCast(*const IXMLDocument, self), p);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDocument_get_doctype(self: *const T, p: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDocument.VTable, self.vtable).get_doctype(@ptrCast(*const IXMLDocument, self), p);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDocument_get_dtdURL(self: *const T, p: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDocument.VTable, self.vtable).get_dtdURL(@ptrCast(*const IXMLDocument, self), p);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDocument_createElement(self: *const T, vType: VARIANT, var1: VARIANT, ppElem: ?*?*IXMLElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDocument.VTable, self.vtable).createElement(@ptrCast(*const IXMLDocument, self), vType, var1, ppElem);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXMLDocument2_Value = @import("../../zig.zig").Guid.initString("2b8de2fe-8d2d-11d1-b2fc-00c04fd915a9");
pub const IID_IXMLDocument2 = &IID_IXMLDocument2_Value;
pub const IXMLDocument2 = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_root: fn(
self: *const IXMLDocument2,
p: ?*?*IXMLElement2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_fileSize: fn(
self: *const IXMLDocument2,
p: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_fileModifiedDate: fn(
self: *const IXMLDocument2,
p: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_fileUpdatedDate: fn(
self: *const IXMLDocument2,
p: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_URL: fn(
self: *const IXMLDocument2,
p: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_URL: fn(
self: *const IXMLDocument2,
p: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_mimeType: fn(
self: *const IXMLDocument2,
p: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_readyState: fn(
self: *const IXMLDocument2,
pl: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_charset: fn(
self: *const IXMLDocument2,
p: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_charset: fn(
self: *const IXMLDocument2,
p: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_version: fn(
self: *const IXMLDocument2,
p: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_doctype: fn(
self: *const IXMLDocument2,
p: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_dtdURL: fn(
self: *const IXMLDocument2,
p: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
createElement: fn(
self: *const IXMLDocument2,
vType: VARIANT,
var1: VARIANT,
ppElem: ?*?*IXMLElement2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_async: fn(
self: *const IXMLDocument2,
pf: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_async: fn(
self: *const IXMLDocument2,
f: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDocument2_get_root(self: *const T, p: ?*?*IXMLElement2) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDocument2.VTable, self.vtable).get_root(@ptrCast(*const IXMLDocument2, self), p);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDocument2_get_fileSize(self: *const T, p: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDocument2.VTable, self.vtable).get_fileSize(@ptrCast(*const IXMLDocument2, self), p);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDocument2_get_fileModifiedDate(self: *const T, p: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDocument2.VTable, self.vtable).get_fileModifiedDate(@ptrCast(*const IXMLDocument2, self), p);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDocument2_get_fileUpdatedDate(self: *const T, p: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDocument2.VTable, self.vtable).get_fileUpdatedDate(@ptrCast(*const IXMLDocument2, self), p);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDocument2_get_URL(self: *const T, p: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDocument2.VTable, self.vtable).get_URL(@ptrCast(*const IXMLDocument2, self), p);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDocument2_put_URL(self: *const T, p: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDocument2.VTable, self.vtable).put_URL(@ptrCast(*const IXMLDocument2, self), p);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDocument2_get_mimeType(self: *const T, p: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDocument2.VTable, self.vtable).get_mimeType(@ptrCast(*const IXMLDocument2, self), p);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDocument2_get_readyState(self: *const T, pl: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDocument2.VTable, self.vtable).get_readyState(@ptrCast(*const IXMLDocument2, self), pl);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDocument2_get_charset(self: *const T, p: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDocument2.VTable, self.vtable).get_charset(@ptrCast(*const IXMLDocument2, self), p);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDocument2_put_charset(self: *const T, p: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDocument2.VTable, self.vtable).put_charset(@ptrCast(*const IXMLDocument2, self), p);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDocument2_get_version(self: *const T, p: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDocument2.VTable, self.vtable).get_version(@ptrCast(*const IXMLDocument2, self), p);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDocument2_get_doctype(self: *const T, p: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDocument2.VTable, self.vtable).get_doctype(@ptrCast(*const IXMLDocument2, self), p);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDocument2_get_dtdURL(self: *const T, p: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDocument2.VTable, self.vtable).get_dtdURL(@ptrCast(*const IXMLDocument2, self), p);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDocument2_createElement(self: *const T, vType: VARIANT, var1: VARIANT, ppElem: ?*?*IXMLElement2) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDocument2.VTable, self.vtable).createElement(@ptrCast(*const IXMLDocument2, self), vType, var1, ppElem);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDocument2_get_async(self: *const T, pf: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDocument2.VTable, self.vtable).get_async(@ptrCast(*const IXMLDocument2, self), pf);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDocument2_put_async(self: *const T, f: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDocument2.VTable, self.vtable).put_async(@ptrCast(*const IXMLDocument2, self), f);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXMLElement_Value = @import("../../zig.zig").Guid.initString("3f7f31ac-e15f-11d0-9c25-00c04fc99c8e");
pub const IID_IXMLElement = &IID_IXMLElement_Value;
pub const IXMLElement = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_tagName: fn(
self: *const IXMLElement,
p: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_tagName: fn(
self: *const IXMLElement,
p: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_parent: fn(
self: *const IXMLElement,
ppParent: ?*?*IXMLElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
setAttribute: fn(
self: *const IXMLElement,
strPropertyName: ?BSTR,
PropertyValue: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getAttribute: fn(
self: *const IXMLElement,
strPropertyName: ?BSTR,
PropertyValue: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
removeAttribute: fn(
self: *const IXMLElement,
strPropertyName: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_children: fn(
self: *const IXMLElement,
pp: ?*?*IXMLElementCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_type: fn(
self: *const IXMLElement,
plType: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_text: fn(
self: *const IXMLElement,
p: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_text: fn(
self: *const IXMLElement,
p: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
addChild: fn(
self: *const IXMLElement,
pChildElem: ?*IXMLElement,
lIndex: i32,
lReserved: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
removeChild: fn(
self: *const IXMLElement,
pChildElem: ?*IXMLElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLElement_get_tagName(self: *const T, p: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLElement.VTable, self.vtable).get_tagName(@ptrCast(*const IXMLElement, self), p);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLElement_put_tagName(self: *const T, p: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLElement.VTable, self.vtable).put_tagName(@ptrCast(*const IXMLElement, self), p);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLElement_get_parent(self: *const T, ppParent: ?*?*IXMLElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLElement.VTable, self.vtable).get_parent(@ptrCast(*const IXMLElement, self), ppParent);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLElement_setAttribute(self: *const T, strPropertyName: ?BSTR, PropertyValue: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLElement.VTable, self.vtable).setAttribute(@ptrCast(*const IXMLElement, self), strPropertyName, PropertyValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLElement_getAttribute(self: *const T, strPropertyName: ?BSTR, PropertyValue: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLElement.VTable, self.vtable).getAttribute(@ptrCast(*const IXMLElement, self), strPropertyName, PropertyValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLElement_removeAttribute(self: *const T, strPropertyName: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLElement.VTable, self.vtable).removeAttribute(@ptrCast(*const IXMLElement, self), strPropertyName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLElement_get_children(self: *const T, pp: ?*?*IXMLElementCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLElement.VTable, self.vtable).get_children(@ptrCast(*const IXMLElement, self), pp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLElement_get_type(self: *const T, plType: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLElement.VTable, self.vtable).get_type(@ptrCast(*const IXMLElement, self), plType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLElement_get_text(self: *const T, p: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLElement.VTable, self.vtable).get_text(@ptrCast(*const IXMLElement, self), p);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLElement_put_text(self: *const T, p: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLElement.VTable, self.vtable).put_text(@ptrCast(*const IXMLElement, self), p);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLElement_addChild(self: *const T, pChildElem: ?*IXMLElement, lIndex: i32, lReserved: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLElement.VTable, self.vtable).addChild(@ptrCast(*const IXMLElement, self), pChildElem, lIndex, lReserved);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLElement_removeChild(self: *const T, pChildElem: ?*IXMLElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLElement.VTable, self.vtable).removeChild(@ptrCast(*const IXMLElement, self), pChildElem);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXMLElement2_Value = @import("../../zig.zig").Guid.initString("2b8de2ff-8d2d-11d1-b2fc-00c04fd915a9");
pub const IID_IXMLElement2 = &IID_IXMLElement2_Value;
pub const IXMLElement2 = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_tagName: fn(
self: *const IXMLElement2,
p: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_tagName: fn(
self: *const IXMLElement2,
p: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_parent: fn(
self: *const IXMLElement2,
ppParent: ?*?*IXMLElement2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
setAttribute: fn(
self: *const IXMLElement2,
strPropertyName: ?BSTR,
PropertyValue: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getAttribute: fn(
self: *const IXMLElement2,
strPropertyName: ?BSTR,
PropertyValue: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
removeAttribute: fn(
self: *const IXMLElement2,
strPropertyName: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_children: fn(
self: *const IXMLElement2,
pp: ?*?*IXMLElementCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_type: fn(
self: *const IXMLElement2,
plType: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_text: fn(
self: *const IXMLElement2,
p: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_text: fn(
self: *const IXMLElement2,
p: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
addChild: fn(
self: *const IXMLElement2,
pChildElem: ?*IXMLElement2,
lIndex: i32,
lReserved: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
removeChild: fn(
self: *const IXMLElement2,
pChildElem: ?*IXMLElement2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_attributes: fn(
self: *const IXMLElement2,
pp: ?*?*IXMLElementCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLElement2_get_tagName(self: *const T, p: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLElement2.VTable, self.vtable).get_tagName(@ptrCast(*const IXMLElement2, self), p);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLElement2_put_tagName(self: *const T, p: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLElement2.VTable, self.vtable).put_tagName(@ptrCast(*const IXMLElement2, self), p);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLElement2_get_parent(self: *const T, ppParent: ?*?*IXMLElement2) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLElement2.VTable, self.vtable).get_parent(@ptrCast(*const IXMLElement2, self), ppParent);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLElement2_setAttribute(self: *const T, strPropertyName: ?BSTR, PropertyValue: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLElement2.VTable, self.vtable).setAttribute(@ptrCast(*const IXMLElement2, self), strPropertyName, PropertyValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLElement2_getAttribute(self: *const T, strPropertyName: ?BSTR, PropertyValue: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLElement2.VTable, self.vtable).getAttribute(@ptrCast(*const IXMLElement2, self), strPropertyName, PropertyValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLElement2_removeAttribute(self: *const T, strPropertyName: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLElement2.VTable, self.vtable).removeAttribute(@ptrCast(*const IXMLElement2, self), strPropertyName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLElement2_get_children(self: *const T, pp: ?*?*IXMLElementCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLElement2.VTable, self.vtable).get_children(@ptrCast(*const IXMLElement2, self), pp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLElement2_get_type(self: *const T, plType: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLElement2.VTable, self.vtable).get_type(@ptrCast(*const IXMLElement2, self), plType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLElement2_get_text(self: *const T, p: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLElement2.VTable, self.vtable).get_text(@ptrCast(*const IXMLElement2, self), p);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLElement2_put_text(self: *const T, p: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLElement2.VTable, self.vtable).put_text(@ptrCast(*const IXMLElement2, self), p);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLElement2_addChild(self: *const T, pChildElem: ?*IXMLElement2, lIndex: i32, lReserved: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLElement2.VTable, self.vtable).addChild(@ptrCast(*const IXMLElement2, self), pChildElem, lIndex, lReserved);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLElement2_removeChild(self: *const T, pChildElem: ?*IXMLElement2) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLElement2.VTable, self.vtable).removeChild(@ptrCast(*const IXMLElement2, self), pChildElem);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLElement2_get_attributes(self: *const T, pp: ?*?*IXMLElementCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLElement2.VTable, self.vtable).get_attributes(@ptrCast(*const IXMLElement2, self), pp);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXMLAttribute_Value = @import("../../zig.zig").Guid.initString("d4d4a0fc-3b73-11d1-b2b4-00c04fb92596");
pub const IID_IXMLAttribute = &IID_IXMLAttribute_Value;
pub const IXMLAttribute = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_name: fn(
self: *const IXMLAttribute,
n: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_value: fn(
self: *const IXMLAttribute,
v: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLAttribute_get_name(self: *const T, n: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLAttribute.VTable, self.vtable).get_name(@ptrCast(*const IXMLAttribute, self), n);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLAttribute_get_value(self: *const T, v: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLAttribute.VTable, self.vtable).get_value(@ptrCast(*const IXMLAttribute, self), v);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXMLError_Value = @import("../../zig.zig").Guid.initString("948c5ad3-c58d-11d0-9c0b-00c04fc99c8e");
pub const IID_IXMLError = &IID_IXMLError_Value;
pub const IXMLError = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetErrorInfo: fn(
self: *const IXMLError,
pErrorReturn: ?*XML_ERROR,
) 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 IXMLError_GetErrorInfo(self: *const T, pErrorReturn: ?*XML_ERROR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLError.VTable, self.vtable).GetErrorInfo(@ptrCast(*const IXMLError, self), pErrorReturn);
}
};}
pub usingnamespace MethodMixin(@This());
};
const CLSID_DOMDocument60_Value = @import("../../zig.zig").Guid.initString("88d96a05-f192-11d4-a65f-0040963251e5");
pub const CLSID_DOMDocument60 = &CLSID_DOMDocument60_Value;
const CLSID_FreeThreadedDOMDocument60_Value = @import("../../zig.zig").Guid.initString("88d96a06-f192-11d4-a65f-0040963251e5");
pub const CLSID_FreeThreadedDOMDocument60 = &CLSID_FreeThreadedDOMDocument60_Value;
const CLSID_XMLSchemaCache60_Value = @import("../../zig.zig").Guid.initString("88d96a07-f192-11d4-a65f-0040963251e5");
pub const CLSID_XMLSchemaCache60 = &CLSID_XMLSchemaCache60_Value;
const CLSID_XSLTemplate60_Value = @import("../../zig.zig").Guid.initString("88d96a08-f192-11d4-a65f-0040963251e5");
pub const CLSID_XSLTemplate60 = &CLSID_XSLTemplate60_Value;
const CLSID_XMLHTTP60_Value = @import("../../zig.zig").Guid.initString("88d96a0a-f192-11d4-a65f-0040963251e5");
pub const CLSID_XMLHTTP60 = &CLSID_XMLHTTP60_Value;
const CLSID_FreeThreadedXMLHTTP60_Value = @import("../../zig.zig").Guid.initString("88d96a09-f192-11d4-a65f-0040963251e5");
pub const CLSID_FreeThreadedXMLHTTP60 = &CLSID_FreeThreadedXMLHTTP60_Value;
const CLSID_ServerXMLHTTP60_Value = @import("../../zig.zig").Guid.initString("88d96a0b-f192-11d4-a65f-0040963251e5");
pub const CLSID_ServerXMLHTTP60 = &CLSID_ServerXMLHTTP60_Value;
const CLSID_SAXXMLReader60_Value = @import("../../zig.zig").Guid.initString("88d96a0c-f192-11d4-a65f-0040963251e5");
pub const CLSID_SAXXMLReader60 = &CLSID_SAXXMLReader60_Value;
const CLSID_MXXMLWriter60_Value = @import("../../zig.zig").Guid.initString("88d96a0f-f192-11d4-a65f-0040963251e5");
pub const CLSID_MXXMLWriter60 = &CLSID_MXXMLWriter60_Value;
const CLSID_MXHTMLWriter60_Value = @import("../../zig.zig").Guid.initString("88d96a10-f192-11d4-a65f-0040963251e5");
pub const CLSID_MXHTMLWriter60 = &CLSID_MXHTMLWriter60_Value;
const CLSID_SAXAttributes60_Value = @import("../../zig.zig").Guid.initString("88d96a0e-f192-11d4-a65f-0040963251e5");
pub const CLSID_SAXAttributes60 = &CLSID_SAXAttributes60_Value;
const CLSID_MXNamespaceManager60_Value = @import("../../zig.zig").Guid.initString("88d96a11-f192-11d4-a65f-0040963251e5");
pub const CLSID_MXNamespaceManager60 = &CLSID_MXNamespaceManager60_Value;
const IID_IXMLDOMDocument2_Value = @import("../../zig.zig").Guid.initString("2933bf95-7b36-11d2-b20e-00c04f983e60");
pub const IID_IXMLDOMDocument2 = &IID_IXMLDOMDocument2_Value;
pub const IXMLDOMDocument2 = extern struct {
pub const VTable = extern struct {
base: IXMLDOMDocument.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_namespaces: fn(
self: *const IXMLDOMDocument2,
namespaceCollection: ?*?*IXMLDOMSchemaCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_schemas: fn(
self: *const IXMLDOMDocument2,
otherCollection: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
putref_schemas: fn(
self: *const IXMLDOMDocument2,
otherCollection: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
validate: fn(
self: *const IXMLDOMDocument2,
errorObj: ?*?*IXMLDOMParseError,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
setProperty: fn(
self: *const IXMLDOMDocument2,
name: ?BSTR,
value: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getProperty: fn(
self: *const IXMLDOMDocument2,
name: ?BSTR,
value: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IXMLDOMDocument.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument2_get_namespaces(self: *const T, namespaceCollection: ?*?*IXMLDOMSchemaCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument2.VTable, self.vtable).get_namespaces(@ptrCast(*const IXMLDOMDocument2, self), namespaceCollection);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument2_get_schemas(self: *const T, otherCollection: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument2.VTable, self.vtable).get_schemas(@ptrCast(*const IXMLDOMDocument2, self), otherCollection);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument2_putref_schemas(self: *const T, otherCollection: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument2.VTable, self.vtable).putref_schemas(@ptrCast(*const IXMLDOMDocument2, self), otherCollection);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument2_validate(self: *const T, errorObj: ?*?*IXMLDOMParseError) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument2.VTable, self.vtable).validate(@ptrCast(*const IXMLDOMDocument2, self), errorObj);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument2_setProperty(self: *const T, name: ?BSTR, value: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument2.VTable, self.vtable).setProperty(@ptrCast(*const IXMLDOMDocument2, self), name, value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument2_getProperty(self: *const T, name: ?BSTR, value: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument2.VTable, self.vtable).getProperty(@ptrCast(*const IXMLDOMDocument2, self), name, value);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXMLDOMDocument3_Value = @import("../../zig.zig").Guid.initString("2933bf96-7b36-11d2-b20e-00c04f983e60");
pub const IID_IXMLDOMDocument3 = &IID_IXMLDOMDocument3_Value;
pub const IXMLDOMDocument3 = extern struct {
pub const VTable = extern struct {
base: IXMLDOMDocument2.VTable,
validateNode: fn(
self: *const IXMLDOMDocument3,
node: ?*IXMLDOMNode,
errorObj: ?*?*IXMLDOMParseError,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
importNode: fn(
self: *const IXMLDOMDocument3,
node: ?*IXMLDOMNode,
deep: i16,
clone: ?*?*IXMLDOMNode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IXMLDOMDocument2.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument3_validateNode(self: *const T, node: ?*IXMLDOMNode, errorObj: ?*?*IXMLDOMParseError) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument3.VTable, self.vtable).validateNode(@ptrCast(*const IXMLDOMDocument3, self), node, errorObj);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMDocument3_importNode(self: *const T, node: ?*IXMLDOMNode, deep: i16, clone: ?*?*IXMLDOMNode) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMDocument3.VTable, self.vtable).importNode(@ptrCast(*const IXMLDOMDocument3, self), node, deep, clone);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXMLDOMSchemaCollection_Value = @import("../../zig.zig").Guid.initString("373984c8-b845-449b-91e7-45ac83036ade");
pub const IID_IXMLDOMSchemaCollection = &IID_IXMLDOMSchemaCollection_Value;
pub const IXMLDOMSchemaCollection = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
add: fn(
self: *const IXMLDOMSchemaCollection,
namespaceURI: ?BSTR,
@"var": VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
get: fn(
self: *const IXMLDOMSchemaCollection,
namespaceURI: ?BSTR,
schemaNode: ?*?*IXMLDOMNode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
remove: fn(
self: *const IXMLDOMSchemaCollection,
namespaceURI: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_length: fn(
self: *const IXMLDOMSchemaCollection,
length: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_namespaceURI: fn(
self: *const IXMLDOMSchemaCollection,
index: i32,
length: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
addCollection: fn(
self: *const IXMLDOMSchemaCollection,
otherCollection: ?*IXMLDOMSchemaCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get__newEnum: fn(
self: *const IXMLDOMSchemaCollection,
ppUnk: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMSchemaCollection_add(self: *const T, namespaceURI: ?BSTR, @"var": VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMSchemaCollection.VTable, self.vtable).add(@ptrCast(*const IXMLDOMSchemaCollection, self), namespaceURI, @"var");
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMSchemaCollection_get(self: *const T, namespaceURI: ?BSTR, schemaNode: ?*?*IXMLDOMNode) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMSchemaCollection.VTable, self.vtable).get(@ptrCast(*const IXMLDOMSchemaCollection, self), namespaceURI, schemaNode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMSchemaCollection_remove(self: *const T, namespaceURI: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMSchemaCollection.VTable, self.vtable).remove(@ptrCast(*const IXMLDOMSchemaCollection, self), namespaceURI);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMSchemaCollection_get_length(self: *const T, length: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMSchemaCollection.VTable, self.vtable).get_length(@ptrCast(*const IXMLDOMSchemaCollection, self), length);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMSchemaCollection_get_namespaceURI(self: *const T, index: i32, length: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMSchemaCollection.VTable, self.vtable).get_namespaceURI(@ptrCast(*const IXMLDOMSchemaCollection, self), index, length);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMSchemaCollection_addCollection(self: *const T, otherCollection: ?*IXMLDOMSchemaCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMSchemaCollection.VTable, self.vtable).addCollection(@ptrCast(*const IXMLDOMSchemaCollection, self), otherCollection);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMSchemaCollection_get__newEnum(self: *const T, ppUnk: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMSchemaCollection.VTable, self.vtable).get__newEnum(@ptrCast(*const IXMLDOMSchemaCollection, self), ppUnk);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXMLDOMSelection_Value = @import("../../zig.zig").Guid.initString("aa634fc7-5888-44a7-a257-3a47150d3a0e");
pub const IID_IXMLDOMSelection = &IID_IXMLDOMSelection_Value;
pub const IXMLDOMSelection = extern struct {
pub const VTable = extern struct {
base: IXMLDOMNodeList.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_expr: fn(
self: *const IXMLDOMSelection,
expression: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_expr: fn(
self: *const IXMLDOMSelection,
expression: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_context: fn(
self: *const IXMLDOMSelection,
ppNode: ?*?*IXMLDOMNode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
putref_context: fn(
self: *const IXMLDOMSelection,
pNode: ?*IXMLDOMNode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
peekNode: fn(
self: *const IXMLDOMSelection,
ppNode: ?*?*IXMLDOMNode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
matches: fn(
self: *const IXMLDOMSelection,
pNode: ?*IXMLDOMNode,
ppNode: ?*?*IXMLDOMNode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
removeNext: fn(
self: *const IXMLDOMSelection,
ppNode: ?*?*IXMLDOMNode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
removeAll: fn(
self: *const IXMLDOMSelection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
clone: fn(
self: *const IXMLDOMSelection,
ppNode: ?*?*IXMLDOMSelection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getProperty: fn(
self: *const IXMLDOMSelection,
name: ?BSTR,
value: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
setProperty: fn(
self: *const IXMLDOMSelection,
name: ?BSTR,
value: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IXMLDOMNodeList.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMSelection_get_expr(self: *const T, expression: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMSelection.VTable, self.vtable).get_expr(@ptrCast(*const IXMLDOMSelection, self), expression);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMSelection_put_expr(self: *const T, expression: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMSelection.VTable, self.vtable).put_expr(@ptrCast(*const IXMLDOMSelection, self), expression);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMSelection_get_context(self: *const T, ppNode: ?*?*IXMLDOMNode) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMSelection.VTable, self.vtable).get_context(@ptrCast(*const IXMLDOMSelection, self), ppNode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMSelection_putref_context(self: *const T, pNode: ?*IXMLDOMNode) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMSelection.VTable, self.vtable).putref_context(@ptrCast(*const IXMLDOMSelection, self), pNode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMSelection_peekNode(self: *const T, ppNode: ?*?*IXMLDOMNode) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMSelection.VTable, self.vtable).peekNode(@ptrCast(*const IXMLDOMSelection, self), ppNode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMSelection_matches(self: *const T, pNode: ?*IXMLDOMNode, ppNode: ?*?*IXMLDOMNode) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMSelection.VTable, self.vtable).matches(@ptrCast(*const IXMLDOMSelection, self), pNode, ppNode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMSelection_removeNext(self: *const T, ppNode: ?*?*IXMLDOMNode) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMSelection.VTable, self.vtable).removeNext(@ptrCast(*const IXMLDOMSelection, self), ppNode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMSelection_removeAll(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMSelection.VTable, self.vtable).removeAll(@ptrCast(*const IXMLDOMSelection, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMSelection_clone(self: *const T, ppNode: ?*?*IXMLDOMSelection) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMSelection.VTable, self.vtable).clone(@ptrCast(*const IXMLDOMSelection, self), ppNode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMSelection_getProperty(self: *const T, name: ?BSTR, value: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMSelection.VTable, self.vtable).getProperty(@ptrCast(*const IXMLDOMSelection, self), name, value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMSelection_setProperty(self: *const T, name: ?BSTR, value: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMSelection.VTable, self.vtable).setProperty(@ptrCast(*const IXMLDOMSelection, self), name, value);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXMLDOMParseError2_Value = @import("../../zig.zig").Guid.initString("3efaa428-272f-11d2-836f-0000f87a7782");
pub const IID_IXMLDOMParseError2 = &IID_IXMLDOMParseError2_Value;
pub const IXMLDOMParseError2 = extern struct {
pub const VTable = extern struct {
base: IXMLDOMParseError.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_errorXPath: fn(
self: *const IXMLDOMParseError2,
xpathexpr: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_allErrors: fn(
self: *const IXMLDOMParseError2,
allErrors: ?*?*IXMLDOMParseErrorCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
errorParameters: fn(
self: *const IXMLDOMParseError2,
index: i32,
param1: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_errorParametersCount: fn(
self: *const IXMLDOMParseError2,
count: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IXMLDOMParseError.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMParseError2_get_errorXPath(self: *const T, xpathexpr: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMParseError2.VTable, self.vtable).get_errorXPath(@ptrCast(*const IXMLDOMParseError2, self), xpathexpr);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMParseError2_get_allErrors(self: *const T, allErrors: ?*?*IXMLDOMParseErrorCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMParseError2.VTable, self.vtable).get_allErrors(@ptrCast(*const IXMLDOMParseError2, self), allErrors);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMParseError2_errorParameters(self: *const T, index: i32, param1: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMParseError2.VTable, self.vtable).errorParameters(@ptrCast(*const IXMLDOMParseError2, self), index, param1);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMParseError2_get_errorParametersCount(self: *const T, count: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMParseError2.VTable, self.vtable).get_errorParametersCount(@ptrCast(*const IXMLDOMParseError2, self), count);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXMLDOMParseErrorCollection_Value = @import("../../zig.zig").Guid.initString("3efaa429-272f-11d2-836f-0000f87a7782");
pub const IID_IXMLDOMParseErrorCollection = &IID_IXMLDOMParseErrorCollection_Value;
pub const IXMLDOMParseErrorCollection = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_item: fn(
self: *const IXMLDOMParseErrorCollection,
index: i32,
@"error": ?*?*IXMLDOMParseError2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_length: fn(
self: *const IXMLDOMParseErrorCollection,
length: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_next: fn(
self: *const IXMLDOMParseErrorCollection,
@"error": ?*?*IXMLDOMParseError2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
reset: fn(
self: *const IXMLDOMParseErrorCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get__newEnum: fn(
self: *const IXMLDOMParseErrorCollection,
ppunk: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMParseErrorCollection_get_item(self: *const T, index: i32, @"error": ?*?*IXMLDOMParseError2) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMParseErrorCollection.VTable, self.vtable).get_item(@ptrCast(*const IXMLDOMParseErrorCollection, self), index, @"error");
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMParseErrorCollection_get_length(self: *const T, length: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMParseErrorCollection.VTable, self.vtable).get_length(@ptrCast(*const IXMLDOMParseErrorCollection, self), length);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMParseErrorCollection_get_next(self: *const T, @"error": ?*?*IXMLDOMParseError2) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMParseErrorCollection.VTable, self.vtable).get_next(@ptrCast(*const IXMLDOMParseErrorCollection, self), @"error");
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMParseErrorCollection_reset(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMParseErrorCollection.VTable, self.vtable).reset(@ptrCast(*const IXMLDOMParseErrorCollection, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMParseErrorCollection_get__newEnum(self: *const T, ppunk: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMParseErrorCollection.VTable, self.vtable).get__newEnum(@ptrCast(*const IXMLDOMParseErrorCollection, self), ppunk);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXSLProcessor_Value = @import("../../zig.zig").Guid.initString("2933bf92-7b36-11d2-b20e-00c04f983e60");
pub const IID_IXSLProcessor = &IID_IXSLProcessor_Value;
pub const IXSLProcessor = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_input: fn(
self: *const IXSLProcessor,
@"var": VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_input: fn(
self: *const IXSLProcessor,
pVar: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ownerTemplate: fn(
self: *const IXSLProcessor,
ppTemplate: ?*?*IXSLTemplate,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
setStartMode: fn(
self: *const IXSLProcessor,
mode: ?BSTR,
namespaceURI: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_startMode: fn(
self: *const IXSLProcessor,
mode: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_startModeURI: fn(
self: *const IXSLProcessor,
namespaceURI: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_output: fn(
self: *const IXSLProcessor,
output: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_output: fn(
self: *const IXSLProcessor,
pOutput: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
transform: fn(
self: *const IXSLProcessor,
pDone: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
reset: fn(
self: *const IXSLProcessor,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_readyState: fn(
self: *const IXSLProcessor,
pReadyState: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
addParameter: fn(
self: *const IXSLProcessor,
baseName: ?BSTR,
parameter: VARIANT,
namespaceURI: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
addObject: fn(
self: *const IXSLProcessor,
obj: ?*IDispatch,
namespaceURI: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_stylesheet: fn(
self: *const IXSLProcessor,
stylesheet: ?*?*IXMLDOMNode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXSLProcessor_put_input(self: *const T, @"var": VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXSLProcessor.VTable, self.vtable).put_input(@ptrCast(*const IXSLProcessor, self), @"var");
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXSLProcessor_get_input(self: *const T, pVar: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXSLProcessor.VTable, self.vtable).get_input(@ptrCast(*const IXSLProcessor, self), pVar);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXSLProcessor_get_ownerTemplate(self: *const T, ppTemplate: ?*?*IXSLTemplate) callconv(.Inline) HRESULT {
return @ptrCast(*const IXSLProcessor.VTable, self.vtable).get_ownerTemplate(@ptrCast(*const IXSLProcessor, self), ppTemplate);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXSLProcessor_setStartMode(self: *const T, mode: ?BSTR, namespaceURI: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXSLProcessor.VTable, self.vtable).setStartMode(@ptrCast(*const IXSLProcessor, self), mode, namespaceURI);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXSLProcessor_get_startMode(self: *const T, mode: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXSLProcessor.VTable, self.vtable).get_startMode(@ptrCast(*const IXSLProcessor, self), mode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXSLProcessor_get_startModeURI(self: *const T, namespaceURI: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXSLProcessor.VTable, self.vtable).get_startModeURI(@ptrCast(*const IXSLProcessor, self), namespaceURI);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXSLProcessor_put_output(self: *const T, output: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXSLProcessor.VTable, self.vtable).put_output(@ptrCast(*const IXSLProcessor, self), output);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXSLProcessor_get_output(self: *const T, pOutput: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXSLProcessor.VTable, self.vtable).get_output(@ptrCast(*const IXSLProcessor, self), pOutput);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXSLProcessor_transform(self: *const T, pDone: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXSLProcessor.VTable, self.vtable).transform(@ptrCast(*const IXSLProcessor, self), pDone);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXSLProcessor_reset(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXSLProcessor.VTable, self.vtable).reset(@ptrCast(*const IXSLProcessor, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXSLProcessor_get_readyState(self: *const T, pReadyState: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXSLProcessor.VTable, self.vtable).get_readyState(@ptrCast(*const IXSLProcessor, self), pReadyState);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXSLProcessor_addParameter(self: *const T, baseName: ?BSTR, parameter: VARIANT, namespaceURI: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXSLProcessor.VTable, self.vtable).addParameter(@ptrCast(*const IXSLProcessor, self), baseName, parameter, namespaceURI);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXSLProcessor_addObject(self: *const T, obj: ?*IDispatch, namespaceURI: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXSLProcessor.VTable, self.vtable).addObject(@ptrCast(*const IXSLProcessor, self), obj, namespaceURI);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXSLProcessor_get_stylesheet(self: *const T, stylesheet: ?*?*IXMLDOMNode) callconv(.Inline) HRESULT {
return @ptrCast(*const IXSLProcessor.VTable, self.vtable).get_stylesheet(@ptrCast(*const IXSLProcessor, self), stylesheet);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXSLTemplate_Value = @import("../../zig.zig").Guid.initString("2933bf93-7b36-11d2-b20e-00c04f983e60");
pub const IID_IXSLTemplate = &IID_IXSLTemplate_Value;
pub const IXSLTemplate = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
putref_stylesheet: fn(
self: *const IXSLTemplate,
stylesheet: ?*IXMLDOMNode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_stylesheet: fn(
self: *const IXSLTemplate,
stylesheet: ?*?*IXMLDOMNode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
createProcessor: fn(
self: *const IXSLTemplate,
ppProcessor: ?*?*IXSLProcessor,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXSLTemplate_putref_stylesheet(self: *const T, stylesheet: ?*IXMLDOMNode) callconv(.Inline) HRESULT {
return @ptrCast(*const IXSLTemplate.VTable, self.vtable).putref_stylesheet(@ptrCast(*const IXSLTemplate, self), stylesheet);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXSLTemplate_get_stylesheet(self: *const T, stylesheet: ?*?*IXMLDOMNode) callconv(.Inline) HRESULT {
return @ptrCast(*const IXSLTemplate.VTable, self.vtable).get_stylesheet(@ptrCast(*const IXSLTemplate, self), stylesheet);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXSLTemplate_createProcessor(self: *const T, ppProcessor: ?*?*IXSLProcessor) callconv(.Inline) HRESULT {
return @ptrCast(*const IXSLTemplate.VTable, self.vtable).createProcessor(@ptrCast(*const IXSLTemplate, self), ppProcessor);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXMLHTTPRequest_Value = @import("../../zig.zig").Guid.initString("ed8c108d-4349-11d2-91a4-00c04f7969e8");
pub const IID_IXMLHTTPRequest = &IID_IXMLHTTPRequest_Value;
pub const IXMLHTTPRequest = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
open: fn(
self: *const IXMLHTTPRequest,
bstrMethod: ?BSTR,
bstrUrl: ?BSTR,
varAsync: VARIANT,
bstrUser: VARIANT,
bstrPassword: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
setRequestHeader: fn(
self: *const IXMLHTTPRequest,
bstrHeader: ?BSTR,
bstrValue: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getResponseHeader: fn(
self: *const IXMLHTTPRequest,
bstrHeader: ?BSTR,
pbstrValue: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getAllResponseHeaders: fn(
self: *const IXMLHTTPRequest,
pbstrHeaders: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
send: fn(
self: *const IXMLHTTPRequest,
varBody: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
abort: fn(
self: *const IXMLHTTPRequest,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_status: fn(
self: *const IXMLHTTPRequest,
plStatus: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_statusText: fn(
self: *const IXMLHTTPRequest,
pbstrStatus: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_responseXML: fn(
self: *const IXMLHTTPRequest,
ppBody: ?*?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_responseText: fn(
self: *const IXMLHTTPRequest,
pbstrBody: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_responseBody: fn(
self: *const IXMLHTTPRequest,
pvarBody: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_responseStream: fn(
self: *const IXMLHTTPRequest,
pvarBody: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_readyState: fn(
self: *const IXMLHTTPRequest,
plState: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_onreadystatechange: fn(
self: *const IXMLHTTPRequest,
pReadyStateSink: ?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHTTPRequest_open(self: *const T, bstrMethod: ?BSTR, bstrUrl: ?BSTR, varAsync: VARIANT, bstrUser: VARIANT, bstrPassword: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHTTPRequest.VTable, self.vtable).open(@ptrCast(*const IXMLHTTPRequest, self), bstrMethod, bstrUrl, varAsync, bstrUser, bstrPassword);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHTTPRequest_setRequestHeader(self: *const T, bstrHeader: ?BSTR, bstrValue: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHTTPRequest.VTable, self.vtable).setRequestHeader(@ptrCast(*const IXMLHTTPRequest, self), bstrHeader, bstrValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHTTPRequest_getResponseHeader(self: *const T, bstrHeader: ?BSTR, pbstrValue: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHTTPRequest.VTable, self.vtable).getResponseHeader(@ptrCast(*const IXMLHTTPRequest, self), bstrHeader, pbstrValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHTTPRequest_getAllResponseHeaders(self: *const T, pbstrHeaders: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHTTPRequest.VTable, self.vtable).getAllResponseHeaders(@ptrCast(*const IXMLHTTPRequest, self), pbstrHeaders);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHTTPRequest_send(self: *const T, varBody: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHTTPRequest.VTable, self.vtable).send(@ptrCast(*const IXMLHTTPRequest, self), varBody);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHTTPRequest_abort(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHTTPRequest.VTable, self.vtable).abort(@ptrCast(*const IXMLHTTPRequest, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHTTPRequest_get_status(self: *const T, plStatus: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHTTPRequest.VTable, self.vtable).get_status(@ptrCast(*const IXMLHTTPRequest, self), plStatus);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHTTPRequest_get_statusText(self: *const T, pbstrStatus: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHTTPRequest.VTable, self.vtable).get_statusText(@ptrCast(*const IXMLHTTPRequest, self), pbstrStatus);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHTTPRequest_get_responseXML(self: *const T, ppBody: ?*?*IDispatch) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHTTPRequest.VTable, self.vtable).get_responseXML(@ptrCast(*const IXMLHTTPRequest, self), ppBody);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHTTPRequest_get_responseText(self: *const T, pbstrBody: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHTTPRequest.VTable, self.vtable).get_responseText(@ptrCast(*const IXMLHTTPRequest, self), pbstrBody);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHTTPRequest_get_responseBody(self: *const T, pvarBody: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHTTPRequest.VTable, self.vtable).get_responseBody(@ptrCast(*const IXMLHTTPRequest, self), pvarBody);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHTTPRequest_get_responseStream(self: *const T, pvarBody: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHTTPRequest.VTable, self.vtable).get_responseStream(@ptrCast(*const IXMLHTTPRequest, self), pvarBody);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHTTPRequest_get_readyState(self: *const T, plState: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHTTPRequest.VTable, self.vtable).get_readyState(@ptrCast(*const IXMLHTTPRequest, self), plState);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHTTPRequest_put_onreadystatechange(self: *const T, pReadyStateSink: ?*IDispatch) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHTTPRequest.VTable, self.vtable).put_onreadystatechange(@ptrCast(*const IXMLHTTPRequest, self), pReadyStateSink);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const SERVERXMLHTTP_OPTION = enum(i32) {
URL = -1,
URL_CODEPAGE = 0,
ESCAPE_PERCENT_IN_URL = 1,
IGNORE_SERVER_SSL_CERT_ERROR_FLAGS = 2,
SELECT_CLIENT_SSL_CERT = 3,
};
pub const SXH_OPTION_URL = SERVERXMLHTTP_OPTION.URL;
pub const SXH_OPTION_URL_CODEPAGE = SERVERXMLHTTP_OPTION.URL_CODEPAGE;
pub const SXH_OPTION_ESCAPE_PERCENT_IN_URL = SERVERXMLHTTP_OPTION.ESCAPE_PERCENT_IN_URL;
pub const SXH_OPTION_IGNORE_SERVER_SSL_CERT_ERROR_FLAGS = SERVERXMLHTTP_OPTION.IGNORE_SERVER_SSL_CERT_ERROR_FLAGS;
pub const SXH_OPTION_SELECT_CLIENT_SSL_CERT = SERVERXMLHTTP_OPTION.SELECT_CLIENT_SSL_CERT;
pub const SXH_SERVER_CERT_OPTION = enum(i32) {
UNKNOWN_CA = 256,
WRONG_USAGE = 512,
CERT_CN_INVALID = 4096,
CERT_DATE_INVALID = 8192,
ALL_SERVER_ERRORS = 13056,
};
pub const SXH_SERVER_CERT_IGNORE_UNKNOWN_CA = SXH_SERVER_CERT_OPTION.UNKNOWN_CA;
pub const SXH_SERVER_CERT_IGNORE_WRONG_USAGE = SXH_SERVER_CERT_OPTION.WRONG_USAGE;
pub const SXH_SERVER_CERT_IGNORE_CERT_CN_INVALID = SXH_SERVER_CERT_OPTION.CERT_CN_INVALID;
pub const SXH_SERVER_CERT_IGNORE_CERT_DATE_INVALID = SXH_SERVER_CERT_OPTION.CERT_DATE_INVALID;
pub const SXH_SERVER_CERT_IGNORE_ALL_SERVER_ERRORS = SXH_SERVER_CERT_OPTION.ALL_SERVER_ERRORS;
pub const SXH_PROXY_SETTING = enum(i32) {
DEFAULT = 0,
// PRECONFIG = 0, this enum value conflicts with DEFAULT
DIRECT = 1,
PROXY = 2,
};
pub const SXH_PROXY_SET_DEFAULT = SXH_PROXY_SETTING.DEFAULT;
pub const SXH_PROXY_SET_PRECONFIG = SXH_PROXY_SETTING.DEFAULT;
pub const SXH_PROXY_SET_DIRECT = SXH_PROXY_SETTING.DIRECT;
pub const SXH_PROXY_SET_PROXY = SXH_PROXY_SETTING.PROXY;
const IID_IServerXMLHTTPRequest_Value = @import("../../zig.zig").Guid.initString("2e9196bf-13ba-4dd4-91ca-6c571f281495");
pub const IID_IServerXMLHTTPRequest = &IID_IServerXMLHTTPRequest_Value;
pub const IServerXMLHTTPRequest = extern struct {
pub const VTable = extern struct {
base: IXMLHTTPRequest.VTable,
setTimeouts: fn(
self: *const IServerXMLHTTPRequest,
resolveTimeout: i32,
connectTimeout: i32,
sendTimeout: i32,
receiveTimeout: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
waitForResponse: fn(
self: *const IServerXMLHTTPRequest,
timeoutInSeconds: VARIANT,
isSuccessful: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getOption: fn(
self: *const IServerXMLHTTPRequest,
option: SERVERXMLHTTP_OPTION,
value: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
setOption: fn(
self: *const IServerXMLHTTPRequest,
option: SERVERXMLHTTP_OPTION,
value: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IXMLHTTPRequest.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IServerXMLHTTPRequest_setTimeouts(self: *const T, resolveTimeout: i32, connectTimeout: i32, sendTimeout: i32, receiveTimeout: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IServerXMLHTTPRequest.VTable, self.vtable).setTimeouts(@ptrCast(*const IServerXMLHTTPRequest, self), resolveTimeout, connectTimeout, sendTimeout, receiveTimeout);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IServerXMLHTTPRequest_waitForResponse(self: *const T, timeoutInSeconds: VARIANT, isSuccessful: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IServerXMLHTTPRequest.VTable, self.vtable).waitForResponse(@ptrCast(*const IServerXMLHTTPRequest, self), timeoutInSeconds, isSuccessful);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IServerXMLHTTPRequest_getOption(self: *const T, option: SERVERXMLHTTP_OPTION, value: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IServerXMLHTTPRequest.VTable, self.vtable).getOption(@ptrCast(*const IServerXMLHTTPRequest, self), option, value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IServerXMLHTTPRequest_setOption(self: *const T, option: SERVERXMLHTTP_OPTION, value: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IServerXMLHTTPRequest.VTable, self.vtable).setOption(@ptrCast(*const IServerXMLHTTPRequest, self), option, value);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IServerXMLHTTPRequest2_Value = @import("../../zig.zig").Guid.initString("2e01311b-c322-4b0a-bd77-b90cfdc8dce7");
pub const IID_IServerXMLHTTPRequest2 = &IID_IServerXMLHTTPRequest2_Value;
pub const IServerXMLHTTPRequest2 = extern struct {
pub const VTable = extern struct {
base: IServerXMLHTTPRequest.VTable,
setProxy: fn(
self: *const IServerXMLHTTPRequest2,
proxySetting: SXH_PROXY_SETTING,
varProxyServer: VARIANT,
varBypassList: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
setProxyCredentials: fn(
self: *const IServerXMLHTTPRequest2,
bstrUserName: ?BSTR,
bstrPassword: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IServerXMLHTTPRequest.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IServerXMLHTTPRequest2_setProxy(self: *const T, proxySetting: SXH_PROXY_SETTING, varProxyServer: VARIANT, varBypassList: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IServerXMLHTTPRequest2.VTable, self.vtable).setProxy(@ptrCast(*const IServerXMLHTTPRequest2, self), proxySetting, varProxyServer, varBypassList);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IServerXMLHTTPRequest2_setProxyCredentials(self: *const T, bstrUserName: ?BSTR, bstrPassword: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IServerXMLHTTPRequest2.VTable, self.vtable).setProxyCredentials(@ptrCast(*const IServerXMLHTTPRequest2, self), bstrUserName, bstrPassword);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ISAXXMLReader_Value = @import("../../zig.zig").Guid.initString("a4f96ed0-f829-476e-81c0-cdc7bd2a0802");
pub const IID_ISAXXMLReader = &IID_ISAXXMLReader_Value;
pub const ISAXXMLReader = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
getFeature: fn(
self: *const ISAXXMLReader,
pwchName: ?[*:0]const u16,
pvfValue: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
putFeature: fn(
self: *const ISAXXMLReader,
pwchName: ?[*:0]const u16,
vfValue: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getProperty: fn(
self: *const ISAXXMLReader,
pwchName: ?[*:0]const u16,
pvarValue: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
putProperty: fn(
self: *const ISAXXMLReader,
pwchName: ?[*:0]const u16,
varValue: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getEntityResolver: fn(
self: *const ISAXXMLReader,
ppResolver: ?*?*ISAXEntityResolver,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
putEntityResolver: fn(
self: *const ISAXXMLReader,
pResolver: ?*ISAXEntityResolver,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getContentHandler: fn(
self: *const ISAXXMLReader,
ppHandler: ?*?*ISAXContentHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
putContentHandler: fn(
self: *const ISAXXMLReader,
pHandler: ?*ISAXContentHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getDTDHandler: fn(
self: *const ISAXXMLReader,
ppHandler: ?*?*ISAXDTDHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
putDTDHandler: fn(
self: *const ISAXXMLReader,
pHandler: ?*ISAXDTDHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getErrorHandler: fn(
self: *const ISAXXMLReader,
ppHandler: ?*?*ISAXErrorHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
putErrorHandler: fn(
self: *const ISAXXMLReader,
pHandler: ?*ISAXErrorHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getBaseURL: fn(
self: *const ISAXXMLReader,
ppwchBaseUrl: ?*const ?*u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
putBaseURL: fn(
self: *const ISAXXMLReader,
pwchBaseUrl: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getSecureBaseURL: fn(
self: *const ISAXXMLReader,
ppwchSecureBaseUrl: ?*const ?*u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
putSecureBaseURL: fn(
self: *const ISAXXMLReader,
pwchSecureBaseUrl: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
parse: fn(
self: *const ISAXXMLReader,
varInput: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
parseURL: fn(
self: *const ISAXXMLReader,
pwchUrl: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXXMLReader_getFeature(self: *const T, pwchName: ?[*:0]const u16, pvfValue: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXXMLReader.VTable, self.vtable).getFeature(@ptrCast(*const ISAXXMLReader, self), pwchName, pvfValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXXMLReader_putFeature(self: *const T, pwchName: ?[*:0]const u16, vfValue: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXXMLReader.VTable, self.vtable).putFeature(@ptrCast(*const ISAXXMLReader, self), pwchName, vfValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXXMLReader_getProperty(self: *const T, pwchName: ?[*:0]const u16, pvarValue: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXXMLReader.VTable, self.vtable).getProperty(@ptrCast(*const ISAXXMLReader, self), pwchName, pvarValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXXMLReader_putProperty(self: *const T, pwchName: ?[*:0]const u16, varValue: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXXMLReader.VTable, self.vtable).putProperty(@ptrCast(*const ISAXXMLReader, self), pwchName, varValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXXMLReader_getEntityResolver(self: *const T, ppResolver: ?*?*ISAXEntityResolver) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXXMLReader.VTable, self.vtable).getEntityResolver(@ptrCast(*const ISAXXMLReader, self), ppResolver);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXXMLReader_putEntityResolver(self: *const T, pResolver: ?*ISAXEntityResolver) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXXMLReader.VTable, self.vtable).putEntityResolver(@ptrCast(*const ISAXXMLReader, self), pResolver);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXXMLReader_getContentHandler(self: *const T, ppHandler: ?*?*ISAXContentHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXXMLReader.VTable, self.vtable).getContentHandler(@ptrCast(*const ISAXXMLReader, self), ppHandler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXXMLReader_putContentHandler(self: *const T, pHandler: ?*ISAXContentHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXXMLReader.VTable, self.vtable).putContentHandler(@ptrCast(*const ISAXXMLReader, self), pHandler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXXMLReader_getDTDHandler(self: *const T, ppHandler: ?*?*ISAXDTDHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXXMLReader.VTable, self.vtable).getDTDHandler(@ptrCast(*const ISAXXMLReader, self), ppHandler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXXMLReader_putDTDHandler(self: *const T, pHandler: ?*ISAXDTDHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXXMLReader.VTable, self.vtable).putDTDHandler(@ptrCast(*const ISAXXMLReader, self), pHandler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXXMLReader_getErrorHandler(self: *const T, ppHandler: ?*?*ISAXErrorHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXXMLReader.VTable, self.vtable).getErrorHandler(@ptrCast(*const ISAXXMLReader, self), ppHandler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXXMLReader_putErrorHandler(self: *const T, pHandler: ?*ISAXErrorHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXXMLReader.VTable, self.vtable).putErrorHandler(@ptrCast(*const ISAXXMLReader, self), pHandler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXXMLReader_getBaseURL(self: *const T, ppwchBaseUrl: ?*const ?*u16) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXXMLReader.VTable, self.vtable).getBaseURL(@ptrCast(*const ISAXXMLReader, self), ppwchBaseUrl);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXXMLReader_putBaseURL(self: *const T, pwchBaseUrl: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXXMLReader.VTable, self.vtable).putBaseURL(@ptrCast(*const ISAXXMLReader, self), pwchBaseUrl);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXXMLReader_getSecureBaseURL(self: *const T, ppwchSecureBaseUrl: ?*const ?*u16) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXXMLReader.VTable, self.vtable).getSecureBaseURL(@ptrCast(*const ISAXXMLReader, self), ppwchSecureBaseUrl);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXXMLReader_putSecureBaseURL(self: *const T, pwchSecureBaseUrl: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXXMLReader.VTable, self.vtable).putSecureBaseURL(@ptrCast(*const ISAXXMLReader, self), pwchSecureBaseUrl);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXXMLReader_parse(self: *const T, varInput: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXXMLReader.VTable, self.vtable).parse(@ptrCast(*const ISAXXMLReader, self), varInput);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXXMLReader_parseURL(self: *const T, pwchUrl: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXXMLReader.VTable, self.vtable).parseURL(@ptrCast(*const ISAXXMLReader, self), pwchUrl);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ISAXXMLFilter_Value = @import("../../zig.zig").Guid.initString("70409222-ca09-4475-acb8-40312fe8d145");
pub const IID_ISAXXMLFilter = &IID_ISAXXMLFilter_Value;
pub const ISAXXMLFilter = extern struct {
pub const VTable = extern struct {
base: ISAXXMLReader.VTable,
getParent: fn(
self: *const ISAXXMLFilter,
ppReader: ?*?*ISAXXMLReader,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
putParent: fn(
self: *const ISAXXMLFilter,
pReader: ?*ISAXXMLReader,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace ISAXXMLReader.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXXMLFilter_getParent(self: *const T, ppReader: ?*?*ISAXXMLReader) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXXMLFilter.VTable, self.vtable).getParent(@ptrCast(*const ISAXXMLFilter, self), ppReader);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXXMLFilter_putParent(self: *const T, pReader: ?*ISAXXMLReader) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXXMLFilter.VTable, self.vtable).putParent(@ptrCast(*const ISAXXMLFilter, self), pReader);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ISAXLocator_Value = @import("../../zig.zig").Guid.initString("9b7e472a-0de4-4640-bff3-84d38a051c31");
pub const IID_ISAXLocator = &IID_ISAXLocator_Value;
pub const ISAXLocator = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
getColumnNumber: fn(
self: *const ISAXLocator,
pnColumn: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getLineNumber: fn(
self: *const ISAXLocator,
pnLine: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getPublicId: fn(
self: *const ISAXLocator,
ppwchPublicId: ?*const ?*u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getSystemId: fn(
self: *const ISAXLocator,
ppwchSystemId: ?*const ?*u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXLocator_getColumnNumber(self: *const T, pnColumn: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXLocator.VTable, self.vtable).getColumnNumber(@ptrCast(*const ISAXLocator, self), pnColumn);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXLocator_getLineNumber(self: *const T, pnLine: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXLocator.VTable, self.vtable).getLineNumber(@ptrCast(*const ISAXLocator, self), pnLine);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXLocator_getPublicId(self: *const T, ppwchPublicId: ?*const ?*u16) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXLocator.VTable, self.vtable).getPublicId(@ptrCast(*const ISAXLocator, self), ppwchPublicId);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXLocator_getSystemId(self: *const T, ppwchSystemId: ?*const ?*u16) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXLocator.VTable, self.vtable).getSystemId(@ptrCast(*const ISAXLocator, self), ppwchSystemId);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ISAXEntityResolver_Value = @import("../../zig.zig").Guid.initString("99bca7bd-e8c4-4d5f-a0cf-6d907901ff07");
pub const IID_ISAXEntityResolver = &IID_ISAXEntityResolver_Value;
pub const ISAXEntityResolver = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
resolveEntity: fn(
self: *const ISAXEntityResolver,
pwchPublicId: ?[*:0]const u16,
pwchSystemId: ?[*:0]const u16,
pvarInput: ?*VARIANT,
) 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 ISAXEntityResolver_resolveEntity(self: *const T, pwchPublicId: ?[*:0]const u16, pwchSystemId: ?[*:0]const u16, pvarInput: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXEntityResolver.VTable, self.vtable).resolveEntity(@ptrCast(*const ISAXEntityResolver, self), pwchPublicId, pwchSystemId, pvarInput);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ISAXContentHandler_Value = @import("../../zig.zig").Guid.initString("1545cdfa-9e4e-4497-a8a4-2bf7d0112c44");
pub const IID_ISAXContentHandler = &IID_ISAXContentHandler_Value;
pub const ISAXContentHandler = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
putDocumentLocator: fn(
self: *const ISAXContentHandler,
pLocator: ?*ISAXLocator,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
startDocument: fn(
self: *const ISAXContentHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
endDocument: fn(
self: *const ISAXContentHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
startPrefixMapping: fn(
self: *const ISAXContentHandler,
pwchPrefix: ?[*:0]const u16,
cchPrefix: i32,
pwchUri: ?[*:0]const u16,
cchUri: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
endPrefixMapping: fn(
self: *const ISAXContentHandler,
pwchPrefix: ?[*:0]const u16,
cchPrefix: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
startElement: fn(
self: *const ISAXContentHandler,
pwchNamespaceUri: ?[*:0]const u16,
cchNamespaceUri: i32,
pwchLocalName: ?[*:0]const u16,
cchLocalName: i32,
pwchQName: ?[*:0]const u16,
cchQName: i32,
pAttributes: ?*ISAXAttributes,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
endElement: fn(
self: *const ISAXContentHandler,
pwchNamespaceUri: ?[*:0]const u16,
cchNamespaceUri: i32,
pwchLocalName: ?[*:0]const u16,
cchLocalName: i32,
pwchQName: ?[*:0]const u16,
cchQName: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
characters: fn(
self: *const ISAXContentHandler,
pwchChars: ?[*:0]const u16,
cchChars: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ignorableWhitespace: fn(
self: *const ISAXContentHandler,
pwchChars: ?[*:0]const u16,
cchChars: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
processingInstruction: fn(
self: *const ISAXContentHandler,
pwchTarget: ?[*:0]const u16,
cchTarget: i32,
pwchData: ?[*:0]const u16,
cchData: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
skippedEntity: fn(
self: *const ISAXContentHandler,
pwchName: ?[*:0]const u16,
cchName: 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 ISAXContentHandler_putDocumentLocator(self: *const T, pLocator: ?*ISAXLocator) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXContentHandler.VTable, self.vtable).putDocumentLocator(@ptrCast(*const ISAXContentHandler, self), pLocator);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXContentHandler_startDocument(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXContentHandler.VTable, self.vtable).startDocument(@ptrCast(*const ISAXContentHandler, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXContentHandler_endDocument(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXContentHandler.VTable, self.vtable).endDocument(@ptrCast(*const ISAXContentHandler, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXContentHandler_startPrefixMapping(self: *const T, pwchPrefix: ?[*:0]const u16, cchPrefix: i32, pwchUri: ?[*:0]const u16, cchUri: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXContentHandler.VTable, self.vtable).startPrefixMapping(@ptrCast(*const ISAXContentHandler, self), pwchPrefix, cchPrefix, pwchUri, cchUri);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXContentHandler_endPrefixMapping(self: *const T, pwchPrefix: ?[*:0]const u16, cchPrefix: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXContentHandler.VTable, self.vtable).endPrefixMapping(@ptrCast(*const ISAXContentHandler, self), pwchPrefix, cchPrefix);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXContentHandler_startElement(self: *const T, pwchNamespaceUri: ?[*:0]const u16, cchNamespaceUri: i32, pwchLocalName: ?[*:0]const u16, cchLocalName: i32, pwchQName: ?[*:0]const u16, cchQName: i32, pAttributes: ?*ISAXAttributes) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXContentHandler.VTable, self.vtable).startElement(@ptrCast(*const ISAXContentHandler, self), pwchNamespaceUri, cchNamespaceUri, pwchLocalName, cchLocalName, pwchQName, cchQName, pAttributes);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXContentHandler_endElement(self: *const T, pwchNamespaceUri: ?[*:0]const u16, cchNamespaceUri: i32, pwchLocalName: ?[*:0]const u16, cchLocalName: i32, pwchQName: ?[*:0]const u16, cchQName: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXContentHandler.VTable, self.vtable).endElement(@ptrCast(*const ISAXContentHandler, self), pwchNamespaceUri, cchNamespaceUri, pwchLocalName, cchLocalName, pwchQName, cchQName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXContentHandler_characters(self: *const T, pwchChars: ?[*:0]const u16, cchChars: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXContentHandler.VTable, self.vtable).characters(@ptrCast(*const ISAXContentHandler, self), pwchChars, cchChars);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXContentHandler_ignorableWhitespace(self: *const T, pwchChars: ?[*:0]const u16, cchChars: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXContentHandler.VTable, self.vtable).ignorableWhitespace(@ptrCast(*const ISAXContentHandler, self), pwchChars, cchChars);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXContentHandler_processingInstruction(self: *const T, pwchTarget: ?[*:0]const u16, cchTarget: i32, pwchData: ?[*:0]const u16, cchData: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXContentHandler.VTable, self.vtable).processingInstruction(@ptrCast(*const ISAXContentHandler, self), pwchTarget, cchTarget, pwchData, cchData);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXContentHandler_skippedEntity(self: *const T, pwchName: ?[*:0]const u16, cchName: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXContentHandler.VTable, self.vtable).skippedEntity(@ptrCast(*const ISAXContentHandler, self), pwchName, cchName);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ISAXDTDHandler_Value = @import("../../zig.zig").Guid.initString("e15c1baf-afb3-4d60-8c36-19a8c45defed");
pub const IID_ISAXDTDHandler = &IID_ISAXDTDHandler_Value;
pub const ISAXDTDHandler = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
notationDecl: fn(
self: *const ISAXDTDHandler,
pwchName: ?[*:0]const u16,
cchName: i32,
pwchPublicId: ?[*:0]const u16,
cchPublicId: i32,
pwchSystemId: ?[*:0]const u16,
cchSystemId: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
unparsedEntityDecl: fn(
self: *const ISAXDTDHandler,
pwchName: ?[*:0]const u16,
cchName: i32,
pwchPublicId: ?[*:0]const u16,
cchPublicId: i32,
pwchSystemId: ?[*:0]const u16,
cchSystemId: i32,
pwchNotationName: ?[*:0]const u16,
cchNotationName: 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 ISAXDTDHandler_notationDecl(self: *const T, pwchName: ?[*:0]const u16, cchName: i32, pwchPublicId: ?[*:0]const u16, cchPublicId: i32, pwchSystemId: ?[*:0]const u16, cchSystemId: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXDTDHandler.VTable, self.vtable).notationDecl(@ptrCast(*const ISAXDTDHandler, self), pwchName, cchName, pwchPublicId, cchPublicId, pwchSystemId, cchSystemId);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXDTDHandler_unparsedEntityDecl(self: *const T, pwchName: ?[*:0]const u16, cchName: i32, pwchPublicId: ?[*:0]const u16, cchPublicId: i32, pwchSystemId: ?[*:0]const u16, cchSystemId: i32, pwchNotationName: ?[*:0]const u16, cchNotationName: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXDTDHandler.VTable, self.vtable).unparsedEntityDecl(@ptrCast(*const ISAXDTDHandler, self), pwchName, cchName, pwchPublicId, cchPublicId, pwchSystemId, cchSystemId, pwchNotationName, cchNotationName);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ISAXErrorHandler_Value = @import("../../zig.zig").Guid.initString("a60511c4-ccf5-479e-98a3-dc8dc545b7d0");
pub const IID_ISAXErrorHandler = &IID_ISAXErrorHandler_Value;
pub const ISAXErrorHandler = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
@"error": fn(
self: *const ISAXErrorHandler,
pLocator: ?*ISAXLocator,
pwchErrorMessage: ?[*:0]const u16,
hrErrorCode: HRESULT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
fatalError: fn(
self: *const ISAXErrorHandler,
pLocator: ?*ISAXLocator,
pwchErrorMessage: ?[*:0]const u16,
hrErrorCode: HRESULT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ignorableWarning: fn(
self: *const ISAXErrorHandler,
pLocator: ?*ISAXLocator,
pwchErrorMessage: ?[*:0]const u16,
hrErrorCode: 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 ISAXErrorHandler_error(self: *const T, pLocator: ?*ISAXLocator, pwchErrorMessage: ?[*:0]const u16, hrErrorCode: HRESULT) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXErrorHandler.VTable, self.vtable).@"error"(@ptrCast(*const ISAXErrorHandler, self), pLocator, pwchErrorMessage, hrErrorCode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXErrorHandler_fatalError(self: *const T, pLocator: ?*ISAXLocator, pwchErrorMessage: ?[*:0]const u16, hrErrorCode: HRESULT) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXErrorHandler.VTable, self.vtable).fatalError(@ptrCast(*const ISAXErrorHandler, self), pLocator, pwchErrorMessage, hrErrorCode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXErrorHandler_ignorableWarning(self: *const T, pLocator: ?*ISAXLocator, pwchErrorMessage: ?[*:0]const u16, hrErrorCode: HRESULT) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXErrorHandler.VTable, self.vtable).ignorableWarning(@ptrCast(*const ISAXErrorHandler, self), pLocator, pwchErrorMessage, hrErrorCode);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ISAXLexicalHandler_Value = @import("../../zig.zig").Guid.initString("7f85d5f5-47a8-4497-bda5-84ba04819ea6");
pub const IID_ISAXLexicalHandler = &IID_ISAXLexicalHandler_Value;
pub const ISAXLexicalHandler = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
startDTD: fn(
self: *const ISAXLexicalHandler,
pwchName: ?[*:0]const u16,
cchName: i32,
pwchPublicId: ?[*:0]const u16,
cchPublicId: i32,
pwchSystemId: ?[*:0]const u16,
cchSystemId: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
endDTD: fn(
self: *const ISAXLexicalHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
startEntity: fn(
self: *const ISAXLexicalHandler,
pwchName: ?[*:0]const u16,
cchName: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
endEntity: fn(
self: *const ISAXLexicalHandler,
pwchName: ?[*:0]const u16,
cchName: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
startCDATA: fn(
self: *const ISAXLexicalHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
endCDATA: fn(
self: *const ISAXLexicalHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
comment: fn(
self: *const ISAXLexicalHandler,
pwchChars: ?[*:0]const u16,
cchChars: 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 ISAXLexicalHandler_startDTD(self: *const T, pwchName: ?[*:0]const u16, cchName: i32, pwchPublicId: ?[*:0]const u16, cchPublicId: i32, pwchSystemId: ?[*:0]const u16, cchSystemId: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXLexicalHandler.VTable, self.vtable).startDTD(@ptrCast(*const ISAXLexicalHandler, self), pwchName, cchName, pwchPublicId, cchPublicId, pwchSystemId, cchSystemId);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXLexicalHandler_endDTD(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXLexicalHandler.VTable, self.vtable).endDTD(@ptrCast(*const ISAXLexicalHandler, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXLexicalHandler_startEntity(self: *const T, pwchName: ?[*:0]const u16, cchName: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXLexicalHandler.VTable, self.vtable).startEntity(@ptrCast(*const ISAXLexicalHandler, self), pwchName, cchName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXLexicalHandler_endEntity(self: *const T, pwchName: ?[*:0]const u16, cchName: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXLexicalHandler.VTable, self.vtable).endEntity(@ptrCast(*const ISAXLexicalHandler, self), pwchName, cchName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXLexicalHandler_startCDATA(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXLexicalHandler.VTable, self.vtable).startCDATA(@ptrCast(*const ISAXLexicalHandler, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXLexicalHandler_endCDATA(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXLexicalHandler.VTable, self.vtable).endCDATA(@ptrCast(*const ISAXLexicalHandler, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXLexicalHandler_comment(self: *const T, pwchChars: ?[*:0]const u16, cchChars: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXLexicalHandler.VTable, self.vtable).comment(@ptrCast(*const ISAXLexicalHandler, self), pwchChars, cchChars);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ISAXDeclHandler_Value = @import("../../zig.zig").Guid.initString("862629ac-771a-47b2-8337-4e6843c1be90");
pub const IID_ISAXDeclHandler = &IID_ISAXDeclHandler_Value;
pub const ISAXDeclHandler = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
elementDecl: fn(
self: *const ISAXDeclHandler,
pwchName: ?[*:0]const u16,
cchName: i32,
pwchModel: ?[*:0]const u16,
cchModel: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
attributeDecl: fn(
self: *const ISAXDeclHandler,
pwchElementName: ?[*:0]const u16,
cchElementName: i32,
pwchAttributeName: ?[*:0]const u16,
cchAttributeName: i32,
pwchType: ?[*:0]const u16,
cchType: i32,
pwchValueDefault: ?[*:0]const u16,
cchValueDefault: i32,
pwchValue: ?[*:0]const u16,
cchValue: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
internalEntityDecl: fn(
self: *const ISAXDeclHandler,
pwchName: ?[*:0]const u16,
cchName: i32,
pwchValue: ?[*:0]const u16,
cchValue: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
externalEntityDecl: fn(
self: *const ISAXDeclHandler,
pwchName: ?[*:0]const u16,
cchName: i32,
pwchPublicId: ?[*:0]const u16,
cchPublicId: i32,
pwchSystemId: ?[*:0]const u16,
cchSystemId: 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 ISAXDeclHandler_elementDecl(self: *const T, pwchName: ?[*:0]const u16, cchName: i32, pwchModel: ?[*:0]const u16, cchModel: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXDeclHandler.VTable, self.vtable).elementDecl(@ptrCast(*const ISAXDeclHandler, self), pwchName, cchName, pwchModel, cchModel);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXDeclHandler_attributeDecl(self: *const T, pwchElementName: ?[*:0]const u16, cchElementName: i32, pwchAttributeName: ?[*:0]const u16, cchAttributeName: i32, pwchType: ?[*:0]const u16, cchType: i32, pwchValueDefault: ?[*:0]const u16, cchValueDefault: i32, pwchValue: ?[*:0]const u16, cchValue: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXDeclHandler.VTable, self.vtable).attributeDecl(@ptrCast(*const ISAXDeclHandler, self), pwchElementName, cchElementName, pwchAttributeName, cchAttributeName, pwchType, cchType, pwchValueDefault, cchValueDefault, pwchValue, cchValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXDeclHandler_internalEntityDecl(self: *const T, pwchName: ?[*:0]const u16, cchName: i32, pwchValue: ?[*:0]const u16, cchValue: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXDeclHandler.VTable, self.vtable).internalEntityDecl(@ptrCast(*const ISAXDeclHandler, self), pwchName, cchName, pwchValue, cchValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXDeclHandler_externalEntityDecl(self: *const T, pwchName: ?[*:0]const u16, cchName: i32, pwchPublicId: ?[*:0]const u16, cchPublicId: i32, pwchSystemId: ?[*:0]const u16, cchSystemId: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXDeclHandler.VTable, self.vtable).externalEntityDecl(@ptrCast(*const ISAXDeclHandler, self), pwchName, cchName, pwchPublicId, cchPublicId, pwchSystemId, cchSystemId);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ISAXAttributes_Value = @import("../../zig.zig").Guid.initString("f078abe1-45d2-4832-91ea-4466ce2f25c9");
pub const IID_ISAXAttributes = &IID_ISAXAttributes_Value;
pub const ISAXAttributes = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
getLength: fn(
self: *const ISAXAttributes,
pnLength: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getURI: fn(
self: *const ISAXAttributes,
nIndex: i32,
ppwchUri: ?*const ?*u16,
pcchUri: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getLocalName: fn(
self: *const ISAXAttributes,
nIndex: i32,
ppwchLocalName: ?*const ?*u16,
pcchLocalName: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getQName: fn(
self: *const ISAXAttributes,
nIndex: i32,
ppwchQName: ?*const ?*u16,
pcchQName: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getName: fn(
self: *const ISAXAttributes,
nIndex: i32,
ppwchUri: ?*const ?*u16,
pcchUri: ?*i32,
ppwchLocalName: ?*const ?*u16,
pcchLocalName: ?*i32,
ppwchQName: ?*const ?*u16,
pcchQName: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getIndexFromName: fn(
self: *const ISAXAttributes,
pwchUri: ?[*:0]const u16,
cchUri: i32,
pwchLocalName: ?[*:0]const u16,
cchLocalName: i32,
pnIndex: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getIndexFromQName: fn(
self: *const ISAXAttributes,
pwchQName: ?[*:0]const u16,
cchQName: i32,
pnIndex: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getType: fn(
self: *const ISAXAttributes,
nIndex: i32,
ppwchType: ?*const ?*u16,
pcchType: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getTypeFromName: fn(
self: *const ISAXAttributes,
pwchUri: ?[*:0]const u16,
cchUri: i32,
pwchLocalName: ?[*:0]const u16,
cchLocalName: i32,
ppwchType: ?*const ?*u16,
pcchType: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getTypeFromQName: fn(
self: *const ISAXAttributes,
pwchQName: ?[*:0]const u16,
cchQName: i32,
ppwchType: ?*const ?*u16,
pcchType: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getValue: fn(
self: *const ISAXAttributes,
nIndex: i32,
ppwchValue: ?*const ?*u16,
pcchValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getValueFromName: fn(
self: *const ISAXAttributes,
pwchUri: ?[*:0]const u16,
cchUri: i32,
pwchLocalName: ?[*:0]const u16,
cchLocalName: i32,
ppwchValue: ?*const ?*u16,
pcchValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getValueFromQName: fn(
self: *const ISAXAttributes,
pwchQName: ?[*:0]const u16,
cchQName: i32,
ppwchValue: ?*const ?*u16,
pcchValue: ?*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 ISAXAttributes_getLength(self: *const T, pnLength: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXAttributes.VTable, self.vtable).getLength(@ptrCast(*const ISAXAttributes, self), pnLength);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXAttributes_getURI(self: *const T, nIndex: i32, ppwchUri: ?*const ?*u16, pcchUri: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXAttributes.VTable, self.vtable).getURI(@ptrCast(*const ISAXAttributes, self), nIndex, ppwchUri, pcchUri);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXAttributes_getLocalName(self: *const T, nIndex: i32, ppwchLocalName: ?*const ?*u16, pcchLocalName: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXAttributes.VTable, self.vtable).getLocalName(@ptrCast(*const ISAXAttributes, self), nIndex, ppwchLocalName, pcchLocalName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXAttributes_getQName(self: *const T, nIndex: i32, ppwchQName: ?*const ?*u16, pcchQName: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXAttributes.VTable, self.vtable).getQName(@ptrCast(*const ISAXAttributes, self), nIndex, ppwchQName, pcchQName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXAttributes_getName(self: *const T, nIndex: i32, ppwchUri: ?*const ?*u16, pcchUri: ?*i32, ppwchLocalName: ?*const ?*u16, pcchLocalName: ?*i32, ppwchQName: ?*const ?*u16, pcchQName: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXAttributes.VTable, self.vtable).getName(@ptrCast(*const ISAXAttributes, self), nIndex, ppwchUri, pcchUri, ppwchLocalName, pcchLocalName, ppwchQName, pcchQName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXAttributes_getIndexFromName(self: *const T, pwchUri: ?[*:0]const u16, cchUri: i32, pwchLocalName: ?[*:0]const u16, cchLocalName: i32, pnIndex: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXAttributes.VTable, self.vtable).getIndexFromName(@ptrCast(*const ISAXAttributes, self), pwchUri, cchUri, pwchLocalName, cchLocalName, pnIndex);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXAttributes_getIndexFromQName(self: *const T, pwchQName: ?[*:0]const u16, cchQName: i32, pnIndex: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXAttributes.VTable, self.vtable).getIndexFromQName(@ptrCast(*const ISAXAttributes, self), pwchQName, cchQName, pnIndex);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXAttributes_getType(self: *const T, nIndex: i32, ppwchType: ?*const ?*u16, pcchType: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXAttributes.VTable, self.vtable).getType(@ptrCast(*const ISAXAttributes, self), nIndex, ppwchType, pcchType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXAttributes_getTypeFromName(self: *const T, pwchUri: ?[*:0]const u16, cchUri: i32, pwchLocalName: ?[*:0]const u16, cchLocalName: i32, ppwchType: ?*const ?*u16, pcchType: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXAttributes.VTable, self.vtable).getTypeFromName(@ptrCast(*const ISAXAttributes, self), pwchUri, cchUri, pwchLocalName, cchLocalName, ppwchType, pcchType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXAttributes_getTypeFromQName(self: *const T, pwchQName: ?[*:0]const u16, cchQName: i32, ppwchType: ?*const ?*u16, pcchType: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXAttributes.VTable, self.vtable).getTypeFromQName(@ptrCast(*const ISAXAttributes, self), pwchQName, cchQName, ppwchType, pcchType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXAttributes_getValue(self: *const T, nIndex: i32, ppwchValue: ?*const ?*u16, pcchValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXAttributes.VTable, self.vtable).getValue(@ptrCast(*const ISAXAttributes, self), nIndex, ppwchValue, pcchValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXAttributes_getValueFromName(self: *const T, pwchUri: ?[*:0]const u16, cchUri: i32, pwchLocalName: ?[*:0]const u16, cchLocalName: i32, ppwchValue: ?*const ?*u16, pcchValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXAttributes.VTable, self.vtable).getValueFromName(@ptrCast(*const ISAXAttributes, self), pwchUri, cchUri, pwchLocalName, cchLocalName, ppwchValue, pcchValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISAXAttributes_getValueFromQName(self: *const T, pwchQName: ?[*:0]const u16, cchQName: i32, ppwchValue: ?*const ?*u16, pcchValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISAXAttributes.VTable, self.vtable).getValueFromQName(@ptrCast(*const ISAXAttributes, self), pwchQName, cchQName, ppwchValue, pcchValue);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IVBSAXXMLReader_Value = @import("../../zig.zig").Guid.initString("8c033caa-6cd6-4f73-b728-4531af74945f");
pub const IID_IVBSAXXMLReader = &IID_IVBSAXXMLReader_Value;
pub const IVBSAXXMLReader = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
getFeature: fn(
self: *const IVBSAXXMLReader,
strName: ?BSTR,
fValue: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
putFeature: fn(
self: *const IVBSAXXMLReader,
strName: ?BSTR,
fValue: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getProperty: fn(
self: *const IVBSAXXMLReader,
strName: ?BSTR,
varValue: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
putProperty: fn(
self: *const IVBSAXXMLReader,
strName: ?BSTR,
varValue: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_entityResolver: fn(
self: *const IVBSAXXMLReader,
oResolver: ?*?*IVBSAXEntityResolver,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
putref_entityResolver: fn(
self: *const IVBSAXXMLReader,
oResolver: ?*IVBSAXEntityResolver,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_contentHandler: fn(
self: *const IVBSAXXMLReader,
oHandler: ?*?*IVBSAXContentHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
putref_contentHandler: fn(
self: *const IVBSAXXMLReader,
oHandler: ?*IVBSAXContentHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_dtdHandler: fn(
self: *const IVBSAXXMLReader,
oHandler: ?*?*IVBSAXDTDHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
putref_dtdHandler: fn(
self: *const IVBSAXXMLReader,
oHandler: ?*IVBSAXDTDHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_errorHandler: fn(
self: *const IVBSAXXMLReader,
oHandler: ?*?*IVBSAXErrorHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
putref_errorHandler: fn(
self: *const IVBSAXXMLReader,
oHandler: ?*IVBSAXErrorHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_baseURL: fn(
self: *const IVBSAXXMLReader,
strBaseURL: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_baseURL: fn(
self: *const IVBSAXXMLReader,
strBaseURL: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_secureBaseURL: fn(
self: *const IVBSAXXMLReader,
strSecureBaseURL: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_secureBaseURL: fn(
self: *const IVBSAXXMLReader,
strSecureBaseURL: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
parse: fn(
self: *const IVBSAXXMLReader,
varInput: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
parseURL: fn(
self: *const IVBSAXXMLReader,
strURL: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXXMLReader_getFeature(self: *const T, strName: ?BSTR, fValue: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXXMLReader.VTable, self.vtable).getFeature(@ptrCast(*const IVBSAXXMLReader, self), strName, fValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXXMLReader_putFeature(self: *const T, strName: ?BSTR, fValue: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXXMLReader.VTable, self.vtable).putFeature(@ptrCast(*const IVBSAXXMLReader, self), strName, fValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXXMLReader_getProperty(self: *const T, strName: ?BSTR, varValue: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXXMLReader.VTable, self.vtable).getProperty(@ptrCast(*const IVBSAXXMLReader, self), strName, varValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXXMLReader_putProperty(self: *const T, strName: ?BSTR, varValue: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXXMLReader.VTable, self.vtable).putProperty(@ptrCast(*const IVBSAXXMLReader, self), strName, varValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXXMLReader_get_entityResolver(self: *const T, oResolver: ?*?*IVBSAXEntityResolver) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXXMLReader.VTable, self.vtable).get_entityResolver(@ptrCast(*const IVBSAXXMLReader, self), oResolver);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXXMLReader_putref_entityResolver(self: *const T, oResolver: ?*IVBSAXEntityResolver) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXXMLReader.VTable, self.vtable).putref_entityResolver(@ptrCast(*const IVBSAXXMLReader, self), oResolver);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXXMLReader_get_contentHandler(self: *const T, oHandler: ?*?*IVBSAXContentHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXXMLReader.VTable, self.vtable).get_contentHandler(@ptrCast(*const IVBSAXXMLReader, self), oHandler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXXMLReader_putref_contentHandler(self: *const T, oHandler: ?*IVBSAXContentHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXXMLReader.VTable, self.vtable).putref_contentHandler(@ptrCast(*const IVBSAXXMLReader, self), oHandler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXXMLReader_get_dtdHandler(self: *const T, oHandler: ?*?*IVBSAXDTDHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXXMLReader.VTable, self.vtable).get_dtdHandler(@ptrCast(*const IVBSAXXMLReader, self), oHandler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXXMLReader_putref_dtdHandler(self: *const T, oHandler: ?*IVBSAXDTDHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXXMLReader.VTable, self.vtable).putref_dtdHandler(@ptrCast(*const IVBSAXXMLReader, self), oHandler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXXMLReader_get_errorHandler(self: *const T, oHandler: ?*?*IVBSAXErrorHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXXMLReader.VTable, self.vtable).get_errorHandler(@ptrCast(*const IVBSAXXMLReader, self), oHandler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXXMLReader_putref_errorHandler(self: *const T, oHandler: ?*IVBSAXErrorHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXXMLReader.VTable, self.vtable).putref_errorHandler(@ptrCast(*const IVBSAXXMLReader, self), oHandler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXXMLReader_get_baseURL(self: *const T, strBaseURL: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXXMLReader.VTable, self.vtable).get_baseURL(@ptrCast(*const IVBSAXXMLReader, self), strBaseURL);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXXMLReader_put_baseURL(self: *const T, strBaseURL: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXXMLReader.VTable, self.vtable).put_baseURL(@ptrCast(*const IVBSAXXMLReader, self), strBaseURL);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXXMLReader_get_secureBaseURL(self: *const T, strSecureBaseURL: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXXMLReader.VTable, self.vtable).get_secureBaseURL(@ptrCast(*const IVBSAXXMLReader, self), strSecureBaseURL);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXXMLReader_put_secureBaseURL(self: *const T, strSecureBaseURL: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXXMLReader.VTable, self.vtable).put_secureBaseURL(@ptrCast(*const IVBSAXXMLReader, self), strSecureBaseURL);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXXMLReader_parse(self: *const T, varInput: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXXMLReader.VTable, self.vtable).parse(@ptrCast(*const IVBSAXXMLReader, self), varInput);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXXMLReader_parseURL(self: *const T, strURL: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXXMLReader.VTable, self.vtable).parseURL(@ptrCast(*const IVBSAXXMLReader, self), strURL);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IVBSAXXMLFilter_Value = @import("../../zig.zig").Guid.initString("1299eb1b-5b88-433e-82de-82ca75ad4e04");
pub const IID_IVBSAXXMLFilter = &IID_IVBSAXXMLFilter_Value;
pub const IVBSAXXMLFilter = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_parent: fn(
self: *const IVBSAXXMLFilter,
oReader: ?*?*IVBSAXXMLReader,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
putref_parent: fn(
self: *const IVBSAXXMLFilter,
oReader: ?*IVBSAXXMLReader,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXXMLFilter_get_parent(self: *const T, oReader: ?*?*IVBSAXXMLReader) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXXMLFilter.VTable, self.vtable).get_parent(@ptrCast(*const IVBSAXXMLFilter, self), oReader);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXXMLFilter_putref_parent(self: *const T, oReader: ?*IVBSAXXMLReader) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXXMLFilter.VTable, self.vtable).putref_parent(@ptrCast(*const IVBSAXXMLFilter, self), oReader);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IVBSAXLocator_Value = @import("../../zig.zig").Guid.initString("796e7ac5-5aa2-4eff-acad-3faaf01a3288");
pub const IID_IVBSAXLocator = &IID_IVBSAXLocator_Value;
pub const IVBSAXLocator = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_columnNumber: fn(
self: *const IVBSAXLocator,
nColumn: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_lineNumber: fn(
self: *const IVBSAXLocator,
nLine: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_publicId: fn(
self: *const IVBSAXLocator,
strPublicId: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_systemId: fn(
self: *const IVBSAXLocator,
strSystemId: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXLocator_get_columnNumber(self: *const T, nColumn: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXLocator.VTable, self.vtable).get_columnNumber(@ptrCast(*const IVBSAXLocator, self), nColumn);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXLocator_get_lineNumber(self: *const T, nLine: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXLocator.VTable, self.vtable).get_lineNumber(@ptrCast(*const IVBSAXLocator, self), nLine);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXLocator_get_publicId(self: *const T, strPublicId: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXLocator.VTable, self.vtable).get_publicId(@ptrCast(*const IVBSAXLocator, self), strPublicId);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXLocator_get_systemId(self: *const T, strSystemId: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXLocator.VTable, self.vtable).get_systemId(@ptrCast(*const IVBSAXLocator, self), strSystemId);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IVBSAXEntityResolver_Value = @import("../../zig.zig").Guid.initString("0c05d096-f45b-4aca-ad1a-aa0bc25518dc");
pub const IID_IVBSAXEntityResolver = &IID_IVBSAXEntityResolver_Value;
pub const IVBSAXEntityResolver = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
resolveEntity: fn(
self: *const IVBSAXEntityResolver,
strPublicId: ?*?BSTR,
strSystemId: ?*?BSTR,
varInput: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXEntityResolver_resolveEntity(self: *const T, strPublicId: ?*?BSTR, strSystemId: ?*?BSTR, varInput: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXEntityResolver.VTable, self.vtable).resolveEntity(@ptrCast(*const IVBSAXEntityResolver, self), strPublicId, strSystemId, varInput);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IVBSAXContentHandler_Value = @import("../../zig.zig").Guid.initString("2ed7290a-4dd5-4b46-bb26-4e4155e77faa");
pub const IID_IVBSAXContentHandler = &IID_IVBSAXContentHandler_Value;
pub const IVBSAXContentHandler = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
putref_documentLocator: fn(
self: *const IVBSAXContentHandler,
oLocator: ?*IVBSAXLocator,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
startDocument: fn(
self: *const IVBSAXContentHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
endDocument: fn(
self: *const IVBSAXContentHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
startPrefixMapping: fn(
self: *const IVBSAXContentHandler,
strPrefix: ?*?BSTR,
strURI: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
endPrefixMapping: fn(
self: *const IVBSAXContentHandler,
strPrefix: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
startElement: fn(
self: *const IVBSAXContentHandler,
strNamespaceURI: ?*?BSTR,
strLocalName: ?*?BSTR,
strQName: ?*?BSTR,
oAttributes: ?*IVBSAXAttributes,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
endElement: fn(
self: *const IVBSAXContentHandler,
strNamespaceURI: ?*?BSTR,
strLocalName: ?*?BSTR,
strQName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
characters: fn(
self: *const IVBSAXContentHandler,
strChars: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ignorableWhitespace: fn(
self: *const IVBSAXContentHandler,
strChars: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
processingInstruction: fn(
self: *const IVBSAXContentHandler,
strTarget: ?*?BSTR,
strData: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
skippedEntity: fn(
self: *const IVBSAXContentHandler,
strName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXContentHandler_putref_documentLocator(self: *const T, oLocator: ?*IVBSAXLocator) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXContentHandler.VTable, self.vtable).putref_documentLocator(@ptrCast(*const IVBSAXContentHandler, self), oLocator);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXContentHandler_startDocument(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXContentHandler.VTable, self.vtable).startDocument(@ptrCast(*const IVBSAXContentHandler, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXContentHandler_endDocument(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXContentHandler.VTable, self.vtable).endDocument(@ptrCast(*const IVBSAXContentHandler, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXContentHandler_startPrefixMapping(self: *const T, strPrefix: ?*?BSTR, strURI: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXContentHandler.VTable, self.vtable).startPrefixMapping(@ptrCast(*const IVBSAXContentHandler, self), strPrefix, strURI);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXContentHandler_endPrefixMapping(self: *const T, strPrefix: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXContentHandler.VTable, self.vtable).endPrefixMapping(@ptrCast(*const IVBSAXContentHandler, self), strPrefix);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXContentHandler_startElement(self: *const T, strNamespaceURI: ?*?BSTR, strLocalName: ?*?BSTR, strQName: ?*?BSTR, oAttributes: ?*IVBSAXAttributes) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXContentHandler.VTable, self.vtable).startElement(@ptrCast(*const IVBSAXContentHandler, self), strNamespaceURI, strLocalName, strQName, oAttributes);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXContentHandler_endElement(self: *const T, strNamespaceURI: ?*?BSTR, strLocalName: ?*?BSTR, strQName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXContentHandler.VTable, self.vtable).endElement(@ptrCast(*const IVBSAXContentHandler, self), strNamespaceURI, strLocalName, strQName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXContentHandler_characters(self: *const T, strChars: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXContentHandler.VTable, self.vtable).characters(@ptrCast(*const IVBSAXContentHandler, self), strChars);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXContentHandler_ignorableWhitespace(self: *const T, strChars: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXContentHandler.VTable, self.vtable).ignorableWhitespace(@ptrCast(*const IVBSAXContentHandler, self), strChars);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXContentHandler_processingInstruction(self: *const T, strTarget: ?*?BSTR, strData: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXContentHandler.VTable, self.vtable).processingInstruction(@ptrCast(*const IVBSAXContentHandler, self), strTarget, strData);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXContentHandler_skippedEntity(self: *const T, strName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXContentHandler.VTable, self.vtable).skippedEntity(@ptrCast(*const IVBSAXContentHandler, self), strName);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IVBSAXDTDHandler_Value = @import("../../zig.zig").Guid.initString("24fb3297-302d-4620-ba39-3a732d850558");
pub const IID_IVBSAXDTDHandler = &IID_IVBSAXDTDHandler_Value;
pub const IVBSAXDTDHandler = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
notationDecl: fn(
self: *const IVBSAXDTDHandler,
strName: ?*?BSTR,
strPublicId: ?*?BSTR,
strSystemId: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
unparsedEntityDecl: fn(
self: *const IVBSAXDTDHandler,
strName: ?*?BSTR,
strPublicId: ?*?BSTR,
strSystemId: ?*?BSTR,
strNotationName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXDTDHandler_notationDecl(self: *const T, strName: ?*?BSTR, strPublicId: ?*?BSTR, strSystemId: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXDTDHandler.VTable, self.vtable).notationDecl(@ptrCast(*const IVBSAXDTDHandler, self), strName, strPublicId, strSystemId);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXDTDHandler_unparsedEntityDecl(self: *const T, strName: ?*?BSTR, strPublicId: ?*?BSTR, strSystemId: ?*?BSTR, strNotationName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXDTDHandler.VTable, self.vtable).unparsedEntityDecl(@ptrCast(*const IVBSAXDTDHandler, self), strName, strPublicId, strSystemId, strNotationName);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IVBSAXErrorHandler_Value = @import("../../zig.zig").Guid.initString("d963d3fe-173c-4862-9095-b92f66995f52");
pub const IID_IVBSAXErrorHandler = &IID_IVBSAXErrorHandler_Value;
pub const IVBSAXErrorHandler = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
@"error": fn(
self: *const IVBSAXErrorHandler,
oLocator: ?*IVBSAXLocator,
strErrorMessage: ?*?BSTR,
nErrorCode: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
fatalError: fn(
self: *const IVBSAXErrorHandler,
oLocator: ?*IVBSAXLocator,
strErrorMessage: ?*?BSTR,
nErrorCode: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ignorableWarning: fn(
self: *const IVBSAXErrorHandler,
oLocator: ?*IVBSAXLocator,
strErrorMessage: ?*?BSTR,
nErrorCode: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXErrorHandler_error(self: *const T, oLocator: ?*IVBSAXLocator, strErrorMessage: ?*?BSTR, nErrorCode: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXErrorHandler.VTable, self.vtable).@"error"(@ptrCast(*const IVBSAXErrorHandler, self), oLocator, strErrorMessage, nErrorCode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXErrorHandler_fatalError(self: *const T, oLocator: ?*IVBSAXLocator, strErrorMessage: ?*?BSTR, nErrorCode: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXErrorHandler.VTable, self.vtable).fatalError(@ptrCast(*const IVBSAXErrorHandler, self), oLocator, strErrorMessage, nErrorCode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXErrorHandler_ignorableWarning(self: *const T, oLocator: ?*IVBSAXLocator, strErrorMessage: ?*?BSTR, nErrorCode: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXErrorHandler.VTable, self.vtable).ignorableWarning(@ptrCast(*const IVBSAXErrorHandler, self), oLocator, strErrorMessage, nErrorCode);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IVBSAXLexicalHandler_Value = @import("../../zig.zig").Guid.initString("032aac35-8c0e-4d9d-979f-e3b702935576");
pub const IID_IVBSAXLexicalHandler = &IID_IVBSAXLexicalHandler_Value;
pub const IVBSAXLexicalHandler = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
startDTD: fn(
self: *const IVBSAXLexicalHandler,
strName: ?*?BSTR,
strPublicId: ?*?BSTR,
strSystemId: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
endDTD: fn(
self: *const IVBSAXLexicalHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
startEntity: fn(
self: *const IVBSAXLexicalHandler,
strName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
endEntity: fn(
self: *const IVBSAXLexicalHandler,
strName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
startCDATA: fn(
self: *const IVBSAXLexicalHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
endCDATA: fn(
self: *const IVBSAXLexicalHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
comment: fn(
self: *const IVBSAXLexicalHandler,
strChars: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXLexicalHandler_startDTD(self: *const T, strName: ?*?BSTR, strPublicId: ?*?BSTR, strSystemId: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXLexicalHandler.VTable, self.vtable).startDTD(@ptrCast(*const IVBSAXLexicalHandler, self), strName, strPublicId, strSystemId);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXLexicalHandler_endDTD(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXLexicalHandler.VTable, self.vtable).endDTD(@ptrCast(*const IVBSAXLexicalHandler, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXLexicalHandler_startEntity(self: *const T, strName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXLexicalHandler.VTable, self.vtable).startEntity(@ptrCast(*const IVBSAXLexicalHandler, self), strName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXLexicalHandler_endEntity(self: *const T, strName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXLexicalHandler.VTable, self.vtable).endEntity(@ptrCast(*const IVBSAXLexicalHandler, self), strName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXLexicalHandler_startCDATA(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXLexicalHandler.VTable, self.vtable).startCDATA(@ptrCast(*const IVBSAXLexicalHandler, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXLexicalHandler_endCDATA(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXLexicalHandler.VTable, self.vtable).endCDATA(@ptrCast(*const IVBSAXLexicalHandler, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXLexicalHandler_comment(self: *const T, strChars: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXLexicalHandler.VTable, self.vtable).comment(@ptrCast(*const IVBSAXLexicalHandler, self), strChars);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IVBSAXDeclHandler_Value = @import("../../zig.zig").Guid.initString("e8917260-7579-4be1-b5dd-7afbfa6f077b");
pub const IID_IVBSAXDeclHandler = &IID_IVBSAXDeclHandler_Value;
pub const IVBSAXDeclHandler = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
elementDecl: fn(
self: *const IVBSAXDeclHandler,
strName: ?*?BSTR,
strModel: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
attributeDecl: fn(
self: *const IVBSAXDeclHandler,
strElementName: ?*?BSTR,
strAttributeName: ?*?BSTR,
strType: ?*?BSTR,
strValueDefault: ?*?BSTR,
strValue: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
internalEntityDecl: fn(
self: *const IVBSAXDeclHandler,
strName: ?*?BSTR,
strValue: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
externalEntityDecl: fn(
self: *const IVBSAXDeclHandler,
strName: ?*?BSTR,
strPublicId: ?*?BSTR,
strSystemId: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXDeclHandler_elementDecl(self: *const T, strName: ?*?BSTR, strModel: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXDeclHandler.VTable, self.vtable).elementDecl(@ptrCast(*const IVBSAXDeclHandler, self), strName, strModel);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXDeclHandler_attributeDecl(self: *const T, strElementName: ?*?BSTR, strAttributeName: ?*?BSTR, strType: ?*?BSTR, strValueDefault: ?*?BSTR, strValue: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXDeclHandler.VTable, self.vtable).attributeDecl(@ptrCast(*const IVBSAXDeclHandler, self), strElementName, strAttributeName, strType, strValueDefault, strValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXDeclHandler_internalEntityDecl(self: *const T, strName: ?*?BSTR, strValue: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXDeclHandler.VTable, self.vtable).internalEntityDecl(@ptrCast(*const IVBSAXDeclHandler, self), strName, strValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXDeclHandler_externalEntityDecl(self: *const T, strName: ?*?BSTR, strPublicId: ?*?BSTR, strSystemId: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXDeclHandler.VTable, self.vtable).externalEntityDecl(@ptrCast(*const IVBSAXDeclHandler, self), strName, strPublicId, strSystemId);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IVBSAXAttributes_Value = @import("../../zig.zig").Guid.initString("10dc0586-132b-4cac-8bb3-db00ac8b7ee0");
pub const IID_IVBSAXAttributes = &IID_IVBSAXAttributes_Value;
pub const IVBSAXAttributes = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_length: fn(
self: *const IVBSAXAttributes,
nLength: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getURI: fn(
self: *const IVBSAXAttributes,
nIndex: i32,
strURI: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getLocalName: fn(
self: *const IVBSAXAttributes,
nIndex: i32,
strLocalName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getQName: fn(
self: *const IVBSAXAttributes,
nIndex: i32,
strQName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getIndexFromName: fn(
self: *const IVBSAXAttributes,
strURI: ?BSTR,
strLocalName: ?BSTR,
nIndex: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getIndexFromQName: fn(
self: *const IVBSAXAttributes,
strQName: ?BSTR,
nIndex: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getType: fn(
self: *const IVBSAXAttributes,
nIndex: i32,
strType: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getTypeFromName: fn(
self: *const IVBSAXAttributes,
strURI: ?BSTR,
strLocalName: ?BSTR,
strType: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getTypeFromQName: fn(
self: *const IVBSAXAttributes,
strQName: ?BSTR,
strType: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getValue: fn(
self: *const IVBSAXAttributes,
nIndex: i32,
strValue: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getValueFromName: fn(
self: *const IVBSAXAttributes,
strURI: ?BSTR,
strLocalName: ?BSTR,
strValue: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getValueFromQName: fn(
self: *const IVBSAXAttributes,
strQName: ?BSTR,
strValue: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXAttributes_get_length(self: *const T, nLength: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXAttributes.VTable, self.vtable).get_length(@ptrCast(*const IVBSAXAttributes, self), nLength);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXAttributes_getURI(self: *const T, nIndex: i32, strURI: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXAttributes.VTable, self.vtable).getURI(@ptrCast(*const IVBSAXAttributes, self), nIndex, strURI);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXAttributes_getLocalName(self: *const T, nIndex: i32, strLocalName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXAttributes.VTable, self.vtable).getLocalName(@ptrCast(*const IVBSAXAttributes, self), nIndex, strLocalName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXAttributes_getQName(self: *const T, nIndex: i32, strQName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXAttributes.VTable, self.vtable).getQName(@ptrCast(*const IVBSAXAttributes, self), nIndex, strQName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXAttributes_getIndexFromName(self: *const T, strURI: ?BSTR, strLocalName: ?BSTR, nIndex: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXAttributes.VTable, self.vtable).getIndexFromName(@ptrCast(*const IVBSAXAttributes, self), strURI, strLocalName, nIndex);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXAttributes_getIndexFromQName(self: *const T, strQName: ?BSTR, nIndex: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXAttributes.VTable, self.vtable).getIndexFromQName(@ptrCast(*const IVBSAXAttributes, self), strQName, nIndex);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXAttributes_getType(self: *const T, nIndex: i32, strType: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXAttributes.VTable, self.vtable).getType(@ptrCast(*const IVBSAXAttributes, self), nIndex, strType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXAttributes_getTypeFromName(self: *const T, strURI: ?BSTR, strLocalName: ?BSTR, strType: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXAttributes.VTable, self.vtable).getTypeFromName(@ptrCast(*const IVBSAXAttributes, self), strURI, strLocalName, strType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXAttributes_getTypeFromQName(self: *const T, strQName: ?BSTR, strType: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXAttributes.VTable, self.vtable).getTypeFromQName(@ptrCast(*const IVBSAXAttributes, self), strQName, strType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXAttributes_getValue(self: *const T, nIndex: i32, strValue: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXAttributes.VTable, self.vtable).getValue(@ptrCast(*const IVBSAXAttributes, self), nIndex, strValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXAttributes_getValueFromName(self: *const T, strURI: ?BSTR, strLocalName: ?BSTR, strValue: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXAttributes.VTable, self.vtable).getValueFromName(@ptrCast(*const IVBSAXAttributes, self), strURI, strLocalName, strValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBSAXAttributes_getValueFromQName(self: *const T, strQName: ?BSTR, strValue: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBSAXAttributes.VTable, self.vtable).getValueFromQName(@ptrCast(*const IVBSAXAttributes, self), strQName, strValue);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IMXWriter_Value = @import("../../zig.zig").Guid.initString("4d7ff4ba-1565-4ea8-94e1-6e724a46f98d");
pub const IID_IMXWriter = &IID_IMXWriter_Value;
pub const IMXWriter = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_output: fn(
self: *const IMXWriter,
varDestination: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_output: fn(
self: *const IMXWriter,
varDestination: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_encoding: fn(
self: *const IMXWriter,
strEncoding: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_encoding: fn(
self: *const IMXWriter,
strEncoding: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_byteOrderMark: fn(
self: *const IMXWriter,
fWriteByteOrderMark: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_byteOrderMark: fn(
self: *const IMXWriter,
fWriteByteOrderMark: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_indent: fn(
self: *const IMXWriter,
fIndentMode: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_indent: fn(
self: *const IMXWriter,
fIndentMode: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_standalone: fn(
self: *const IMXWriter,
fValue: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_standalone: fn(
self: *const IMXWriter,
fValue: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_omitXMLDeclaration: fn(
self: *const IMXWriter,
fValue: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_omitXMLDeclaration: fn(
self: *const IMXWriter,
fValue: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_version: fn(
self: *const IMXWriter,
strVersion: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_version: fn(
self: *const IMXWriter,
strVersion: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_disableOutputEscaping: fn(
self: *const IMXWriter,
fValue: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_disableOutputEscaping: fn(
self: *const IMXWriter,
fValue: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
flush: fn(
self: *const IMXWriter,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXWriter_put_output(self: *const T, varDestination: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXWriter.VTable, self.vtable).put_output(@ptrCast(*const IMXWriter, self), varDestination);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXWriter_get_output(self: *const T, varDestination: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXWriter.VTable, self.vtable).get_output(@ptrCast(*const IMXWriter, self), varDestination);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXWriter_put_encoding(self: *const T, strEncoding: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXWriter.VTable, self.vtable).put_encoding(@ptrCast(*const IMXWriter, self), strEncoding);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXWriter_get_encoding(self: *const T, strEncoding: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXWriter.VTable, self.vtable).get_encoding(@ptrCast(*const IMXWriter, self), strEncoding);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXWriter_put_byteOrderMark(self: *const T, fWriteByteOrderMark: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXWriter.VTable, self.vtable).put_byteOrderMark(@ptrCast(*const IMXWriter, self), fWriteByteOrderMark);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXWriter_get_byteOrderMark(self: *const T, fWriteByteOrderMark: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXWriter.VTable, self.vtable).get_byteOrderMark(@ptrCast(*const IMXWriter, self), fWriteByteOrderMark);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXWriter_put_indent(self: *const T, fIndentMode: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXWriter.VTable, self.vtable).put_indent(@ptrCast(*const IMXWriter, self), fIndentMode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXWriter_get_indent(self: *const T, fIndentMode: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXWriter.VTable, self.vtable).get_indent(@ptrCast(*const IMXWriter, self), fIndentMode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXWriter_put_standalone(self: *const T, fValue: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXWriter.VTable, self.vtable).put_standalone(@ptrCast(*const IMXWriter, self), fValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXWriter_get_standalone(self: *const T, fValue: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXWriter.VTable, self.vtable).get_standalone(@ptrCast(*const IMXWriter, self), fValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXWriter_put_omitXMLDeclaration(self: *const T, fValue: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXWriter.VTable, self.vtable).put_omitXMLDeclaration(@ptrCast(*const IMXWriter, self), fValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXWriter_get_omitXMLDeclaration(self: *const T, fValue: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXWriter.VTable, self.vtable).get_omitXMLDeclaration(@ptrCast(*const IMXWriter, self), fValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXWriter_put_version(self: *const T, strVersion: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXWriter.VTable, self.vtable).put_version(@ptrCast(*const IMXWriter, self), strVersion);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXWriter_get_version(self: *const T, strVersion: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXWriter.VTable, self.vtable).get_version(@ptrCast(*const IMXWriter, self), strVersion);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXWriter_put_disableOutputEscaping(self: *const T, fValue: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXWriter.VTable, self.vtable).put_disableOutputEscaping(@ptrCast(*const IMXWriter, self), fValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXWriter_get_disableOutputEscaping(self: *const T, fValue: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXWriter.VTable, self.vtable).get_disableOutputEscaping(@ptrCast(*const IMXWriter, self), fValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXWriter_flush(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXWriter.VTable, self.vtable).flush(@ptrCast(*const IMXWriter, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IMXAttributes_Value = @import("../../zig.zig").Guid.initString("f10d27cc-3ec0-415c-8ed8-77ab1c5e7262");
pub const IID_IMXAttributes = &IID_IMXAttributes_Value;
pub const IMXAttributes = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
addAttribute: fn(
self: *const IMXAttributes,
strURI: ?BSTR,
strLocalName: ?BSTR,
strQName: ?BSTR,
strType: ?BSTR,
strValue: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
addAttributeFromIndex: fn(
self: *const IMXAttributes,
varAtts: VARIANT,
nIndex: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
clear: fn(
self: *const IMXAttributes,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
removeAttribute: fn(
self: *const IMXAttributes,
nIndex: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
setAttribute: fn(
self: *const IMXAttributes,
nIndex: i32,
strURI: ?BSTR,
strLocalName: ?BSTR,
strQName: ?BSTR,
strType: ?BSTR,
strValue: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
setAttributes: fn(
self: *const IMXAttributes,
varAtts: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
setLocalName: fn(
self: *const IMXAttributes,
nIndex: i32,
strLocalName: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
setQName: fn(
self: *const IMXAttributes,
nIndex: i32,
strQName: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
setType: fn(
self: *const IMXAttributes,
nIndex: i32,
strType: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
setURI: fn(
self: *const IMXAttributes,
nIndex: i32,
strURI: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
setValue: fn(
self: *const IMXAttributes,
nIndex: i32,
strValue: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXAttributes_addAttribute(self: *const T, strURI: ?BSTR, strLocalName: ?BSTR, strQName: ?BSTR, strType: ?BSTR, strValue: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXAttributes.VTable, self.vtable).addAttribute(@ptrCast(*const IMXAttributes, self), strURI, strLocalName, strQName, strType, strValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXAttributes_addAttributeFromIndex(self: *const T, varAtts: VARIANT, nIndex: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXAttributes.VTable, self.vtable).addAttributeFromIndex(@ptrCast(*const IMXAttributes, self), varAtts, nIndex);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXAttributes_clear(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXAttributes.VTable, self.vtable).clear(@ptrCast(*const IMXAttributes, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXAttributes_removeAttribute(self: *const T, nIndex: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXAttributes.VTable, self.vtable).removeAttribute(@ptrCast(*const IMXAttributes, self), nIndex);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXAttributes_setAttribute(self: *const T, nIndex: i32, strURI: ?BSTR, strLocalName: ?BSTR, strQName: ?BSTR, strType: ?BSTR, strValue: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXAttributes.VTable, self.vtable).setAttribute(@ptrCast(*const IMXAttributes, self), nIndex, strURI, strLocalName, strQName, strType, strValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXAttributes_setAttributes(self: *const T, varAtts: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXAttributes.VTable, self.vtable).setAttributes(@ptrCast(*const IMXAttributes, self), varAtts);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXAttributes_setLocalName(self: *const T, nIndex: i32, strLocalName: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXAttributes.VTable, self.vtable).setLocalName(@ptrCast(*const IMXAttributes, self), nIndex, strLocalName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXAttributes_setQName(self: *const T, nIndex: i32, strQName: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXAttributes.VTable, self.vtable).setQName(@ptrCast(*const IMXAttributes, self), nIndex, strQName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXAttributes_setType(self: *const T, nIndex: i32, strType: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXAttributes.VTable, self.vtable).setType(@ptrCast(*const IMXAttributes, self), nIndex, strType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXAttributes_setURI(self: *const T, nIndex: i32, strURI: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXAttributes.VTable, self.vtable).setURI(@ptrCast(*const IMXAttributes, self), nIndex, strURI);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXAttributes_setValue(self: *const T, nIndex: i32, strValue: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXAttributes.VTable, self.vtable).setValue(@ptrCast(*const IMXAttributes, self), nIndex, strValue);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IMXReaderControl_Value = @import("../../zig.zig").Guid.initString("808f4e35-8d5a-4fbe-8466-33a41279ed30");
pub const IID_IMXReaderControl = &IID_IMXReaderControl_Value;
pub const IMXReaderControl = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
abort: fn(
self: *const IMXReaderControl,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
@"resume": fn(
self: *const IMXReaderControl,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
@"suspend": fn(
self: *const IMXReaderControl,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXReaderControl_abort(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXReaderControl.VTable, self.vtable).abort(@ptrCast(*const IMXReaderControl, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXReaderControl_resume(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXReaderControl.VTable, self.vtable).@"resume"(@ptrCast(*const IMXReaderControl, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXReaderControl_suspend(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXReaderControl.VTable, self.vtable).@"suspend"(@ptrCast(*const IMXReaderControl, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IMXSchemaDeclHandler_Value = @import("../../zig.zig").Guid.initString("fa4bb38c-faf9-4cca-9302-d1dd0fe520db");
pub const IID_IMXSchemaDeclHandler = &IID_IMXSchemaDeclHandler_Value;
pub const IMXSchemaDeclHandler = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
schemaElementDecl: fn(
self: *const IMXSchemaDeclHandler,
oSchemaElement: ?*ISchemaElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXSchemaDeclHandler_schemaElementDecl(self: *const T, oSchemaElement: ?*ISchemaElement) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXSchemaDeclHandler.VTable, self.vtable).schemaElementDecl(@ptrCast(*const IMXSchemaDeclHandler, self), oSchemaElement);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IMXNamespacePrefixes_Value = @import("../../zig.zig").Guid.initString("c90352f4-643c-4fbc-bb23-e996eb2d51fd");
pub const IID_IMXNamespacePrefixes = &IID_IMXNamespacePrefixes_Value;
pub const IMXNamespacePrefixes = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_item: fn(
self: *const IMXNamespacePrefixes,
index: i32,
prefix: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_length: fn(
self: *const IMXNamespacePrefixes,
length: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get__newEnum: fn(
self: *const IMXNamespacePrefixes,
ppUnk: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXNamespacePrefixes_get_item(self: *const T, index: i32, prefix: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXNamespacePrefixes.VTable, self.vtable).get_item(@ptrCast(*const IMXNamespacePrefixes, self), index, prefix);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXNamespacePrefixes_get_length(self: *const T, length: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXNamespacePrefixes.VTable, self.vtable).get_length(@ptrCast(*const IMXNamespacePrefixes, self), length);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXNamespacePrefixes_get__newEnum(self: *const T, ppUnk: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXNamespacePrefixes.VTable, self.vtable).get__newEnum(@ptrCast(*const IMXNamespacePrefixes, self), ppUnk);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IVBMXNamespaceManager_Value = @import("../../zig.zig").Guid.initString("c90352f5-643c-4fbc-bb23-e996eb2d51fd");
pub const IID_IVBMXNamespaceManager = &IID_IVBMXNamespaceManager_Value;
pub const IVBMXNamespaceManager = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_allowOverride: fn(
self: *const IVBMXNamespaceManager,
fOverride: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_allowOverride: fn(
self: *const IVBMXNamespaceManager,
fOverride: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
reset: fn(
self: *const IVBMXNamespaceManager,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
pushContext: fn(
self: *const IVBMXNamespaceManager,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
pushNodeContext: fn(
self: *const IVBMXNamespaceManager,
contextNode: ?*IXMLDOMNode,
fDeep: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
popContext: fn(
self: *const IVBMXNamespaceManager,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
declarePrefix: fn(
self: *const IVBMXNamespaceManager,
prefix: ?BSTR,
namespaceURI: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getDeclaredPrefixes: fn(
self: *const IVBMXNamespaceManager,
prefixes: ?*?*IMXNamespacePrefixes,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getPrefixes: fn(
self: *const IVBMXNamespaceManager,
namespaceURI: ?BSTR,
prefixes: ?*?*IMXNamespacePrefixes,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getURI: fn(
self: *const IVBMXNamespaceManager,
prefix: ?BSTR,
uri: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getURIFromNode: fn(
self: *const IVBMXNamespaceManager,
strPrefix: ?BSTR,
contextNode: ?*IXMLDOMNode,
uri: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBMXNamespaceManager_put_allowOverride(self: *const T, fOverride: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBMXNamespaceManager.VTable, self.vtable).put_allowOverride(@ptrCast(*const IVBMXNamespaceManager, self), fOverride);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBMXNamespaceManager_get_allowOverride(self: *const T, fOverride: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBMXNamespaceManager.VTable, self.vtable).get_allowOverride(@ptrCast(*const IVBMXNamespaceManager, self), fOverride);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBMXNamespaceManager_reset(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBMXNamespaceManager.VTable, self.vtable).reset(@ptrCast(*const IVBMXNamespaceManager, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBMXNamespaceManager_pushContext(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBMXNamespaceManager.VTable, self.vtable).pushContext(@ptrCast(*const IVBMXNamespaceManager, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBMXNamespaceManager_pushNodeContext(self: *const T, contextNode: ?*IXMLDOMNode, fDeep: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBMXNamespaceManager.VTable, self.vtable).pushNodeContext(@ptrCast(*const IVBMXNamespaceManager, self), contextNode, fDeep);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBMXNamespaceManager_popContext(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBMXNamespaceManager.VTable, self.vtable).popContext(@ptrCast(*const IVBMXNamespaceManager, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBMXNamespaceManager_declarePrefix(self: *const T, prefix: ?BSTR, namespaceURI: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBMXNamespaceManager.VTable, self.vtable).declarePrefix(@ptrCast(*const IVBMXNamespaceManager, self), prefix, namespaceURI);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBMXNamespaceManager_getDeclaredPrefixes(self: *const T, prefixes: ?*?*IMXNamespacePrefixes) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBMXNamespaceManager.VTable, self.vtable).getDeclaredPrefixes(@ptrCast(*const IVBMXNamespaceManager, self), prefixes);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBMXNamespaceManager_getPrefixes(self: *const T, namespaceURI: ?BSTR, prefixes: ?*?*IMXNamespacePrefixes) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBMXNamespaceManager.VTable, self.vtable).getPrefixes(@ptrCast(*const IVBMXNamespaceManager, self), namespaceURI, prefixes);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBMXNamespaceManager_getURI(self: *const T, prefix: ?BSTR, uri: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBMXNamespaceManager.VTable, self.vtable).getURI(@ptrCast(*const IVBMXNamespaceManager, self), prefix, uri);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IVBMXNamespaceManager_getURIFromNode(self: *const T, strPrefix: ?BSTR, contextNode: ?*IXMLDOMNode, uri: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IVBMXNamespaceManager.VTable, self.vtable).getURIFromNode(@ptrCast(*const IVBMXNamespaceManager, self), strPrefix, contextNode, uri);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IMXNamespaceManager_Value = @import("../../zig.zig").Guid.initString("c90352f6-643c-4fbc-bb23-e996eb2d51fd");
pub const IID_IMXNamespaceManager = &IID_IMXNamespaceManager_Value;
pub const IMXNamespaceManager = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
putAllowOverride: fn(
self: *const IMXNamespaceManager,
fOverride: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getAllowOverride: fn(
self: *const IMXNamespaceManager,
fOverride: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
reset: fn(
self: *const IMXNamespaceManager,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
pushContext: fn(
self: *const IMXNamespaceManager,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
pushNodeContext: fn(
self: *const IMXNamespaceManager,
contextNode: ?*IXMLDOMNode,
fDeep: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
popContext: fn(
self: *const IMXNamespaceManager,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
declarePrefix: fn(
self: *const IMXNamespaceManager,
prefix: ?[*:0]const u16,
namespaceURI: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getDeclaredPrefix: fn(
self: *const IMXNamespaceManager,
nIndex: i32,
pwchPrefix: [*:0]u16,
pcchPrefix: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getPrefix: fn(
self: *const IMXNamespaceManager,
pwszNamespaceURI: ?[*:0]const u16,
nIndex: i32,
pwchPrefix: [*:0]u16,
pcchPrefix: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getURI: fn(
self: *const IMXNamespaceManager,
pwchPrefix: ?[*:0]const u16,
pContextNode: ?*IXMLDOMNode,
pwchUri: [*:0]u16,
pcchUri: ?*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 IMXNamespaceManager_putAllowOverride(self: *const T, fOverride: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXNamespaceManager.VTable, self.vtable).putAllowOverride(@ptrCast(*const IMXNamespaceManager, self), fOverride);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXNamespaceManager_getAllowOverride(self: *const T, fOverride: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXNamespaceManager.VTable, self.vtable).getAllowOverride(@ptrCast(*const IMXNamespaceManager, self), fOverride);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXNamespaceManager_reset(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXNamespaceManager.VTable, self.vtable).reset(@ptrCast(*const IMXNamespaceManager, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXNamespaceManager_pushContext(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXNamespaceManager.VTable, self.vtable).pushContext(@ptrCast(*const IMXNamespaceManager, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXNamespaceManager_pushNodeContext(self: *const T, contextNode: ?*IXMLDOMNode, fDeep: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXNamespaceManager.VTable, self.vtable).pushNodeContext(@ptrCast(*const IMXNamespaceManager, self), contextNode, fDeep);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXNamespaceManager_popContext(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXNamespaceManager.VTable, self.vtable).popContext(@ptrCast(*const IMXNamespaceManager, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXNamespaceManager_declarePrefix(self: *const T, prefix: ?[*:0]const u16, namespaceURI: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXNamespaceManager.VTable, self.vtable).declarePrefix(@ptrCast(*const IMXNamespaceManager, self), prefix, namespaceURI);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXNamespaceManager_getDeclaredPrefix(self: *const T, nIndex: i32, pwchPrefix: [*:0]u16, pcchPrefix: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXNamespaceManager.VTable, self.vtable).getDeclaredPrefix(@ptrCast(*const IMXNamespaceManager, self), nIndex, pwchPrefix, pcchPrefix);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXNamespaceManager_getPrefix(self: *const T, pwszNamespaceURI: ?[*:0]const u16, nIndex: i32, pwchPrefix: [*:0]u16, pcchPrefix: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXNamespaceManager.VTable, self.vtable).getPrefix(@ptrCast(*const IMXNamespaceManager, self), pwszNamespaceURI, nIndex, pwchPrefix, pcchPrefix);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXNamespaceManager_getURI(self: *const T, pwchPrefix: ?[*:0]const u16, pContextNode: ?*IXMLDOMNode, pwchUri: [*:0]u16, pcchUri: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXNamespaceManager.VTable, self.vtable).getURI(@ptrCast(*const IMXNamespaceManager, self), pwchPrefix, pContextNode, pwchUri, pcchUri);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IMXXMLFilter_Value = @import("../../zig.zig").Guid.initString("c90352f7-643c-4fbc-bb23-e996eb2d51fd");
pub const IID_IMXXMLFilter = &IID_IMXXMLFilter_Value;
pub const IMXXMLFilter = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
getFeature: fn(
self: *const IMXXMLFilter,
strName: ?BSTR,
fValue: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
putFeature: fn(
self: *const IMXXMLFilter,
strName: ?BSTR,
fValue: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getProperty: fn(
self: *const IMXXMLFilter,
strName: ?BSTR,
varValue: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
putProperty: fn(
self: *const IMXXMLFilter,
strName: ?BSTR,
varValue: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_entityResolver: fn(
self: *const IMXXMLFilter,
oResolver: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
putref_entityResolver: fn(
self: *const IMXXMLFilter,
oResolver: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_contentHandler: fn(
self: *const IMXXMLFilter,
oHandler: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
putref_contentHandler: fn(
self: *const IMXXMLFilter,
oHandler: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_dtdHandler: fn(
self: *const IMXXMLFilter,
oHandler: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
putref_dtdHandler: fn(
self: *const IMXXMLFilter,
oHandler: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_errorHandler: fn(
self: *const IMXXMLFilter,
oHandler: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
putref_errorHandler: fn(
self: *const IMXXMLFilter,
oHandler: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXXMLFilter_getFeature(self: *const T, strName: ?BSTR, fValue: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXXMLFilter.VTable, self.vtable).getFeature(@ptrCast(*const IMXXMLFilter, self), strName, fValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXXMLFilter_putFeature(self: *const T, strName: ?BSTR, fValue: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXXMLFilter.VTable, self.vtable).putFeature(@ptrCast(*const IMXXMLFilter, self), strName, fValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXXMLFilter_getProperty(self: *const T, strName: ?BSTR, varValue: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXXMLFilter.VTable, self.vtable).getProperty(@ptrCast(*const IMXXMLFilter, self), strName, varValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXXMLFilter_putProperty(self: *const T, strName: ?BSTR, varValue: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXXMLFilter.VTable, self.vtable).putProperty(@ptrCast(*const IMXXMLFilter, self), strName, varValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXXMLFilter_get_entityResolver(self: *const T, oResolver: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXXMLFilter.VTable, self.vtable).get_entityResolver(@ptrCast(*const IMXXMLFilter, self), oResolver);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXXMLFilter_putref_entityResolver(self: *const T, oResolver: ?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXXMLFilter.VTable, self.vtable).putref_entityResolver(@ptrCast(*const IMXXMLFilter, self), oResolver);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXXMLFilter_get_contentHandler(self: *const T, oHandler: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXXMLFilter.VTable, self.vtable).get_contentHandler(@ptrCast(*const IMXXMLFilter, self), oHandler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXXMLFilter_putref_contentHandler(self: *const T, oHandler: ?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXXMLFilter.VTable, self.vtable).putref_contentHandler(@ptrCast(*const IMXXMLFilter, self), oHandler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXXMLFilter_get_dtdHandler(self: *const T, oHandler: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXXMLFilter.VTable, self.vtable).get_dtdHandler(@ptrCast(*const IMXXMLFilter, self), oHandler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXXMLFilter_putref_dtdHandler(self: *const T, oHandler: ?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXXMLFilter.VTable, self.vtable).putref_dtdHandler(@ptrCast(*const IMXXMLFilter, self), oHandler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXXMLFilter_get_errorHandler(self: *const T, oHandler: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXXMLFilter.VTable, self.vtable).get_errorHandler(@ptrCast(*const IMXXMLFilter, self), oHandler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IMXXMLFilter_putref_errorHandler(self: *const T, oHandler: ?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IMXXMLFilter.VTable, self.vtable).putref_errorHandler(@ptrCast(*const IMXXMLFilter, self), oHandler);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const SOMITEMTYPE = enum(i32) {
SCHEMA = 4096,
ATTRIBUTE = 4097,
ATTRIBUTEGROUP = 4098,
NOTATION = 4099,
ANNOTATION = 4100,
IDENTITYCONSTRAINT = 4352,
KEY = 4353,
KEYREF = 4354,
UNIQUE = 4355,
ANYTYPE = 8192,
DATATYPE = 8448,
DATATYPE_ANYTYPE = 8449,
DATATYPE_ANYURI = 8450,
DATATYPE_BASE64BINARY = 8451,
DATATYPE_BOOLEAN = 8452,
DATATYPE_BYTE = 8453,
DATATYPE_DATE = 8454,
DATATYPE_DATETIME = 8455,
DATATYPE_DAY = 8456,
DATATYPE_DECIMAL = 8457,
DATATYPE_DOUBLE = 8458,
DATATYPE_DURATION = 8459,
DATATYPE_ENTITIES = 8460,
DATATYPE_ENTITY = 8461,
DATATYPE_FLOAT = 8462,
DATATYPE_HEXBINARY = 8463,
DATATYPE_ID = 8464,
DATATYPE_IDREF = 8465,
DATATYPE_IDREFS = 8466,
DATATYPE_INT = 8467,
DATATYPE_INTEGER = 8468,
DATATYPE_LANGUAGE = 8469,
DATATYPE_LONG = 8470,
DATATYPE_MONTH = 8471,
DATATYPE_MONTHDAY = 8472,
DATATYPE_NAME = 8473,
DATATYPE_NCNAME = 8474,
DATATYPE_NEGATIVEINTEGER = 8475,
DATATYPE_NMTOKEN = 8476,
DATATYPE_NMTOKENS = 8477,
DATATYPE_NONNEGATIVEINTEGER = 8478,
DATATYPE_NONPOSITIVEINTEGER = 8479,
DATATYPE_NORMALIZEDSTRING = 8480,
DATATYPE_NOTATION = 8481,
DATATYPE_POSITIVEINTEGER = 8482,
DATATYPE_QNAME = 8483,
DATATYPE_SHORT = 8484,
DATATYPE_STRING = 8485,
DATATYPE_TIME = 8486,
DATATYPE_TOKEN = 8487,
DATATYPE_UNSIGNEDBYTE = 8488,
DATATYPE_UNSIGNEDINT = 8489,
DATATYPE_UNSIGNEDLONG = 8490,
DATATYPE_UNSIGNEDSHORT = 8491,
DATATYPE_YEAR = 8492,
DATATYPE_YEARMONTH = 8493,
DATATYPE_ANYSIMPLETYPE = 8703,
SIMPLETYPE = 8704,
COMPLEXTYPE = 9216,
PARTICLE = 16384,
ANY = 16385,
ANYATTRIBUTE = 16386,
ELEMENT = 16387,
GROUP = 16640,
ALL = 16641,
CHOICE = 16642,
SEQUENCE = 16643,
EMPTYPARTICLE = 16644,
NULL = 2048,
NULL_TYPE = 10240,
NULL_ANY = 18433,
NULL_ANYATTRIBUTE = 18434,
NULL_ELEMENT = 18435,
};
pub const SOMITEM_SCHEMA = SOMITEMTYPE.SCHEMA;
pub const SOMITEM_ATTRIBUTE = SOMITEMTYPE.ATTRIBUTE;
pub const SOMITEM_ATTRIBUTEGROUP = SOMITEMTYPE.ATTRIBUTEGROUP;
pub const SOMITEM_NOTATION = SOMITEMTYPE.NOTATION;
pub const SOMITEM_ANNOTATION = SOMITEMTYPE.ANNOTATION;
pub const SOMITEM_IDENTITYCONSTRAINT = SOMITEMTYPE.IDENTITYCONSTRAINT;
pub const SOMITEM_KEY = SOMITEMTYPE.KEY;
pub const SOMITEM_KEYREF = SOMITEMTYPE.KEYREF;
pub const SOMITEM_UNIQUE = SOMITEMTYPE.UNIQUE;
pub const SOMITEM_ANYTYPE = SOMITEMTYPE.ANYTYPE;
pub const SOMITEM_DATATYPE = SOMITEMTYPE.DATATYPE;
pub const SOMITEM_DATATYPE_ANYTYPE = SOMITEMTYPE.DATATYPE_ANYTYPE;
pub const SOMITEM_DATATYPE_ANYURI = SOMITEMTYPE.DATATYPE_ANYURI;
pub const SOMITEM_DATATYPE_BASE64BINARY = SOMITEMTYPE.DATATYPE_BASE64BINARY;
pub const SOMITEM_DATATYPE_BOOLEAN = SOMITEMTYPE.DATATYPE_BOOLEAN;
pub const SOMITEM_DATATYPE_BYTE = SOMITEMTYPE.DATATYPE_BYTE;
pub const SOMITEM_DATATYPE_DATE = SOMITEMTYPE.DATATYPE_DATE;
pub const SOMITEM_DATATYPE_DATETIME = SOMITEMTYPE.DATATYPE_DATETIME;
pub const SOMITEM_DATATYPE_DAY = SOMITEMTYPE.DATATYPE_DAY;
pub const SOMITEM_DATATYPE_DECIMAL = SOMITEMTYPE.DATATYPE_DECIMAL;
pub const SOMITEM_DATATYPE_DOUBLE = SOMITEMTYPE.DATATYPE_DOUBLE;
pub const SOMITEM_DATATYPE_DURATION = SOMITEMTYPE.DATATYPE_DURATION;
pub const SOMITEM_DATATYPE_ENTITIES = SOMITEMTYPE.DATATYPE_ENTITIES;
pub const SOMITEM_DATATYPE_ENTITY = SOMITEMTYPE.DATATYPE_ENTITY;
pub const SOMITEM_DATATYPE_FLOAT = SOMITEMTYPE.DATATYPE_FLOAT;
pub const SOMITEM_DATATYPE_HEXBINARY = SOMITEMTYPE.DATATYPE_HEXBINARY;
pub const SOMITEM_DATATYPE_ID = SOMITEMTYPE.DATATYPE_ID;
pub const SOMITEM_DATATYPE_IDREF = SOMITEMTYPE.DATATYPE_IDREF;
pub const SOMITEM_DATATYPE_IDREFS = SOMITEMTYPE.DATATYPE_IDREFS;
pub const SOMITEM_DATATYPE_INT = SOMITEMTYPE.DATATYPE_INT;
pub const SOMITEM_DATATYPE_INTEGER = SOMITEMTYPE.DATATYPE_INTEGER;
pub const SOMITEM_DATATYPE_LANGUAGE = SOMITEMTYPE.DATATYPE_LANGUAGE;
pub const SOMITEM_DATATYPE_LONG = SOMITEMTYPE.DATATYPE_LONG;
pub const SOMITEM_DATATYPE_MONTH = SOMITEMTYPE.DATATYPE_MONTH;
pub const SOMITEM_DATATYPE_MONTHDAY = SOMITEMTYPE.DATATYPE_MONTHDAY;
pub const SOMITEM_DATATYPE_NAME = SOMITEMTYPE.DATATYPE_NAME;
pub const SOMITEM_DATATYPE_NCNAME = SOMITEMTYPE.DATATYPE_NCNAME;
pub const SOMITEM_DATATYPE_NEGATIVEINTEGER = SOMITEMTYPE.DATATYPE_NEGATIVEINTEGER;
pub const SOMITEM_DATATYPE_NMTOKEN = SOMITEMTYPE.DATATYPE_NMTOKEN;
pub const SOMITEM_DATATYPE_NMTOKENS = SOMITEMTYPE.DATATYPE_NMTOKENS;
pub const SOMITEM_DATATYPE_NONNEGATIVEINTEGER = SOMITEMTYPE.DATATYPE_NONNEGATIVEINTEGER;
pub const SOMITEM_DATATYPE_NONPOSITIVEINTEGER = SOMITEMTYPE.DATATYPE_NONPOSITIVEINTEGER;
pub const SOMITEM_DATATYPE_NORMALIZEDSTRING = SOMITEMTYPE.DATATYPE_NORMALIZEDSTRING;
pub const SOMITEM_DATATYPE_NOTATION = SOMITEMTYPE.DATATYPE_NOTATION;
pub const SOMITEM_DATATYPE_POSITIVEINTEGER = SOMITEMTYPE.DATATYPE_POSITIVEINTEGER;
pub const SOMITEM_DATATYPE_QNAME = SOMITEMTYPE.DATATYPE_QNAME;
pub const SOMITEM_DATATYPE_SHORT = SOMITEMTYPE.DATATYPE_SHORT;
pub const SOMITEM_DATATYPE_STRING = SOMITEMTYPE.DATATYPE_STRING;
pub const SOMITEM_DATATYPE_TIME = SOMITEMTYPE.DATATYPE_TIME;
pub const SOMITEM_DATATYPE_TOKEN = SOMITEMTYPE.DATATYPE_TOKEN;
pub const SOMITEM_DATATYPE_UNSIGNEDBYTE = SOMITEMTYPE.DATATYPE_UNSIGNEDBYTE;
pub const SOMITEM_DATATYPE_UNSIGNEDINT = SOMITEMTYPE.DATATYPE_UNSIGNEDINT;
pub const SOMITEM_DATATYPE_UNSIGNEDLONG = SOMITEMTYPE.DATATYPE_UNSIGNEDLONG;
pub const SOMITEM_DATATYPE_UNSIGNEDSHORT = SOMITEMTYPE.DATATYPE_UNSIGNEDSHORT;
pub const SOMITEM_DATATYPE_YEAR = SOMITEMTYPE.DATATYPE_YEAR;
pub const SOMITEM_DATATYPE_YEARMONTH = SOMITEMTYPE.DATATYPE_YEARMONTH;
pub const SOMITEM_DATATYPE_ANYSIMPLETYPE = SOMITEMTYPE.DATATYPE_ANYSIMPLETYPE;
pub const SOMITEM_SIMPLETYPE = SOMITEMTYPE.SIMPLETYPE;
pub const SOMITEM_COMPLEXTYPE = SOMITEMTYPE.COMPLEXTYPE;
pub const SOMITEM_PARTICLE = SOMITEMTYPE.PARTICLE;
pub const SOMITEM_ANY = SOMITEMTYPE.ANY;
pub const SOMITEM_ANYATTRIBUTE = SOMITEMTYPE.ANYATTRIBUTE;
pub const SOMITEM_ELEMENT = SOMITEMTYPE.ELEMENT;
pub const SOMITEM_GROUP = SOMITEMTYPE.GROUP;
pub const SOMITEM_ALL = SOMITEMTYPE.ALL;
pub const SOMITEM_CHOICE = SOMITEMTYPE.CHOICE;
pub const SOMITEM_SEQUENCE = SOMITEMTYPE.SEQUENCE;
pub const SOMITEM_EMPTYPARTICLE = SOMITEMTYPE.EMPTYPARTICLE;
pub const SOMITEM_NULL = SOMITEMTYPE.NULL;
pub const SOMITEM_NULL_TYPE = SOMITEMTYPE.NULL_TYPE;
pub const SOMITEM_NULL_ANY = SOMITEMTYPE.NULL_ANY;
pub const SOMITEM_NULL_ANYATTRIBUTE = SOMITEMTYPE.NULL_ANYATTRIBUTE;
pub const SOMITEM_NULL_ELEMENT = SOMITEMTYPE.NULL_ELEMENT;
pub const SCHEMAUSE = enum(i32) {
OPTIONAL = 0,
PROHIBITED = 1,
REQUIRED = 2,
};
pub const SCHEMAUSE_OPTIONAL = SCHEMAUSE.OPTIONAL;
pub const SCHEMAUSE_PROHIBITED = SCHEMAUSE.PROHIBITED;
pub const SCHEMAUSE_REQUIRED = SCHEMAUSE.REQUIRED;
pub const SCHEMADERIVATIONMETHOD = enum(i32) {
EMPTY = 0,
SUBSTITUTION = 1,
EXTENSION = 2,
RESTRICTION = 4,
LIST = 8,
UNION = 16,
ALL = 255,
NONE = 256,
};
pub const SCHEMADERIVATIONMETHOD_EMPTY = SCHEMADERIVATIONMETHOD.EMPTY;
pub const SCHEMADERIVATIONMETHOD_SUBSTITUTION = SCHEMADERIVATIONMETHOD.SUBSTITUTION;
pub const SCHEMADERIVATIONMETHOD_EXTENSION = SCHEMADERIVATIONMETHOD.EXTENSION;
pub const SCHEMADERIVATIONMETHOD_RESTRICTION = SCHEMADERIVATIONMETHOD.RESTRICTION;
pub const SCHEMADERIVATIONMETHOD_LIST = SCHEMADERIVATIONMETHOD.LIST;
pub const SCHEMADERIVATIONMETHOD_UNION = SCHEMADERIVATIONMETHOD.UNION;
pub const SCHEMADERIVATIONMETHOD_ALL = SCHEMADERIVATIONMETHOD.ALL;
pub const SCHEMADERIVATIONMETHOD_NONE = SCHEMADERIVATIONMETHOD.NONE;
pub const SCHEMACONTENTTYPE = enum(i32) {
EMPTY = 0,
TEXTONLY = 1,
ELEMENTONLY = 2,
MIXED = 3,
};
pub const SCHEMACONTENTTYPE_EMPTY = SCHEMACONTENTTYPE.EMPTY;
pub const SCHEMACONTENTTYPE_TEXTONLY = SCHEMACONTENTTYPE.TEXTONLY;
pub const SCHEMACONTENTTYPE_ELEMENTONLY = SCHEMACONTENTTYPE.ELEMENTONLY;
pub const SCHEMACONTENTTYPE_MIXED = SCHEMACONTENTTYPE.MIXED;
pub const SCHEMAPROCESSCONTENTS = enum(i32) {
NONE = 0,
SKIP = 1,
LAX = 2,
STRICT = 3,
};
pub const SCHEMAPROCESSCONTENTS_NONE = SCHEMAPROCESSCONTENTS.NONE;
pub const SCHEMAPROCESSCONTENTS_SKIP = SCHEMAPROCESSCONTENTS.SKIP;
pub const SCHEMAPROCESSCONTENTS_LAX = SCHEMAPROCESSCONTENTS.LAX;
pub const SCHEMAPROCESSCONTENTS_STRICT = SCHEMAPROCESSCONTENTS.STRICT;
pub const SCHEMAWHITESPACE = enum(i32) {
NONE = -1,
PRESERVE = 0,
REPLACE = 1,
COLLAPSE = 2,
};
pub const SCHEMAWHITESPACE_NONE = SCHEMAWHITESPACE.NONE;
pub const SCHEMAWHITESPACE_PRESERVE = SCHEMAWHITESPACE.PRESERVE;
pub const SCHEMAWHITESPACE_REPLACE = SCHEMAWHITESPACE.REPLACE;
pub const SCHEMAWHITESPACE_COLLAPSE = SCHEMAWHITESPACE.COLLAPSE;
pub const SCHEMATYPEVARIETY = enum(i32) {
NONE = -1,
ATOMIC = 0,
LIST = 1,
UNION = 2,
};
pub const SCHEMATYPEVARIETY_NONE = SCHEMATYPEVARIETY.NONE;
pub const SCHEMATYPEVARIETY_ATOMIC = SCHEMATYPEVARIETY.ATOMIC;
pub const SCHEMATYPEVARIETY_LIST = SCHEMATYPEVARIETY.LIST;
pub const SCHEMATYPEVARIETY_UNION = SCHEMATYPEVARIETY.UNION;
const IID_IXMLDOMSchemaCollection2_Value = @import("../../zig.zig").Guid.initString("50ea08b0-dd1b-4664-9a50-c2f40f4bd79a");
pub const IID_IXMLDOMSchemaCollection2 = &IID_IXMLDOMSchemaCollection2_Value;
pub const IXMLDOMSchemaCollection2 = extern struct {
pub const VTable = extern struct {
base: IXMLDOMSchemaCollection.VTable,
validate: fn(
self: *const IXMLDOMSchemaCollection2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_validateOnLoad: fn(
self: *const IXMLDOMSchemaCollection2,
validateOnLoad: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_validateOnLoad: fn(
self: *const IXMLDOMSchemaCollection2,
validateOnLoad: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getSchema: fn(
self: *const IXMLDOMSchemaCollection2,
namespaceURI: ?BSTR,
schema: ?*?*ISchema,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getDeclaration: fn(
self: *const IXMLDOMSchemaCollection2,
node: ?*IXMLDOMNode,
item: ?*?*ISchemaItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IXMLDOMSchemaCollection.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMSchemaCollection2_validate(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMSchemaCollection2.VTable, self.vtable).validate(@ptrCast(*const IXMLDOMSchemaCollection2, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMSchemaCollection2_put_validateOnLoad(self: *const T, validateOnLoad: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMSchemaCollection2.VTable, self.vtable).put_validateOnLoad(@ptrCast(*const IXMLDOMSchemaCollection2, self), validateOnLoad);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMSchemaCollection2_get_validateOnLoad(self: *const T, validateOnLoad: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMSchemaCollection2.VTable, self.vtable).get_validateOnLoad(@ptrCast(*const IXMLDOMSchemaCollection2, self), validateOnLoad);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMSchemaCollection2_getSchema(self: *const T, namespaceURI: ?BSTR, schema: ?*?*ISchema) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMSchemaCollection2.VTable, self.vtable).getSchema(@ptrCast(*const IXMLDOMSchemaCollection2, self), namespaceURI, schema);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLDOMSchemaCollection2_getDeclaration(self: *const T, node: ?*IXMLDOMNode, item: ?*?*ISchemaItem) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLDOMSchemaCollection2.VTable, self.vtable).getDeclaration(@ptrCast(*const IXMLDOMSchemaCollection2, self), node, item);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ISchemaStringCollection_Value = @import("../../zig.zig").Guid.initString("50ea08b1-dd1b-4664-9a50-c2f40f4bd79a");
pub const IID_ISchemaStringCollection = &IID_ISchemaStringCollection_Value;
pub const ISchemaStringCollection = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_item: fn(
self: *const ISchemaStringCollection,
index: i32,
bstr: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_length: fn(
self: *const ISchemaStringCollection,
length: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get__newEnum: fn(
self: *const ISchemaStringCollection,
ppunk: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaStringCollection_get_item(self: *const T, index: i32, bstr: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaStringCollection.VTable, self.vtable).get_item(@ptrCast(*const ISchemaStringCollection, self), index, bstr);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaStringCollection_get_length(self: *const T, length: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaStringCollection.VTable, self.vtable).get_length(@ptrCast(*const ISchemaStringCollection, self), length);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaStringCollection_get__newEnum(self: *const T, ppunk: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaStringCollection.VTable, self.vtable).get__newEnum(@ptrCast(*const ISchemaStringCollection, self), ppunk);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ISchemaItemCollection_Value = @import("../../zig.zig").Guid.initString("50ea08b2-dd1b-4664-9a50-c2f40f4bd79a");
pub const IID_ISchemaItemCollection = &IID_ISchemaItemCollection_Value;
pub const ISchemaItemCollection = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_item: fn(
self: *const ISchemaItemCollection,
index: i32,
item: ?*?*ISchemaItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
itemByName: fn(
self: *const ISchemaItemCollection,
name: ?BSTR,
item: ?*?*ISchemaItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
itemByQName: fn(
self: *const ISchemaItemCollection,
name: ?BSTR,
namespaceURI: ?BSTR,
item: ?*?*ISchemaItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_length: fn(
self: *const ISchemaItemCollection,
length: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get__newEnum: fn(
self: *const ISchemaItemCollection,
ppunk: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaItemCollection_get_item(self: *const T, index: i32, item: ?*?*ISchemaItem) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaItemCollection.VTable, self.vtable).get_item(@ptrCast(*const ISchemaItemCollection, self), index, item);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaItemCollection_itemByName(self: *const T, name: ?BSTR, item: ?*?*ISchemaItem) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaItemCollection.VTable, self.vtable).itemByName(@ptrCast(*const ISchemaItemCollection, self), name, item);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaItemCollection_itemByQName(self: *const T, name: ?BSTR, namespaceURI: ?BSTR, item: ?*?*ISchemaItem) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaItemCollection.VTable, self.vtable).itemByQName(@ptrCast(*const ISchemaItemCollection, self), name, namespaceURI, item);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaItemCollection_get_length(self: *const T, length: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaItemCollection.VTable, self.vtable).get_length(@ptrCast(*const ISchemaItemCollection, self), length);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaItemCollection_get__newEnum(self: *const T, ppunk: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaItemCollection.VTable, self.vtable).get__newEnum(@ptrCast(*const ISchemaItemCollection, self), ppunk);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ISchemaItem_Value = @import("../../zig.zig").Guid.initString("50ea08b3-dd1b-4664-9a50-c2f40f4bd79a");
pub const IID_ISchemaItem = &IID_ISchemaItem_Value;
pub const ISchemaItem = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_name: fn(
self: *const ISchemaItem,
name: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_namespaceURI: fn(
self: *const ISchemaItem,
namespaceURI: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_schema: fn(
self: *const ISchemaItem,
schema: ?*?*ISchema,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_id: fn(
self: *const ISchemaItem,
id: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_itemType: fn(
self: *const ISchemaItem,
itemType: ?*SOMITEMTYPE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_unhandledAttributes: fn(
self: *const ISchemaItem,
attributes: ?*?*IVBSAXAttributes,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
writeAnnotation: fn(
self: *const ISchemaItem,
annotationSink: ?*IUnknown,
isWritten: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaItem_get_name(self: *const T, name: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaItem.VTable, self.vtable).get_name(@ptrCast(*const ISchemaItem, self), name);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaItem_get_namespaceURI(self: *const T, namespaceURI: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaItem.VTable, self.vtable).get_namespaceURI(@ptrCast(*const ISchemaItem, self), namespaceURI);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaItem_get_schema(self: *const T, schema: ?*?*ISchema) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaItem.VTable, self.vtable).get_schema(@ptrCast(*const ISchemaItem, self), schema);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaItem_get_id(self: *const T, id: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaItem.VTable, self.vtable).get_id(@ptrCast(*const ISchemaItem, self), id);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaItem_get_itemType(self: *const T, itemType: ?*SOMITEMTYPE) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaItem.VTable, self.vtable).get_itemType(@ptrCast(*const ISchemaItem, self), itemType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaItem_get_unhandledAttributes(self: *const T, attributes: ?*?*IVBSAXAttributes) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaItem.VTable, self.vtable).get_unhandledAttributes(@ptrCast(*const ISchemaItem, self), attributes);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaItem_writeAnnotation(self: *const T, annotationSink: ?*IUnknown, isWritten: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaItem.VTable, self.vtable).writeAnnotation(@ptrCast(*const ISchemaItem, self), annotationSink, isWritten);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ISchema_Value = @import("../../zig.zig").Guid.initString("50ea08b4-dd1b-4664-9a50-c2f40f4bd79a");
pub const IID_ISchema = &IID_ISchema_Value;
pub const ISchema = extern struct {
pub const VTable = extern struct {
base: ISchemaItem.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_targetNamespace: fn(
self: *const ISchema,
targetNamespace: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_version: fn(
self: *const ISchema,
version: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_types: fn(
self: *const ISchema,
types: ?*?*ISchemaItemCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_elements: fn(
self: *const ISchema,
elements: ?*?*ISchemaItemCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_attributes: fn(
self: *const ISchema,
attributes: ?*?*ISchemaItemCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_attributeGroups: fn(
self: *const ISchema,
attributeGroups: ?*?*ISchemaItemCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_modelGroups: fn(
self: *const ISchema,
modelGroups: ?*?*ISchemaItemCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_notations: fn(
self: *const ISchema,
notations: ?*?*ISchemaItemCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_schemaLocations: fn(
self: *const ISchema,
schemaLocations: ?*?*ISchemaStringCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace ISchemaItem.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchema_get_targetNamespace(self: *const T, targetNamespace: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchema.VTable, self.vtable).get_targetNamespace(@ptrCast(*const ISchema, self), targetNamespace);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchema_get_version(self: *const T, version: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchema.VTable, self.vtable).get_version(@ptrCast(*const ISchema, self), version);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchema_get_types(self: *const T, types: ?*?*ISchemaItemCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchema.VTable, self.vtable).get_types(@ptrCast(*const ISchema, self), types);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchema_get_elements(self: *const T, elements: ?*?*ISchemaItemCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchema.VTable, self.vtable).get_elements(@ptrCast(*const ISchema, self), elements);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchema_get_attributes(self: *const T, attributes: ?*?*ISchemaItemCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchema.VTable, self.vtable).get_attributes(@ptrCast(*const ISchema, self), attributes);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchema_get_attributeGroups(self: *const T, attributeGroups: ?*?*ISchemaItemCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchema.VTable, self.vtable).get_attributeGroups(@ptrCast(*const ISchema, self), attributeGroups);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchema_get_modelGroups(self: *const T, modelGroups: ?*?*ISchemaItemCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchema.VTable, self.vtable).get_modelGroups(@ptrCast(*const ISchema, self), modelGroups);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchema_get_notations(self: *const T, notations: ?*?*ISchemaItemCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchema.VTable, self.vtable).get_notations(@ptrCast(*const ISchema, self), notations);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchema_get_schemaLocations(self: *const T, schemaLocations: ?*?*ISchemaStringCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchema.VTable, self.vtable).get_schemaLocations(@ptrCast(*const ISchema, self), schemaLocations);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ISchemaParticle_Value = @import("../../zig.zig").Guid.initString("50ea08b5-dd1b-4664-9a50-c2f40f4bd79a");
pub const IID_ISchemaParticle = &IID_ISchemaParticle_Value;
pub const ISchemaParticle = extern struct {
pub const VTable = extern struct {
base: ISchemaItem.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_minOccurs: fn(
self: *const ISchemaParticle,
minOccurs: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_maxOccurs: fn(
self: *const ISchemaParticle,
maxOccurs: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace ISchemaItem.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaParticle_get_minOccurs(self: *const T, minOccurs: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaParticle.VTable, self.vtable).get_minOccurs(@ptrCast(*const ISchemaParticle, self), minOccurs);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaParticle_get_maxOccurs(self: *const T, maxOccurs: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaParticle.VTable, self.vtable).get_maxOccurs(@ptrCast(*const ISchemaParticle, self), maxOccurs);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ISchemaAttribute_Value = @import("../../zig.zig").Guid.initString("50ea08b6-dd1b-4664-9a50-c2f40f4bd79a");
pub const IID_ISchemaAttribute = &IID_ISchemaAttribute_Value;
pub const ISchemaAttribute = extern struct {
pub const VTable = extern struct {
base: ISchemaItem.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_type: fn(
self: *const ISchemaAttribute,
type: ?*?*ISchemaType,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_scope: fn(
self: *const ISchemaAttribute,
scope: ?*?*ISchemaComplexType,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_defaultValue: fn(
self: *const ISchemaAttribute,
defaultValue: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_fixedValue: fn(
self: *const ISchemaAttribute,
fixedValue: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_use: fn(
self: *const ISchemaAttribute,
use: ?*SCHEMAUSE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_isReference: fn(
self: *const ISchemaAttribute,
reference: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace ISchemaItem.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaAttribute_get_type(self: *const T, type_: ?*?*ISchemaType) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaAttribute.VTable, self.vtable).get_type(@ptrCast(*const ISchemaAttribute, self), type_);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaAttribute_get_scope(self: *const T, scope: ?*?*ISchemaComplexType) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaAttribute.VTable, self.vtable).get_scope(@ptrCast(*const ISchemaAttribute, self), scope);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaAttribute_get_defaultValue(self: *const T, defaultValue: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaAttribute.VTable, self.vtable).get_defaultValue(@ptrCast(*const ISchemaAttribute, self), defaultValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaAttribute_get_fixedValue(self: *const T, fixedValue: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaAttribute.VTable, self.vtable).get_fixedValue(@ptrCast(*const ISchemaAttribute, self), fixedValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaAttribute_get_use(self: *const T, use: ?*SCHEMAUSE) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaAttribute.VTable, self.vtable).get_use(@ptrCast(*const ISchemaAttribute, self), use);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaAttribute_get_isReference(self: *const T, reference: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaAttribute.VTable, self.vtable).get_isReference(@ptrCast(*const ISchemaAttribute, self), reference);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ISchemaElement_Value = @import("../../zig.zig").Guid.initString("50ea08b7-dd1b-4664-9a50-c2f40f4bd79a");
pub const IID_ISchemaElement = &IID_ISchemaElement_Value;
pub const ISchemaElement = extern struct {
pub const VTable = extern struct {
base: ISchemaParticle.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_type: fn(
self: *const ISchemaElement,
type: ?*?*ISchemaType,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_scope: fn(
self: *const ISchemaElement,
scope: ?*?*ISchemaComplexType,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_defaultValue: fn(
self: *const ISchemaElement,
defaultValue: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_fixedValue: fn(
self: *const ISchemaElement,
fixedValue: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_isNillable: fn(
self: *const ISchemaElement,
nillable: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_identityConstraints: fn(
self: *const ISchemaElement,
constraints: ?*?*ISchemaItemCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_substitutionGroup: fn(
self: *const ISchemaElement,
element: ?*?*ISchemaElement,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_substitutionGroupExclusions: fn(
self: *const ISchemaElement,
exclusions: ?*SCHEMADERIVATIONMETHOD,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_disallowedSubstitutions: fn(
self: *const ISchemaElement,
disallowed: ?*SCHEMADERIVATIONMETHOD,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_isAbstract: fn(
self: *const ISchemaElement,
abstract: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_isReference: fn(
self: *const ISchemaElement,
reference: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace ISchemaParticle.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaElement_get_type(self: *const T, type_: ?*?*ISchemaType) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaElement.VTable, self.vtable).get_type(@ptrCast(*const ISchemaElement, self), type_);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaElement_get_scope(self: *const T, scope: ?*?*ISchemaComplexType) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaElement.VTable, self.vtable).get_scope(@ptrCast(*const ISchemaElement, self), scope);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaElement_get_defaultValue(self: *const T, defaultValue: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaElement.VTable, self.vtable).get_defaultValue(@ptrCast(*const ISchemaElement, self), defaultValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaElement_get_fixedValue(self: *const T, fixedValue: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaElement.VTable, self.vtable).get_fixedValue(@ptrCast(*const ISchemaElement, self), fixedValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaElement_get_isNillable(self: *const T, nillable: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaElement.VTable, self.vtable).get_isNillable(@ptrCast(*const ISchemaElement, self), nillable);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaElement_get_identityConstraints(self: *const T, constraints: ?*?*ISchemaItemCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaElement.VTable, self.vtable).get_identityConstraints(@ptrCast(*const ISchemaElement, self), constraints);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaElement_get_substitutionGroup(self: *const T, element: ?*?*ISchemaElement) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaElement.VTable, self.vtable).get_substitutionGroup(@ptrCast(*const ISchemaElement, self), element);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaElement_get_substitutionGroupExclusions(self: *const T, exclusions: ?*SCHEMADERIVATIONMETHOD) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaElement.VTable, self.vtable).get_substitutionGroupExclusions(@ptrCast(*const ISchemaElement, self), exclusions);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaElement_get_disallowedSubstitutions(self: *const T, disallowed: ?*SCHEMADERIVATIONMETHOD) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaElement.VTable, self.vtable).get_disallowedSubstitutions(@ptrCast(*const ISchemaElement, self), disallowed);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaElement_get_isAbstract(self: *const T, abstract: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaElement.VTable, self.vtable).get_isAbstract(@ptrCast(*const ISchemaElement, self), abstract);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaElement_get_isReference(self: *const T, reference: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaElement.VTable, self.vtable).get_isReference(@ptrCast(*const ISchemaElement, self), reference);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ISchemaType_Value = @import("../../zig.zig").Guid.initString("50ea08b8-dd1b-4664-9a50-c2f40f4bd79a");
pub const IID_ISchemaType = &IID_ISchemaType_Value;
pub const ISchemaType = extern struct {
pub const VTable = extern struct {
base: ISchemaItem.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_baseTypes: fn(
self: *const ISchemaType,
baseTypes: ?*?*ISchemaItemCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_final: fn(
self: *const ISchemaType,
final: ?*SCHEMADERIVATIONMETHOD,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_variety: fn(
self: *const ISchemaType,
variety: ?*SCHEMATYPEVARIETY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_derivedBy: fn(
self: *const ISchemaType,
derivedBy: ?*SCHEMADERIVATIONMETHOD,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
isValid: fn(
self: *const ISchemaType,
data: ?BSTR,
valid: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_minExclusive: fn(
self: *const ISchemaType,
minExclusive: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_minInclusive: fn(
self: *const ISchemaType,
minInclusive: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_maxExclusive: fn(
self: *const ISchemaType,
maxExclusive: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_maxInclusive: fn(
self: *const ISchemaType,
maxInclusive: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_totalDigits: fn(
self: *const ISchemaType,
totalDigits: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_fractionDigits: fn(
self: *const ISchemaType,
fractionDigits: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_length: fn(
self: *const ISchemaType,
length: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_minLength: fn(
self: *const ISchemaType,
minLength: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_maxLength: fn(
self: *const ISchemaType,
maxLength: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_enumeration: fn(
self: *const ISchemaType,
enumeration: ?*?*ISchemaStringCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_whitespace: fn(
self: *const ISchemaType,
whitespace: ?*SCHEMAWHITESPACE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_patterns: fn(
self: *const ISchemaType,
patterns: ?*?*ISchemaStringCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace ISchemaItem.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaType_get_baseTypes(self: *const T, baseTypes: ?*?*ISchemaItemCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaType.VTable, self.vtable).get_baseTypes(@ptrCast(*const ISchemaType, self), baseTypes);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaType_get_final(self: *const T, final: ?*SCHEMADERIVATIONMETHOD) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaType.VTable, self.vtable).get_final(@ptrCast(*const ISchemaType, self), final);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaType_get_variety(self: *const T, variety: ?*SCHEMATYPEVARIETY) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaType.VTable, self.vtable).get_variety(@ptrCast(*const ISchemaType, self), variety);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaType_get_derivedBy(self: *const T, derivedBy: ?*SCHEMADERIVATIONMETHOD) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaType.VTable, self.vtable).get_derivedBy(@ptrCast(*const ISchemaType, self), derivedBy);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaType_isValid(self: *const T, data: ?BSTR, valid: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaType.VTable, self.vtable).isValid(@ptrCast(*const ISchemaType, self), data, valid);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaType_get_minExclusive(self: *const T, minExclusive: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaType.VTable, self.vtable).get_minExclusive(@ptrCast(*const ISchemaType, self), minExclusive);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaType_get_minInclusive(self: *const T, minInclusive: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaType.VTable, self.vtable).get_minInclusive(@ptrCast(*const ISchemaType, self), minInclusive);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaType_get_maxExclusive(self: *const T, maxExclusive: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaType.VTable, self.vtable).get_maxExclusive(@ptrCast(*const ISchemaType, self), maxExclusive);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaType_get_maxInclusive(self: *const T, maxInclusive: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaType.VTable, self.vtable).get_maxInclusive(@ptrCast(*const ISchemaType, self), maxInclusive);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaType_get_totalDigits(self: *const T, totalDigits: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaType.VTable, self.vtable).get_totalDigits(@ptrCast(*const ISchemaType, self), totalDigits);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaType_get_fractionDigits(self: *const T, fractionDigits: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaType.VTable, self.vtable).get_fractionDigits(@ptrCast(*const ISchemaType, self), fractionDigits);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaType_get_length(self: *const T, length: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaType.VTable, self.vtable).get_length(@ptrCast(*const ISchemaType, self), length);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaType_get_minLength(self: *const T, minLength: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaType.VTable, self.vtable).get_minLength(@ptrCast(*const ISchemaType, self), minLength);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaType_get_maxLength(self: *const T, maxLength: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaType.VTable, self.vtable).get_maxLength(@ptrCast(*const ISchemaType, self), maxLength);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaType_get_enumeration(self: *const T, enumeration: ?*?*ISchemaStringCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaType.VTable, self.vtable).get_enumeration(@ptrCast(*const ISchemaType, self), enumeration);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaType_get_whitespace(self: *const T, whitespace: ?*SCHEMAWHITESPACE) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaType.VTable, self.vtable).get_whitespace(@ptrCast(*const ISchemaType, self), whitespace);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaType_get_patterns(self: *const T, patterns: ?*?*ISchemaStringCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaType.VTable, self.vtable).get_patterns(@ptrCast(*const ISchemaType, self), patterns);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ISchemaComplexType_Value = @import("../../zig.zig").Guid.initString("50ea08b9-dd1b-4664-9a50-c2f40f4bd79a");
pub const IID_ISchemaComplexType = &IID_ISchemaComplexType_Value;
pub const ISchemaComplexType = extern struct {
pub const VTable = extern struct {
base: ISchemaType.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_isAbstract: fn(
self: *const ISchemaComplexType,
abstract: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_anyAttribute: fn(
self: *const ISchemaComplexType,
anyAttribute: ?*?*ISchemaAny,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_attributes: fn(
self: *const ISchemaComplexType,
attributes: ?*?*ISchemaItemCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_contentType: fn(
self: *const ISchemaComplexType,
contentType: ?*SCHEMACONTENTTYPE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_contentModel: fn(
self: *const ISchemaComplexType,
contentModel: ?*?*ISchemaModelGroup,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_prohibitedSubstitutions: fn(
self: *const ISchemaComplexType,
prohibited: ?*SCHEMADERIVATIONMETHOD,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace ISchemaType.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaComplexType_get_isAbstract(self: *const T, abstract: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaComplexType.VTable, self.vtable).get_isAbstract(@ptrCast(*const ISchemaComplexType, self), abstract);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaComplexType_get_anyAttribute(self: *const T, anyAttribute: ?*?*ISchemaAny) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaComplexType.VTable, self.vtable).get_anyAttribute(@ptrCast(*const ISchemaComplexType, self), anyAttribute);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaComplexType_get_attributes(self: *const T, attributes: ?*?*ISchemaItemCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaComplexType.VTable, self.vtable).get_attributes(@ptrCast(*const ISchemaComplexType, self), attributes);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaComplexType_get_contentType(self: *const T, contentType: ?*SCHEMACONTENTTYPE) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaComplexType.VTable, self.vtable).get_contentType(@ptrCast(*const ISchemaComplexType, self), contentType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaComplexType_get_contentModel(self: *const T, contentModel: ?*?*ISchemaModelGroup) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaComplexType.VTable, self.vtable).get_contentModel(@ptrCast(*const ISchemaComplexType, self), contentModel);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaComplexType_get_prohibitedSubstitutions(self: *const T, prohibited: ?*SCHEMADERIVATIONMETHOD) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaComplexType.VTable, self.vtable).get_prohibitedSubstitutions(@ptrCast(*const ISchemaComplexType, self), prohibited);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ISchemaAttributeGroup_Value = @import("../../zig.zig").Guid.initString("50ea08ba-dd1b-4664-9a50-c2f40f4bd79a");
pub const IID_ISchemaAttributeGroup = &IID_ISchemaAttributeGroup_Value;
pub const ISchemaAttributeGroup = extern struct {
pub const VTable = extern struct {
base: ISchemaItem.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_anyAttribute: fn(
self: *const ISchemaAttributeGroup,
anyAttribute: ?*?*ISchemaAny,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_attributes: fn(
self: *const ISchemaAttributeGroup,
attributes: ?*?*ISchemaItemCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace ISchemaItem.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaAttributeGroup_get_anyAttribute(self: *const T, anyAttribute: ?*?*ISchemaAny) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaAttributeGroup.VTable, self.vtable).get_anyAttribute(@ptrCast(*const ISchemaAttributeGroup, self), anyAttribute);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaAttributeGroup_get_attributes(self: *const T, attributes: ?*?*ISchemaItemCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaAttributeGroup.VTable, self.vtable).get_attributes(@ptrCast(*const ISchemaAttributeGroup, self), attributes);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ISchemaModelGroup_Value = @import("../../zig.zig").Guid.initString("50ea08bb-dd1b-4664-9a50-c2f40f4bd79a");
pub const IID_ISchemaModelGroup = &IID_ISchemaModelGroup_Value;
pub const ISchemaModelGroup = extern struct {
pub const VTable = extern struct {
base: ISchemaParticle.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_particles: fn(
self: *const ISchemaModelGroup,
particles: ?*?*ISchemaItemCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace ISchemaParticle.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaModelGroup_get_particles(self: *const T, particles: ?*?*ISchemaItemCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaModelGroup.VTable, self.vtable).get_particles(@ptrCast(*const ISchemaModelGroup, self), particles);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ISchemaAny_Value = @import("../../zig.zig").Guid.initString("50ea08bc-dd1b-4664-9a50-c2f40f4bd79a");
pub const IID_ISchemaAny = &IID_ISchemaAny_Value;
pub const ISchemaAny = extern struct {
pub const VTable = extern struct {
base: ISchemaParticle.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_namespaces: fn(
self: *const ISchemaAny,
namespaces: ?*?*ISchemaStringCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_processContents: fn(
self: *const ISchemaAny,
processContents: ?*SCHEMAPROCESSCONTENTS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace ISchemaParticle.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaAny_get_namespaces(self: *const T, namespaces: ?*?*ISchemaStringCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaAny.VTable, self.vtable).get_namespaces(@ptrCast(*const ISchemaAny, self), namespaces);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaAny_get_processContents(self: *const T, processContents: ?*SCHEMAPROCESSCONTENTS) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaAny.VTable, self.vtable).get_processContents(@ptrCast(*const ISchemaAny, self), processContents);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ISchemaIdentityConstraint_Value = @import("../../zig.zig").Guid.initString("50ea08bd-dd1b-4664-9a50-c2f40f4bd79a");
pub const IID_ISchemaIdentityConstraint = &IID_ISchemaIdentityConstraint_Value;
pub const ISchemaIdentityConstraint = extern struct {
pub const VTable = extern struct {
base: ISchemaItem.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_selector: fn(
self: *const ISchemaIdentityConstraint,
selector: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_fields: fn(
self: *const ISchemaIdentityConstraint,
fields: ?*?*ISchemaStringCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_referencedKey: fn(
self: *const ISchemaIdentityConstraint,
key: ?*?*ISchemaIdentityConstraint,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace ISchemaItem.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaIdentityConstraint_get_selector(self: *const T, selector: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaIdentityConstraint.VTable, self.vtable).get_selector(@ptrCast(*const ISchemaIdentityConstraint, self), selector);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaIdentityConstraint_get_fields(self: *const T, fields: ?*?*ISchemaStringCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaIdentityConstraint.VTable, self.vtable).get_fields(@ptrCast(*const ISchemaIdentityConstraint, self), fields);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaIdentityConstraint_get_referencedKey(self: *const T, key: ?*?*ISchemaIdentityConstraint) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaIdentityConstraint.VTable, self.vtable).get_referencedKey(@ptrCast(*const ISchemaIdentityConstraint, self), key);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ISchemaNotation_Value = @import("../../zig.zig").Guid.initString("50ea08be-dd1b-4664-9a50-c2f40f4bd79a");
pub const IID_ISchemaNotation = &IID_ISchemaNotation_Value;
pub const ISchemaNotation = extern struct {
pub const VTable = extern struct {
base: ISchemaItem.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_systemIdentifier: fn(
self: *const ISchemaNotation,
uri: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_publicIdentifier: fn(
self: *const ISchemaNotation,
uri: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace ISchemaItem.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaNotation_get_systemIdentifier(self: *const T, uri: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaNotation.VTable, self.vtable).get_systemIdentifier(@ptrCast(*const ISchemaNotation, self), uri);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchemaNotation_get_publicIdentifier(self: *const T, uri: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchemaNotation.VTable, self.vtable).get_publicIdentifier(@ptrCast(*const ISchemaNotation, self), uri);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const __msxml6_ReferenceRemainingTypes__ = extern struct {
__tagDomNodeType__: DOMNodeType,
__domNodeType__: DOMNodeType,
__serverXmlHttpOptionEnum__: SERVERXMLHTTP_OPTION,
__serverXmlHttpOption__: SERVERXMLHTTP_OPTION,
__serverCertOptionEnum__: SXH_SERVER_CERT_OPTION,
__serverCertOption__: SXH_SERVER_CERT_OPTION,
__proxySettingEnum__: SXH_PROXY_SETTING,
__proxySetting__: SXH_PROXY_SETTING,
__somItemTypeEnum__: SOMITEMTYPE,
__somItemType__: SOMITEMTYPE,
__schemaUseEnum__: SCHEMAUSE,
__schemaUse__: SCHEMAUSE,
__schemaDerivationMethodEnum__: SCHEMADERIVATIONMETHOD,
__schemaDerivationMethod__: SCHEMADERIVATIONMETHOD,
__schemaContentTypeEnum__: SCHEMACONTENTTYPE,
__schemaContentType__: SCHEMACONTENTTYPE,
__schemaProcessContentsEnum__: SCHEMAPROCESSCONTENTS,
__schemaProcessContents__: SCHEMAPROCESSCONTENTS,
__schemaWhitespaceEnum__: SCHEMAWHITESPACE,
__schemaWhitespace__: SCHEMAWHITESPACE,
__schemaTypeVarietyEnum__: SCHEMATYPEVARIETY,
__schemaTypeVariety__: SCHEMATYPEVARIETY,
};
pub const XHR_COOKIE_STATE = enum(i32) {
UNKNOWN = 0,
ACCEPT = 1,
PROMPT = 2,
LEASH = 3,
DOWNGRADE = 4,
REJECT = 5,
};
pub const XHR_COOKIE_STATE_UNKNOWN = XHR_COOKIE_STATE.UNKNOWN;
pub const XHR_COOKIE_STATE_ACCEPT = XHR_COOKIE_STATE.ACCEPT;
pub const XHR_COOKIE_STATE_PROMPT = XHR_COOKIE_STATE.PROMPT;
pub const XHR_COOKIE_STATE_LEASH = XHR_COOKIE_STATE.LEASH;
pub const XHR_COOKIE_STATE_DOWNGRADE = XHR_COOKIE_STATE.DOWNGRADE;
pub const XHR_COOKIE_STATE_REJECT = XHR_COOKIE_STATE.REJECT;
pub const XHR_COOKIE_FLAG = enum(i32) {
IS_SECURE = 1,
IS_SESSION = 2,
THIRD_PARTY = 16,
PROMPT_REQUIRED = 32,
EVALUATE_P3P = 64,
APPLY_P3P = 128,
P3P_ENABLED = 256,
IS_RESTRICTED = 512,
IE6 = 1024,
IS_LEGACY = 2048,
NON_SCRIPT = 4096,
HTTPONLY = 8192,
};
pub const XHR_COOKIE_IS_SECURE = XHR_COOKIE_FLAG.IS_SECURE;
pub const XHR_COOKIE_IS_SESSION = XHR_COOKIE_FLAG.IS_SESSION;
pub const XHR_COOKIE_THIRD_PARTY = XHR_COOKIE_FLAG.THIRD_PARTY;
pub const XHR_COOKIE_PROMPT_REQUIRED = XHR_COOKIE_FLAG.PROMPT_REQUIRED;
pub const XHR_COOKIE_EVALUATE_P3P = XHR_COOKIE_FLAG.EVALUATE_P3P;
pub const XHR_COOKIE_APPLY_P3P = XHR_COOKIE_FLAG.APPLY_P3P;
pub const XHR_COOKIE_P3P_ENABLED = XHR_COOKIE_FLAG.P3P_ENABLED;
pub const XHR_COOKIE_IS_RESTRICTED = XHR_COOKIE_FLAG.IS_RESTRICTED;
pub const XHR_COOKIE_IE6 = XHR_COOKIE_FLAG.IE6;
pub const XHR_COOKIE_IS_LEGACY = XHR_COOKIE_FLAG.IS_LEGACY;
pub const XHR_COOKIE_NON_SCRIPT = XHR_COOKIE_FLAG.NON_SCRIPT;
pub const XHR_COOKIE_HTTPONLY = XHR_COOKIE_FLAG.HTTPONLY;
pub const XHR_CRED_PROMPT = enum(i32) {
ALL = 0,
NONE = 1,
PROXY = 2,
};
pub const XHR_CRED_PROMPT_ALL = XHR_CRED_PROMPT.ALL;
pub const XHR_CRED_PROMPT_NONE = XHR_CRED_PROMPT.NONE;
pub const XHR_CRED_PROMPT_PROXY = XHR_CRED_PROMPT.PROXY;
pub const XHR_AUTH = enum(i32) {
ALL = 0,
NONE = 1,
PROXY = 2,
};
pub const XHR_AUTH_ALL = XHR_AUTH.ALL;
pub const XHR_AUTH_NONE = XHR_AUTH.NONE;
pub const XHR_AUTH_PROXY = XHR_AUTH.PROXY;
pub const XHR_PROPERTY = enum(i32) {
NO_CRED_PROMPT = 0,
NO_AUTH = 1,
TIMEOUT = 2,
NO_DEFAULT_HEADERS = 3,
REPORT_REDIRECT_STATUS = 4,
NO_CACHE = 5,
EXTENDED_ERROR = 6,
QUERY_STRING_UTF8 = 7,
IGNORE_CERT_ERRORS = 8,
ONDATA_THRESHOLD = 9,
SET_ENTERPRISEID = 10,
MAX_CONNECTIONS = 11,
};
pub const XHR_PROP_NO_CRED_PROMPT = XHR_PROPERTY.NO_CRED_PROMPT;
pub const XHR_PROP_NO_AUTH = XHR_PROPERTY.NO_AUTH;
pub const XHR_PROP_TIMEOUT = XHR_PROPERTY.TIMEOUT;
pub const XHR_PROP_NO_DEFAULT_HEADERS = XHR_PROPERTY.NO_DEFAULT_HEADERS;
pub const XHR_PROP_REPORT_REDIRECT_STATUS = XHR_PROPERTY.REPORT_REDIRECT_STATUS;
pub const XHR_PROP_NO_CACHE = XHR_PROPERTY.NO_CACHE;
pub const XHR_PROP_EXTENDED_ERROR = XHR_PROPERTY.EXTENDED_ERROR;
pub const XHR_PROP_QUERY_STRING_UTF8 = XHR_PROPERTY.QUERY_STRING_UTF8;
pub const XHR_PROP_IGNORE_CERT_ERRORS = XHR_PROPERTY.IGNORE_CERT_ERRORS;
pub const XHR_PROP_ONDATA_THRESHOLD = XHR_PROPERTY.ONDATA_THRESHOLD;
pub const XHR_PROP_SET_ENTERPRISEID = XHR_PROPERTY.SET_ENTERPRISEID;
pub const XHR_PROP_MAX_CONNECTIONS = XHR_PROPERTY.MAX_CONNECTIONS;
pub const XHR_CERT_IGNORE_FLAG = enum(u32) {
REVOCATION_FAILED = 128,
UNKNOWN_CA = 256,
CERT_CN_INVALID = 4096,
CERT_DATE_INVALID = 8192,
ALL_SERVER_ERRORS = 12672,
};
pub const XHR_CERT_IGNORE_REVOCATION_FAILED = XHR_CERT_IGNORE_FLAG.REVOCATION_FAILED;
pub const XHR_CERT_IGNORE_UNKNOWN_CA = XHR_CERT_IGNORE_FLAG.UNKNOWN_CA;
pub const XHR_CERT_IGNORE_CERT_CN_INVALID = XHR_CERT_IGNORE_FLAG.CERT_CN_INVALID;
pub const XHR_CERT_IGNORE_CERT_DATE_INVALID = XHR_CERT_IGNORE_FLAG.CERT_DATE_INVALID;
pub const XHR_CERT_IGNORE_ALL_SERVER_ERRORS = XHR_CERT_IGNORE_FLAG.ALL_SERVER_ERRORS;
pub const XHR_CERT_ERROR_FLAG = enum(u32) {
REVOCATION_FAILED = 8388608,
UNKNOWN_CA = 16777216,
CERT_CN_INVALID = 33554432,
CERT_DATE_INVALID = 67108864,
ALL_SERVER_ERRORS = 125829120,
};
pub const XHR_CERT_ERROR_REVOCATION_FAILED = XHR_CERT_ERROR_FLAG.REVOCATION_FAILED;
pub const XHR_CERT_ERROR_UNKNOWN_CA = XHR_CERT_ERROR_FLAG.UNKNOWN_CA;
pub const XHR_CERT_ERROR_CERT_CN_INVALID = XHR_CERT_ERROR_FLAG.CERT_CN_INVALID;
pub const XHR_CERT_ERROR_CERT_DATE_INVALID = XHR_CERT_ERROR_FLAG.CERT_DATE_INVALID;
pub const XHR_CERT_ERROR_ALL_SERVER_ERRORS = XHR_CERT_ERROR_FLAG.ALL_SERVER_ERRORS;
pub const XHR_COOKIE = extern struct {
pwszUrl: ?PWSTR,
pwszName: ?PWSTR,
pwszValue: ?PWSTR,
pwszP3PPolicy: ?PWSTR,
ftExpires: FILETIME,
dwFlags: u32,
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IXMLHTTPRequest2Callback_Value = @import("../../zig.zig").Guid.initString("a44a9299-e321-40de-8866-341b41669162");
pub const IID_IXMLHTTPRequest2Callback = &IID_IXMLHTTPRequest2Callback_Value;
pub const IXMLHTTPRequest2Callback = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
OnRedirect: fn(
self: *const IXMLHTTPRequest2Callback,
pXHR: ?*IXMLHTTPRequest2,
pwszRedirectUrl: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
OnHeadersAvailable: fn(
self: *const IXMLHTTPRequest2Callback,
pXHR: ?*IXMLHTTPRequest2,
dwStatus: u32,
pwszStatus: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
OnDataAvailable: fn(
self: *const IXMLHTTPRequest2Callback,
pXHR: ?*IXMLHTTPRequest2,
pResponseStream: ?*ISequentialStream,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
OnResponseReceived: fn(
self: *const IXMLHTTPRequest2Callback,
pXHR: ?*IXMLHTTPRequest2,
pResponseStream: ?*ISequentialStream,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
OnError: fn(
self: *const IXMLHTTPRequest2Callback,
pXHR: ?*IXMLHTTPRequest2,
hrError: 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 IXMLHTTPRequest2Callback_OnRedirect(self: *const T, pXHR: ?*IXMLHTTPRequest2, pwszRedirectUrl: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHTTPRequest2Callback.VTable, self.vtable).OnRedirect(@ptrCast(*const IXMLHTTPRequest2Callback, self), pXHR, pwszRedirectUrl);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHTTPRequest2Callback_OnHeadersAvailable(self: *const T, pXHR: ?*IXMLHTTPRequest2, dwStatus: u32, pwszStatus: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHTTPRequest2Callback.VTable, self.vtable).OnHeadersAvailable(@ptrCast(*const IXMLHTTPRequest2Callback, self), pXHR, dwStatus, pwszStatus);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHTTPRequest2Callback_OnDataAvailable(self: *const T, pXHR: ?*IXMLHTTPRequest2, pResponseStream: ?*ISequentialStream) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHTTPRequest2Callback.VTable, self.vtable).OnDataAvailable(@ptrCast(*const IXMLHTTPRequest2Callback, self), pXHR, pResponseStream);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHTTPRequest2Callback_OnResponseReceived(self: *const T, pXHR: ?*IXMLHTTPRequest2, pResponseStream: ?*ISequentialStream) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHTTPRequest2Callback.VTable, self.vtable).OnResponseReceived(@ptrCast(*const IXMLHTTPRequest2Callback, self), pXHR, pResponseStream);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHTTPRequest2Callback_OnError(self: *const T, pXHR: ?*IXMLHTTPRequest2, hrError: HRESULT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHTTPRequest2Callback.VTable, self.vtable).OnError(@ptrCast(*const IXMLHTTPRequest2Callback, self), pXHR, hrError);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IXMLHTTPRequest2_Value = @import("../../zig.zig").Guid.initString("e5d37dc0-552a-4d52-9cc0-a14d546fbd04");
pub const IID_IXMLHTTPRequest2 = &IID_IXMLHTTPRequest2_Value;
pub const IXMLHTTPRequest2 = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Open: fn(
self: *const IXMLHTTPRequest2,
pwszMethod: ?[*:0]const u16,
pwszUrl: ?[*:0]const u16,
pStatusCallback: ?*IXMLHTTPRequest2Callback,
pwszUserName: ?[*:0]const u16,
pwszPassword: ?[*:0]const u16,
pwszProxyUserName: ?[*:0]const u16,
pwszProxyPassword: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Send: fn(
self: *const IXMLHTTPRequest2,
pBody: ?*ISequentialStream,
cbBody: u64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Abort: fn(
self: *const IXMLHTTPRequest2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetCookie: fn(
self: *const IXMLHTTPRequest2,
pCookie: ?*const XHR_COOKIE,
pdwCookieState: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetCustomResponseStream: fn(
self: *const IXMLHTTPRequest2,
pSequentialStream: ?*ISequentialStream,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetProperty: fn(
self: *const IXMLHTTPRequest2,
eProperty: XHR_PROPERTY,
ullValue: u64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetRequestHeader: fn(
self: *const IXMLHTTPRequest2,
pwszHeader: ?[*:0]const u16,
pwszValue: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetAllResponseHeaders: fn(
self: *const IXMLHTTPRequest2,
ppwszHeaders: ?*?*u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCookie: fn(
self: *const IXMLHTTPRequest2,
pwszUrl: ?[*:0]const u16,
pwszName: ?[*:0]const u16,
dwFlags: u32,
pcCookies: ?*u32,
ppCookies: [*]?*XHR_COOKIE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetResponseHeader: fn(
self: *const IXMLHTTPRequest2,
pwszHeader: ?[*:0]const u16,
ppwszValue: ?*?*u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHTTPRequest2_Open(self: *const T, pwszMethod: ?[*:0]const u16, pwszUrl: ?[*:0]const u16, pStatusCallback: ?*IXMLHTTPRequest2Callback, pwszUserName: ?[*:0]const u16, pwszPassword: ?[*:0]const u16, pwszProxyUserName: ?[*:0]const u16, pwszProxyPassword: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHTTPRequest2.VTable, self.vtable).Open(@ptrCast(*const IXMLHTTPRequest2, self), pwszMethod, pwszUrl, pStatusCallback, pwszUserName, pwszPassword, pwszProxyUserName, pwszProxyPassword);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHTTPRequest2_Send(self: *const T, pBody: ?*ISequentialStream, cbBody: u64) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHTTPRequest2.VTable, self.vtable).Send(@ptrCast(*const IXMLHTTPRequest2, self), pBody, cbBody);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHTTPRequest2_Abort(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHTTPRequest2.VTable, self.vtable).Abort(@ptrCast(*const IXMLHTTPRequest2, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHTTPRequest2_SetCookie(self: *const T, pCookie: ?*const XHR_COOKIE, pdwCookieState: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHTTPRequest2.VTable, self.vtable).SetCookie(@ptrCast(*const IXMLHTTPRequest2, self), pCookie, pdwCookieState);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHTTPRequest2_SetCustomResponseStream(self: *const T, pSequentialStream: ?*ISequentialStream) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHTTPRequest2.VTable, self.vtable).SetCustomResponseStream(@ptrCast(*const IXMLHTTPRequest2, self), pSequentialStream);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHTTPRequest2_SetProperty(self: *const T, eProperty: XHR_PROPERTY, ullValue: u64) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHTTPRequest2.VTable, self.vtable).SetProperty(@ptrCast(*const IXMLHTTPRequest2, self), eProperty, ullValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHTTPRequest2_SetRequestHeader(self: *const T, pwszHeader: ?[*:0]const u16, pwszValue: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHTTPRequest2.VTable, self.vtable).SetRequestHeader(@ptrCast(*const IXMLHTTPRequest2, self), pwszHeader, pwszValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHTTPRequest2_GetAllResponseHeaders(self: *const T, ppwszHeaders: ?*?*u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHTTPRequest2.VTable, self.vtable).GetAllResponseHeaders(@ptrCast(*const IXMLHTTPRequest2, self), ppwszHeaders);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHTTPRequest2_GetCookie(self: *const T, pwszUrl: ?[*:0]const u16, pwszName: ?[*:0]const u16, dwFlags: u32, pcCookies: ?*u32, ppCookies: [*]?*XHR_COOKIE) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHTTPRequest2.VTable, self.vtable).GetCookie(@ptrCast(*const IXMLHTTPRequest2, self), pwszUrl, pwszName, dwFlags, pcCookies, ppCookies);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHTTPRequest2_GetResponseHeader(self: *const T, pwszHeader: ?[*:0]const u16, ppwszValue: ?*?*u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHTTPRequest2.VTable, self.vtable).GetResponseHeader(@ptrCast(*const IXMLHTTPRequest2, self), pwszHeader, ppwszValue);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const XHR_CERT = extern struct {
cbCert: u32,
pbCert: ?*u8,
};
// TODO: this type is limited to platform 'windows8.1'
const IID_IXMLHTTPRequest3Callback_Value = @import("../../zig.zig").Guid.initString("b9e57830-8c6c-4a6f-9c13-47772bb047bb");
pub const IID_IXMLHTTPRequest3Callback = &IID_IXMLHTTPRequest3Callback_Value;
pub const IXMLHTTPRequest3Callback = extern struct {
pub const VTable = extern struct {
base: IXMLHTTPRequest2Callback.VTable,
OnServerCertificateReceived: fn(
self: *const IXMLHTTPRequest3Callback,
pXHR: ?*IXMLHTTPRequest3,
dwCertificateErrors: u32,
cServerCertificateChain: u32,
rgServerCertificateChain: [*]const XHR_CERT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
OnClientCertificateRequested: fn(
self: *const IXMLHTTPRequest3Callback,
pXHR: ?*IXMLHTTPRequest3,
cIssuerList: u32,
rgpwszIssuerList: [*]const ?*const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IXMLHTTPRequest2Callback.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHTTPRequest3Callback_OnServerCertificateReceived(self: *const T, pXHR: ?*IXMLHTTPRequest3, dwCertificateErrors: u32, cServerCertificateChain: u32, rgServerCertificateChain: [*]const XHR_CERT) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHTTPRequest3Callback.VTable, self.vtable).OnServerCertificateReceived(@ptrCast(*const IXMLHTTPRequest3Callback, self), pXHR, dwCertificateErrors, cServerCertificateChain, rgServerCertificateChain);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHTTPRequest3Callback_OnClientCertificateRequested(self: *const T, pXHR: ?*IXMLHTTPRequest3, cIssuerList: u32, rgpwszIssuerList: [*]const ?*const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHTTPRequest3Callback.VTable, self.vtable).OnClientCertificateRequested(@ptrCast(*const IXMLHTTPRequest3Callback, self), pXHR, cIssuerList, rgpwszIssuerList);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.1'
const IID_IXMLHTTPRequest3_Value = @import("../../zig.zig").Guid.initString("a1c9feee-0617-4f23-9d58-8961ea43567c");
pub const IID_IXMLHTTPRequest3 = &IID_IXMLHTTPRequest3_Value;
pub const IXMLHTTPRequest3 = extern struct {
pub const VTable = extern struct {
base: IXMLHTTPRequest2.VTable,
SetClientCertificate: fn(
self: *const IXMLHTTPRequest3,
cbClientCertificateHash: u32,
pbClientCertificateHash: [*:0]const u8,
pwszPin: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IXMLHTTPRequest2.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXMLHTTPRequest3_SetClientCertificate(self: *const T, cbClientCertificateHash: u32, pbClientCertificateHash: [*:0]const u8, pwszPin: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXMLHTTPRequest3.VTable, self.vtable).SetClientCertificate(@ptrCast(*const IXMLHTTPRequest3, self), cbClientCertificateHash, pbClientCertificateHash, pwszPin);
}
};}
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 (9)
//--------------------------------------------------------------------------------
const BOOL = @import("../../foundation.zig").BOOL;
const BSTR = @import("../../foundation.zig").BSTR;
const FILETIME = @import("../../foundation.zig").FILETIME;
const HRESULT = @import("../../foundation.zig").HRESULT;
const IDispatch = @import("../../system/ole_automation.zig").IDispatch;
const ISequentialStream = @import("../../storage/structured_storage.zig").ISequentialStream;
const IUnknown = @import("../../system/com.zig").IUnknown;
const PWSTR = @import("../../foundation.zig").PWSTR;
const VARIANT = @import("../../system/ole_automation.zig").VARIANT;
test {
@setEvalBranchQuota(
@import("std").meta.declarations(@This()).len * 3
);
// reference all the pub declarations
if (!@import("builtin").is_test) return;
inline for (@import("std").meta.declarations(@This())) |decl| {
if (decl.is_pub) {
_ = decl;
}
}
} | deps/zigwin32/win32/data/xml/ms_xml.zig |
const std = @import("std");
/// Returns a struct consisting of an array `index` and a semi-unique `cycle`,
/// which exists to distinguish handles with the same array `index`.
///
/// The `cycle` value is only unique within the incremental period of an
/// unsigned integer with `cycle_bits`, so a larger number of `cycle_bits`
/// provides a larger scope of identifiable conflicts between handles for the
/// same `index`.
///
/// `Handle` is generic because while the `{ index, cycle }` pattern is widely
/// applicable, a good distribution of bits between `index` and `cycle` and the
/// overall size of a handle are highly dependent on the lifecycle of the
/// resource being identified by a handle and the systems consuming handles.
///
/// Reasonable values for `index_bits` depend on the maximum number of
/// uniquely identifiable resources your API will to identify with handles.
/// Generally this is directly tied to the length of the array(s) in which
/// you will store data to be referenced by a handle's `index`.
///
/// Reasonable values for `cycle_bits` depend on the frequency with which your
/// API expects to be issuing handles, and how many cycles of your application
/// are likely to elapse before an expired handle will likely no longer be
/// retained by the API caller's data structures.
///
/// For example, a `Handle(16, 16)` may be sufficient for a GPU resource like
/// a texture or buffer, where 64k instances of that resource is a reasonable
/// upper bound.
///
/// A `Handle(22, 10)` may be more appropriate to identify an entity in a
/// system where we can safely assume that 4 million entities, is a lot, and
/// that API callers can discover and discard expired entity handles within
/// 1024 frames of an entity being destroyed and its handle's `index` being
/// reissued for use by a distinct entity.
///
/// `TResource` identifies type of resource referenced by a handle, and
/// provides a type-safe distinction between two otherwise equivalently
/// configured `Handle` types, such as:
/// * `const BufferHandle = Handle(16, 16, Buffer);`
/// * `const TextureHandle = Handle(16, 16, Texture);`
///
/// The total size of a handle will always be the size of an addressable
/// unsigned integer of type `u8`, `u16`, `u32`, `u64`, `u128`, or `u256`.
pub fn Handle(
comptime index_bits: u8,
comptime cycle_bits: u8,
comptime TResource: type,
) type {
if (index_bits == 0) @compileError("index_bits must be greater than 0");
if (cycle_bits == 0) @compileError("cycle_bits must be greater than 0");
const id_bits: u16 = @as(u16, index_bits) + @as(u16, cycle_bits);
const Id = switch (id_bits) {
8 => u8,
16 => u16,
32 => u32,
64 => u64,
128 => u128,
256 => u256,
else => @compileError("index_bits + cycle_bits must sum to exactly " ++
"8, 16, 32, 64, 128, or 256 bits"),
};
const field_bits = std.math.max(index_bits, cycle_bits);
const utils = @import("utils.zig");
const UInt = utils.UInt;
const AddressableUInt = utils.AddressableUInt;
return struct {
const Self = @This();
const HandleType = Self;
const IndexType = UInt(index_bits);
const CycleType = UInt(cycle_bits);
const HandleUnion = extern union {
id: Id,
bits: packed struct {
cycle: CycleType, // least significant bits
index: IndexType, // most significant bits
},
};
pub const Resource = TResource;
pub const AddressableCycle = AddressableUInt(field_bits);
pub const AddressableIndex = AddressableUInt(field_bits);
pub const max_cycle = ~@as(CycleType, 0);
pub const max_index = ~@as(IndexType, 0);
pub const max_count = @as(Id, max_index - 1) + 2;
id: Id = 0,
pub const nil = Self{ .id = 0 };
pub fn init(i: IndexType, c: CycleType) Self {
var u = HandleUnion{ .bits = .{
.cycle = c,
.index = i,
} };
return .{ .id = u.id };
}
pub fn cycle(self: Self) CycleType {
var u = HandleUnion{ .id = self.id };
return u.bits.cycle;
}
pub fn index(self: Self) IndexType {
var u = HandleUnion{ .id = self.id };
return u.bits.index;
}
/// Unpacks the `index` and `cycle` bit fields that comprise
/// `Handle.id` into an `AddressableHandle`, which stores
/// the `index` and `cycle` values in pointer-addressable fields.
pub fn addressable(self: Self) AddressableHandle {
var u = HandleUnion{ .id = self.id };
return .{
.cycle = u.bits.cycle,
.index = u.bits.index,
};
}
/// When you want to directly access the `index` and `cycle` of a
/// handle, first convert it to an `AddressableHandle` by calling
/// `Handle.addressable()`.
/// An `AddressableHandle` can be converted back into a "compact"
/// `Handle` by calling `AddressableHandle.compact()`.
pub const AddressableHandle = struct {
cycle: AddressableCycle = 0,
index: AddressableIndex = 0,
/// Returns the corresponding `Handle`
pub fn handle(self: AddressableHandle) HandleType {
var u = HandleUnion{ .bits = .{
.cycle = @intCast(CycleType, self.cycle),
.index = @intCast(IndexType, self.index),
} };
return .{ .id = u.id };
}
};
pub fn format(
self: Self,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = fmt;
_ = options;
const n = @typeName(Resource);
const a = self.addressable();
return writer.print("{s}[{}#{}]", .{ n, a.index, a.cycle });
}
};
}
////////////////////////////////////////////////////////////////////////////////
test "Handle sizes and alignments" {
const expectEqual = std.testing.expectEqual;
{
const H = Handle(4, 4, void);
try expectEqual(@sizeOf(u8), @sizeOf(H));
try expectEqual(@alignOf(u8), @alignOf(H));
try expectEqual(4, @bitSizeOf(H.IndexType));
try expectEqual(4, @bitSizeOf(H.CycleType));
try expectEqual(8, @bitSizeOf(H.AddressableIndex));
try expectEqual(8, @bitSizeOf(H.AddressableCycle));
const A = H.AddressableHandle;
try expectEqual(@sizeOf(u16), @sizeOf(A));
try expectEqual(@alignOf(u8), @alignOf(A));
}
{
const H = Handle(6, 2, void);
try expectEqual(@sizeOf(u8), @sizeOf(H));
try expectEqual(@alignOf(u8), @alignOf(H));
try expectEqual(6, @bitSizeOf(H.IndexType));
try expectEqual(2, @bitSizeOf(H.CycleType));
try expectEqual(8, @bitSizeOf(H.AddressableIndex));
try expectEqual(8, @bitSizeOf(H.AddressableCycle));
const A = H.AddressableHandle;
try expectEqual(@sizeOf(u16), @sizeOf(A));
try expectEqual(@alignOf(u8), @alignOf(A));
}
{
const H = Handle(8, 8, void);
try expectEqual(@sizeOf(u16), @sizeOf(H));
try expectEqual(@alignOf(u16), @alignOf(H));
try expectEqual(8, @bitSizeOf(H.IndexType));
try expectEqual(8, @bitSizeOf(H.CycleType));
try expectEqual(8, @bitSizeOf(H.AddressableIndex));
try expectEqual(8, @bitSizeOf(H.AddressableCycle));
const A = H.AddressableHandle;
try expectEqual(@sizeOf(u16), @sizeOf(A));
try expectEqual(@alignOf(u8), @alignOf(A));
}
{
const H = Handle(12, 4, void);
try expectEqual(@sizeOf(u16), @sizeOf(H));
try expectEqual(@alignOf(u16), @alignOf(H));
try expectEqual(12, @bitSizeOf(H.IndexType));
try expectEqual(4, @bitSizeOf(H.CycleType));
try expectEqual(16, @bitSizeOf(H.AddressableIndex));
try expectEqual(16, @bitSizeOf(H.AddressableCycle));
const A = H.AddressableHandle;
try expectEqual(@sizeOf(u32), @sizeOf(A));
try expectEqual(@alignOf(u16), @alignOf(A));
}
{
const H = Handle(16, 16, void);
try expectEqual(@sizeOf(u32), @sizeOf(H));
try expectEqual(@alignOf(u32), @alignOf(H));
try expectEqual(16, @bitSizeOf(H.IndexType));
try expectEqual(16, @bitSizeOf(H.CycleType));
try expectEqual(16, @bitSizeOf(H.AddressableIndex));
try expectEqual(16, @bitSizeOf(H.AddressableCycle));
const A = H.AddressableHandle;
try expectEqual(@sizeOf(u32), @sizeOf(A));
try expectEqual(@alignOf(u16), @alignOf(A));
}
{
const H = Handle(22, 10, void);
try expectEqual(@sizeOf(u32), @sizeOf(H));
try expectEqual(@alignOf(u32), @alignOf(H));
try expectEqual(22, @bitSizeOf(H.IndexType));
try expectEqual(10, @bitSizeOf(H.CycleType));
try expectEqual(32, @bitSizeOf(H.AddressableIndex));
try expectEqual(32, @bitSizeOf(H.AddressableCycle));
const A = H.AddressableHandle;
try expectEqual(@sizeOf(u64), @sizeOf(A));
try expectEqual(@alignOf(u32), @alignOf(A));
}
}
////////////////////////////////////////////////////////////////////////////////
test "Handle sort order" {
const expect = std.testing.expect;
const handle = Handle(4, 4, void).init;
const a = handle(0, 3);
const b = handle(1, 1);
// id order is consistent with index order, even when cycle order is not
try expect(a.id < b.id);
try expect(a.index() < b.index());
try expect(a.cycle() > b.cycle());
}
////////////////////////////////////////////////////////////////////////////////
test "Handle.format()" {
const bufPrint = std.fmt.bufPrint;
const expectEqualStrings = std.testing.expectEqualStrings;
const Foo = struct {};
const H = Handle(12, 4, Foo);
const h = H.init(0, 1);
var buffer = [_]u8{0} ** 128;
const s = try bufPrint(buffer[0..], "{}", .{h});
try expectEqualStrings("Foo[0#1]", s);
} | libs/zpool/src/handle.zig |
const testing = @import("std").testing;
const mem = @import("std").mem;
const c = @import("c.zig").c;
/// Errors that GLFW can produce.
pub const Error = error{
/// GLFW has not been initialized.
///
/// This occurs if a GLFW function was called that must not be called unless the library is
/// initialized.
NotInitialized,
/// No context is current for this thread.
///
/// This occurs if a GLFW function was called that needs and operates on the current OpenGL or
/// OpenGL ES context but no context is current on the calling thread. One such function is
/// glfw.SwapInterval.
NoCurrentContext,
/// One of the arguments to the function was an invalid enum value.
///
/// One of the arguments to the function was an invalid enum value, for example requesting
/// glfw.red_bits with glfw.getWindowAttrib.
InvalidEnum,
/// One of the arguments to the function was an invalid value.
///
/// One of the arguments to the function was an invalid value, for example requesting a
/// non-existent OpenGL or OpenGL ES version like 2.7.
///
/// Requesting a valid but unavailable OpenGL or OpenGL ES version will instead result in a
/// glfw.Error.VersionUnavailable error.
InvalidValue,
/// A memory allocation failed.
OutOfMemory,
/// GLFW could not find support for the requested API on the system.
///
/// The installed graphics driver does not support the requested API, or does not support it
/// via the chosen context creation backend. Below are a few examples.
///
/// Some pre-installed Windows graphics drivers do not support OpenGL. AMD only supports
/// OpenGL ES via EGL, while Nvidia and Intel only support it via a WGL or GLX extension. macOS
/// does not provide OpenGL ES at all. The Mesa EGL, OpenGL and OpenGL ES libraries do not
/// interface with the Nvidia binary driver. Older graphics drivers do not support Vulkan.
APIUnavailable,
/// The requested OpenGL or OpenGL ES version (including any requested context or framebuffer
/// hints) is not available on this machine.
///
/// The machine does not support your requirements. If your application is sufficiently
/// flexible, downgrade your requirements and try again. Otherwise, inform the user that their
/// machine does not match your requirements.
///
/// Future invalid OpenGL and OpenGL ES versions, for example OpenGL 4.8 if 5.0 comes out
/// before the 4.x series gets that far, also fail with this error and not glfw.Error.InvalidValue,
/// because GLFW cannot know what future versions will exist.
VersionUnavailable,
/// A platform-specific error occurred that does not match any of the more specific categories.
///
/// A bug or configuration error in GLFW, the underlying operating system or its drivers, or a
/// lack of required resources. Report the issue to our [issue tracker](https://github.com/glfw/glfw/issues).
PlatformError,
/// The requested format is not supported or available.
///
/// If emitted during window creation, the requested pixel format is not supported.
///
/// If emitted when querying the clipboard, the contents of the clipboard could not be
/// converted to the requested format.
///
/// If emitted during window creation, one or more hard constraints did not match any of the
/// available pixel formats. If your application is sufficiently flexible, downgrade your
/// requirements and try again. Otherwise, inform the user that their machine does not match
/// your requirements.
///
/// If emitted when querying the clipboard, ignore the error or report it to the user, as
/// appropriate.
FormatUnavailable,
/// The specified window does not have an OpenGL or OpenGL ES context.
///
/// A window that does not have an OpenGL or OpenGL ES context was passed to a function that
/// requires it to have one.
NoWindowContext,
};
fn convertError(e: c_int) Error!void {
return switch (e) {
c.GLFW_NO_ERROR => {},
c.GLFW_NOT_INITIALIZED => Error.NotInitialized,
c.GLFW_NO_CURRENT_CONTEXT => Error.NoCurrentContext,
c.GLFW_INVALID_ENUM => Error.InvalidEnum,
c.GLFW_INVALID_VALUE => Error.InvalidValue,
c.GLFW_OUT_OF_MEMORY => Error.OutOfMemory,
c.GLFW_API_UNAVAILABLE => Error.APIUnavailable,
c.GLFW_VERSION_UNAVAILABLE => Error.VersionUnavailable,
c.GLFW_PLATFORM_ERROR => Error.PlatformError,
c.GLFW_FORMAT_UNAVAILABLE => Error.FormatUnavailable,
c.GLFW_NO_WINDOW_CONTEXT => Error.NoWindowContext,
else => unreachable,
};
}
/// Returns and clears the last error for the calling thread.
///
/// This function returns and clears the error code of the last error that occurred on the calling
/// thread, and optionally a UTF-8 encoded human-readable description of it. If no error has
/// occurred since the last call, it returns GLFW_NO_ERROR (zero) and the description pointer is
/// set to `NULL`.
///
/// * @param[in] description Where to store the error description pointer, or `NULL`.
/// @return The last error code for the calling thread, or @ref GLFW_NO_ERROR (zero).
///
/// @pointer_lifetime The returned string is allocated and freed by GLFW. You should not free it
/// yourself. It is guaranteed to be valid only until the next error occurs or the library is
/// terminated.
///
/// @remark This function may be called before @ref glfwInit.
///
/// @thread_safety This function may be called from any thread.
pub inline fn getError() Error!void {
return convertError(c.glfwGetError(null));
}
/// Returns and clears the last error description for the calling thread.
///
/// This function returns a UTF-8 encoded human-readable description of the last error that occured
/// on the calling thread. If no error has occurred since the last call, it returns null.
///
/// @pointer_lifetime The returned string is allocated and freed by GLFW. You should not free it
/// yourself. It is guaranteed to be valid only until the next error occurs or the library is
/// terminated.
///
/// @remark This function may be called before @ref glfwInit.
///
/// @thread_safety This function may be called from any thread.
pub inline fn getErrorString() ?[]const u8 {
var desc: [*c]const u8 = null;
const error_code = c.glfwGetError(&desc);
convertError(error_code) catch {
return mem.sliceTo(desc, 0);
};
return null;
}
/// Sets the error callback.
///
/// This function sets the error callback, which is called with an error code
/// and a human-readable description each time a GLFW error occurs.
///
/// The error code is set before the callback is called. Calling @ref
/// glfwGetError from the error callback will return the same value as the error
/// code argument.
///
/// The error callback is called on the thread where the error occurred. If you
/// are using GLFW from multiple threads, your error callback needs to be
/// written accordingly.
///
/// Because the description string may have been generated specifically for that
/// error, it is not guaranteed to be valid after the callback has returned. If
/// you wish to use it after the callback returns, you need to make a copy.
///
/// Once set, the error callback remains set even after the library has been
/// terminated.
///
/// @param[in] callback The new callback, or `NULL` to remove the currently set
/// callback.
///
/// @callback_param `error_code` An error code. Future releases may add more error codes.
/// @callback_param `description` A UTF-8 encoded string describing the error.
///
/// @errors None.
///
/// @remark This function may be called before @ref glfwInit.
///
/// @thread_safety This function must only be called from the main thread.
pub fn setErrorCallback(comptime callback: ?fn (error_code: Error, description: [:0]const u8) void) void {
if (callback) |user_callback| {
const CWrapper = struct {
pub fn errorCallbackWrapper(err_int: c_int, c_description: [*c]const u8) callconv(.C) void {
if (convertError(err_int)) |_| {
// This means the error was `GLFW_NO_ERROR`
return;
} else |err| {
user_callback(err, mem.sliceTo(c_description, 0));
}
}
};
_ = c.glfwSetErrorCallback(CWrapper.errorCallbackWrapper);
return;
}
_ = c.glfwSetErrorCallback(null);
}
test "errorCallback" {
const TestStruct = struct {
pub fn callback(_: Error, _: [:0]const u8) void {}
};
setErrorCallback(TestStruct.callback);
}
test "error string" {
try testing.expect(getErrorString() == null);
} | libs/mach-glfw/src/errors.zig |
const std = @import("std");
const stdx = @import("stdx");
const platform = @import("platform");
const graphics = @import("graphics");
const Color = graphics.Color;
const ui = @import("../ui.zig");
const Node = ui.Node;
const FrameListPtr = ui.FrameListPtr;
const log = stdx.log.scoped(.scroll_view);
/// By default, scroll view will stretch to it's child. Must be constrained by parent sizer (eg. Sized, Flex) to trigger scrollbars.
pub const ScrollView = struct {
props: struct {
child: ui.FrameId = ui.NullFrameId,
bg_color: Color = Color.White,
border_color: Color = Color.DarkGray,
enable_hscroll: bool = true,
show_border: bool = true,
/// Triggered when mouse down hits the content rather than the scrollbars.
onContentMouseDown: ?stdx.Function(fn (platform.MouseDownEvent) void) = null,
},
/// Internal vars. They should not be modified after the layout phase.
/// Adjusting the scroll pos after layout and before render must call setScrollPosAfterLayout()
scroll_x: f32,
scroll_y: f32,
scroll_width: f32,
scroll_height: f32,
eff_scroll_width: f32,
eff_scroll_height: f32,
has_vbar: bool,
has_hbar: bool,
dragging_hbar: bool,
dragging_offset: f32,
dragging_vbar: bool,
node: *Node,
scroll_to_bottom_after_layout: bool,
const Self = @This();
const BarSize = 15;
pub fn init(self: *Self, c: *ui.InitContext) void {
self.scroll_x = 0;
self.scroll_y = 0;
self.scroll_width = 0;
self.scroll_height = 0;
self.node = c.node;
self.scroll_to_bottom_after_layout = false;
self.eff_scroll_width = 0;
self.eff_scroll_height = 0;
self.has_vbar = false;
self.has_hbar = false;
self.dragging_hbar = false;
self.dragging_vbar = false;
c.addMouseDownHandler(self, onMouseDown);
c.addMouseScrollHandler(self, onMouseScroll);
}
pub fn build(self: *Self, c: *ui.BuildContext) ui.FrameId {
_ = c;
return self.props.child;
}
fn onMouseDown(self: *Self, e: ui.MouseDownEvent) ui.EventResult {
const alo = e.ctx.node.getAbsLayout();
const xf = @intToFloat(f32, e.val.x);
const yf = @intToFloat(f32, e.val.y);
if (self.has_hbar) {
const bounds = self.getHBarBounds(alo);
if (xf >= bounds.thumb_x and xf <= bounds.thumb_x + bounds.thumb_width and yf >= bounds.y and yf <= bounds.y + bounds.height) {
self.dragging_hbar = true;
self.dragging_offset = xf - bounds.thumb_x;
e.ctx.removeMouseMoveHandler(*Self, onMouseMove);
e.ctx.removeMouseUpHandler(*Self, onMouseUp);
e.ctx.addMouseMoveHandler(self, onMouseMove);
e.ctx.addGlobalMouseUpHandler(self, onMouseUp);
e.ctx.requestCaptureMouse(true);
return .Stop;
}
}
if (self.has_vbar) {
const bounds = self.getVBarBounds(alo);
if (xf >= bounds.x and xf <= bounds.x + bounds.width and yf >= bounds.thumb_y and yf <= bounds.thumb_y + bounds.height) {
self.dragging_vbar = true;
self.dragging_offset = yf - bounds.thumb_y;
e.ctx.removeMouseMoveHandler(*Self, onMouseMove);
e.ctx.removeMouseUpHandler(*Self, onMouseUp);
e.ctx.addMouseMoveHandler(self, onMouseMove);
e.ctx.addGlobalMouseUpHandler(self, onMouseUp);
e.ctx.requestCaptureMouse(true);
return .Stop;
}
}
if (self.props.onContentMouseDown) |cb| {
cb.call(.{ e.val });
}
return .Continue;
}
fn onMouseUp(self: *Self, e: ui.MouseUpEvent) void {
self.dragging_hbar = false;
self.dragging_vbar = false;
e.ctx.removeMouseMoveHandler(*Self, onMouseMove);
e.ctx.removeMouseUpHandler(*Self, onMouseUp);
e.ctx.requestCaptureMouse(false);
}
fn onMouseMove(self: *Self, e: ui.MouseMoveEvent) void {
const xf = @intToFloat(f32, e.val.x);
const yf = @intToFloat(f32, e.val.y);
if (self.dragging_hbar) {
const alo = self.node.getAbsLayout();
const bounds = self.getHBarBounds(alo);
var thumb_x = xf - (bounds.x + self.dragging_offset);
if (thumb_x < 0) {
thumb_x = 0;
}
if (thumb_x > bounds.width - bounds.thumb_width) {
thumb_x = bounds.width - bounds.thumb_width;
}
// thumbx back to scrollx
self.scroll_x = thumb_x / bounds.width * self.eff_scroll_width;
} else if (self.dragging_vbar) {
const alo = self.node.getAbsLayout();
const bounds = self.getVBarBounds(alo);
var thumb_y = yf - (bounds.y + self.dragging_offset);
if (thumb_y < 0) {
thumb_y = 0;
}
if (thumb_y > bounds.height - bounds.thumb_height) {
thumb_y = bounds.height - bounds.thumb_height;
}
// thumby back to scrolly
self.scroll_y = thumb_y / bounds.height * self.eff_scroll_height;
}
}
fn onMouseScroll(self: *Self, e: ui.MouseScrollEvent) void {
self.scroll_y += e.val.delta_y;
self.checkScroll();
}
pub fn postPropsUpdate(self: *Self) void {
self.checkScroll();
}
pub fn scrollToBottomAfterLayout(self: *Self) void {
self.scroll_to_bottom_after_layout = true;
}
fn checkScroll(self: *Self) void {
if (self.scroll_y < 0) {
self.scroll_y = 0;
}
if (self.scroll_height > self.node.layout.height) {
if (self.scroll_y > self.eff_scroll_height - self.node.layout.height) {
self.scroll_y = self.eff_scroll_height - self.node.layout.height;
}
} else {
if (self.scroll_y > 0) {
self.scroll_y = 0;
}
}
}
/// In some cases, it's desirable to change the scroll view after the layout phase (when scroll width/height is updated) and before the render phase.
/// eg. Scroll to cursor view.
/// Since layout has already run, the children need to be repositioned.
pub fn setScrollPosAfterLayout(self: *Self, node: *Node, scroll_x: f32, scroll_y: f32) void {
self.scroll_x = scroll_x;
self.scroll_y = scroll_y;
for (node.children.items) |it| {
it.layout.x = -scroll_x;
it.layout.y = -scroll_y;
}
self.computeEffScrollDims(node.layout.width, node.layout.height);
}
/// Take up the same amount of space as it's child or constrained by the parent.
/// Updates scroll width and height.
pub fn layout(self: *Self, c: *ui.LayoutContext) ui.LayoutSize {
const node = c.getNode();
const size_cstr = ui.LayoutSize.init(std.math.inf(f32), std.math.inf(f32));
self.scroll_height = 0;
self.scroll_width = 0;
if (self.props.child != ui.NullFrameId) {
const child = node.children.items[0];
var child_size: ui.LayoutSize = undefined;
if (c.prefer_exact_width and !self.props.enable_hscroll) {
if (self.has_vbar) {
child_size = c.computeLayoutStretch(child, ui.LayoutSize.init(c.getSizeConstraint().width - BarSize, std.math.inf(f32)), true, false);
} else {
child_size = c.computeLayoutStretch(child, ui.LayoutSize.init(c.getSizeConstraint().width, std.math.inf(f32)), true, false);
}
} else {
child_size = c.computeLayout(child, size_cstr);
}
if (child_size.height > self.scroll_height) {
self.scroll_height = child_size.height;
}
if (child_size.width > self.scroll_width) {
self.scroll_width = child_size.width;
}
c.setLayout(child, ui.Layout.init(-self.scroll_x, -self.scroll_y, child_size.width, child_size.height));
}
const cstr = c.getSizeConstraint();
var res = ui.LayoutSize.init(self.scroll_width, self.scroll_height);
if (c.prefer_exact_width) {
res.width = cstr.width;
} else {
res.cropToWidth(cstr.width);
}
if (c.prefer_exact_height) {
res.height = cstr.height;
} else {
res.cropToHeight(cstr.height);
}
if (self.scroll_to_bottom_after_layout) {
if (self.scroll_height > res.height) {
self.scroll_y = self.scroll_height - res.height;
}
self.scroll_to_bottom_after_layout = false;
}
var prev_has_vbar = self.has_vbar;
self.computeEffScrollDims(res.width, res.height);
if (!prev_has_vbar and self.has_vbar and c.prefer_exact_width) {
// Recompute layout when turning on the vbar when prefer_exact_width is on.
return self.layout(c);
}
return res;
}
/// Computes the effective scroll width/height.
fn computeEffScrollDims(self: *Self, width: f32, height: f32) void {
// The view will show more than the scroll height if the scroll y is close to the bottom.
if (self.scroll_height > height) {
self.eff_scroll_height = self.scroll_height + height * 0.5;
} else {
self.eff_scroll_height = self.scroll_height;
}
if (self.scroll_width > width) {
self.eff_scroll_width = self.scroll_width + width * 0.5;
} else {
self.eff_scroll_width = self.scroll_width;
}
self.has_vbar = height < self.eff_scroll_height;
self.has_hbar = width < self.eff_scroll_width;
}
pub fn renderCustom(self: *Self, ctx: *ui.RenderContext) void {
const alo = ctx.getAbsLayout();
const g = ctx.getGraphics();
g.setFillColor(self.props.bg_color);
g.fillRect(alo.x, alo.y, alo.width, alo.height);
g.pushState();
g.clipRect(alo.x, alo.y, alo.width, alo.height);
ctx.renderChildren();
// Computes the layout of the scrollbars here since it depends on layout phase completed to obtain the final ScrollView size.
g.popState();
// Draw borders and scrollbars over the content.
if (self.props.show_border) {
g.setStrokeColor(self.props.border_color);
g.setLineWidth(2);
g.drawRect(alo.x, alo.y, alo.width, alo.height);
}
// Draw bottom right corner.
if (self.has_vbar and self.has_hbar) {
g.setFillColor(Color.LightGray);
g.fillRect(alo.x + alo.width - BarSize, alo.y + alo.height - BarSize, BarSize, BarSize);
}
if (self.has_vbar) {
const bounds = self.getVBarBounds(alo);
// Draw vertical scrollbar.
g.setFillColor(Color.LightGray);
g.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);
// Draw thumb.
g.setFillColor(Color.Gray);
g.fillRect(bounds.x, bounds.thumb_y, bounds.width, bounds.thumb_height);
}
if (self.has_hbar) {
const bounds = self.getHBarBounds(alo);
// Draw horizontal scrollbar.
g.setFillColor(Color.LightGray);
g.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);
// Draw thumb.
g.setFillColor(Color.Gray);
g.fillRect(bounds.thumb_x, bounds.y, bounds.thumb_width, bounds.height);
}
}
fn getVBarBounds(self: Self, alo: ui.Layout) VBarBounds {
var max_bar_height = alo.height;
if (self.has_hbar) {
max_bar_height -= BarSize;
}
const view_to_scroll_height = max_bar_height / self.eff_scroll_height;
const vert_thumb_length = view_to_scroll_height * alo.height;
const vert_thumb_y = view_to_scroll_height * self.scroll_y;
return .{
.x = alo.x + alo.width - BarSize,
.y = alo.y,
.width = BarSize,
.height = max_bar_height,
.thumb_y = alo.y + vert_thumb_y,
.thumb_height = vert_thumb_length,
};
}
fn getHBarBounds(self: Self, alo: ui.Layout) HBarBounds {
var max_bar_width = alo.width;
if (self.has_vbar) {
max_bar_width -= BarSize;
}
const view_to_scroll_width = max_bar_width / self.eff_scroll_width;
const hor_thumb_length = view_to_scroll_width * alo.width;
const hor_thumb_x = view_to_scroll_width * self.scroll_x;
return .{
.x = alo.x,
.y = alo.y + alo.height - BarSize,
.width = max_bar_width,
.height = BarSize,
.thumb_x = alo.x + hor_thumb_x,
.thumb_width = hor_thumb_length,
};
}
};
const HBarBounds = struct {
x: f32,
y: f32,
width: f32,
height: f32,
thumb_x: f32,
thumb_width: f32,
};
const VBarBounds = struct {
x: f32,
y: f32,
width: f32,
height: f32,
thumb_y: f32,
thumb_height: f32,
}; | ui/src/widgets/scroll_view.zig |
const std = @import("std");
const string = []const u8;
const input = @embedFile("../input/day09.txt");
pub fn main() !void {
// part 1
{
var iter = std.mem.split(u8, input, "\n");
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const alloc = &arena.allocator;
var lines = std.ArrayList([]const u32).init(alloc);
defer lines.deinit();
while (iter.next()) |line| {
if (line.len == 0) continue;
var list = std.ArrayList(u32).init(alloc);
defer list.deinit();
for (line) |c| {
try list.append(try std.fmt.parseUnsigned(u32, &[_]u8{c}, 10));
}
try lines.append(list.toOwnedSlice());
}
const grid = lines.toOwnedSlice();
var sum: u32 = 0;
for (grid) |row, y| {
for (row) |item, x| {
if (isLowPoint(grid, y, x)) {
sum += item + 1;
}
}
}
std.debug.print("{d}\n", .{sum});
}
// part 2
{
var iter = std.mem.split(u8, input, "\n");
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const alloc = &arena.allocator;
var lines = std.ArrayList([]const u32).init(alloc);
defer lines.deinit();
while (iter.next()) |line| {
if (line.len == 0) continue;
var list = std.ArrayList(u32).init(alloc);
defer list.deinit();
for (line) |c| {
try list.append(try std.fmt.parseUnsigned(u32, &[_]u8{c}, 10));
}
try lines.append(list.toOwnedSlice());
}
const grid = lines.toOwnedSlice();
var first: u32 = 0;
var second: u32 = 0;
var third: u32 = 0;
for (grid) |row, y| {
for (row) |_, x| {
if (isLowPoint(grid, y, x)) {
// make a duplicate of `grid` that is [][]u1
var basin = try createBasinGrid(alloc, grid);
// mark newgrid[y][x] = 1
basin[y][x] = 1;
// for all positions in newgrid=1 check if adjacent points in grid at !=9
// if yes, mark newgrid pos = 1, repeat
// repeat until the size of the basin does not change
fillBasin(grid, basin);
// check size
const size = basinSize(basin);
// see if its in the top 3
if (size > first) {
third = second;
second = first;
first = size;
} else if (size > second) {
third = second;
second = size;
} else if (size > third) {
third = size;
}
}
}
}
std.debug.print("{d}\n", .{first * second * third});
}
}
fn isLowPoint(grid: []const []const u32, y: usize, x: usize) bool {
const n = grid[y][x];
// is in the corner
// TL
if (y == 0 and x == 0) return (n < grid[y + 1][x] and n < grid[y][x + 1]);
// TR
if (y == 0 and x == grid[0].len - 1) return (n < grid[y + 1][x] and n < grid[y][x - 1]);
// BL
if (y == grid.len - 1 and x == 0) return (n < grid[y - 1][x] and n < grid[y][x + 1]);
// BR
if (y == grid.len - 1 and x == grid[0].len - 1) return (n < grid[y - 1][x] and n < grid[y][x - 1]);
// is on the edge
// left
if (x == 0) return (n < grid[y + 1][x] and n < grid[y - 1][x] and n < grid[y][x + 1]);
// top
if (y == 0) return (n < grid[y + 1][x] and n < grid[y][x + 1] and n < grid[y][x - 1]);
// right
if (x == grid[0].len - 1) return (n < grid[y + 1][x] and n < grid[y - 1][x] and n < grid[y][x - 1]);
// bottom
if (y == grid.len - 1) return (n < grid[y - 1][x] and n < grid[y][x + 1] and n < grid[y][x - 1]);
// is in the middle
return (n < grid[y + 1][x] and n < grid[y - 1][x] and n < grid[y][x + 1] and n < grid[y][x - 1]);
}
// generate [][]u1 grid same size as input grid
fn createBasinGrid(alloc: *std.mem.Allocator, grid: []const []const u32) ![][]u1 {
var list = std.ArrayList([]u1).init(alloc);
defer list.deinit();
for (grid) |row| {
try list.append(try alloc.alloc(u1, row.len));
}
return list.toOwnedSlice();
}
// checking adjacent points in grid and marking newgrid accordingly
fn fillBasin(grid: []const []const u32, basin: [][]u1) void {
const before_size = basinSize(basin);
for (basin) |row, y| {
for (row) |item, x| {
if (item == 1) {
if (y > 0 and checkNotEq(u32, grid, y - 1, x, 9)) basin[y - 1][x] = 1;
if (checkNotEq(u32, grid, y + 1, x, 9)) basin[y + 1][x] = 1;
if (x > 0 and checkNotEq(u32, grid, y, x - 1, 9)) basin[y][x - 1] = 1;
if (checkNotEq(u32, grid, y, x + 1, 9)) basin[y][x + 1] = 1;
}
}
}
const after_size = basinSize(basin);
if (after_size == before_size) return;
fillBasin(grid, basin);
}
// sum pts[y][x]=1 to get basin size
fn basinSize(basin: []const []const u1) u32 {
var sum: u32 = 0;
for (basin) |row| {
for (row) |item| {
sum += item;
}
}
return sum;
}
fn checkNotEq(comptime T: type, slice: []const []const T, y: usize, x: usize, value: T) bool {
if (y < 0) return false;
if (y >= slice.len) return false;
if (x < 0) return false;
if (x >= slice[0].len) return false;
return slice[y][x] != value;
} | src/day09.zig |
const std = @import("std");
const Builder = std.build.Builder;
const BuildMode = std.builtin.Mode;
const TRACY_PATH = "./tracy/";
fn tryAddTracy(enabled: bool, target: anytype) void {
target.addBuildOption(bool, "enable_tracy", enabled);
if (!enabled) return;
target.addIncludeDir(TRACY_PATH);
target.addCSourceFile(
TRACY_PATH ++ "TracyClient.cpp",
&[_][]const u8{ "-DTRACY_ENABLE=1", "-fno-sanitize=undefined" },
);
target.linkSystemLibraryName("c++");
target.linkLibC();
}
pub fn build(b: *Builder) void {
// Standard target options allows the person running `zig build` to choose
// what target to build for. Here we do not override the defaults, which
// means any target is allowed, and the default is native. Other options
// for restricting supported target set are available.
const target = b.standardTargetOptions(.{});
// Standard release options allow the person running `zig build` to select
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall.
const mode = b.standardReleaseOptions();
const exe = b.addExecutable("fastBPE", "fastBPE/main.zig");
exe.linkSystemLibrary("c");
// Tracy integration
// TODO: figure how to ready this option from Zig code.
const enable_tracy = b.option(bool, "enable_tracy", "Enable Tracy profiling") orelse false;
if (enable_tracy) {
const tracy_dir = std.fs.cwd().openDir(TRACY_PATH, .{}) catch @panic("Tracy dir " ++ TRACY_PATH ++ "' not found.");
}
tryAddTracy(enable_tracy, exe);
exe.setTarget(target);
exe.setBuildMode(mode);
exe.install();
const lib = b.addSharedLibrary("fastBPE_apply", "fastBPE/applyBPE.zig", b.version(0, 2, 0));
lib.linkSystemLibrary("c");
lib.setBuildMode(mode);
lib.setOutputDir(".");
lib.install();
tryAddTracy(enable_tracy, lib);
const run_step = b.step("run", "Run the app");
const run_cmd = exe.run();
run_cmd.step.dependOn(b.getInstallStep());
run_step.dependOn(&run_cmd.step);
} | build.zig |
const std = @import("std");
const builtin = @import("builtin");
const zwl = @import("zwl.zig");
const Allocator = std.mem.Allocator;
pub fn Platform(comptime Parent: anytype) type {
return struct {
const Self = @This();
parent: Parent,
file: std.fs.File,
pub fn init(allocator: Allocator, options: zwl.PlatformOptions) !*Parent {
const file = try displayConnect();
errdefer file.close();
var self = try allocator.create(Self);
errdefer allocator.destroy(self);
self.* = .{
.parent = .{
.allocator = allocator,
.type = .Wayland,
.window = undefined,
.windows = if (!Parent.settings.single_window) &[0]*Parent.Window{} else undefined,
},
.file = file,
};
std.log.scoped(.zwl).info("Platform Initialized: Wayland", .{});
return @ptrCast(*Parent, self);
}
pub fn deinit(self: *Self) void {
self.file.close();
self.parent.allocator.destroy(self);
}
pub fn waitForEvent(self: *Self) !Parent.Event {
return error.Unimplemented;
}
pub fn createWindow(self: *Self, options: zwl.WindowOptions) !*Parent.Window {
var window = try self.parent.allocator.create(Window);
errdefer self.parent.allocator.destroy(window);
var wbuf = std.io.bufferedWriter(self.file.writer());
var writer = wbuf.writer();
try window.init(self, options, writer);
// Extra settings and shit
try wbuf.flush();
return @ptrCast(*Parent.Window, window);
}
const MessageId = enum(u16) {
};
const Message = union(MessageId) {
};
fn sendMessage(writer: anytype, objectId: u32, message: Message) !void {
const T = @TypeOf(message);
const tag = std.meta.activeTag(message);
const size = @sizeOf(std.meta.TagPayloadType(Message, tag));
const opcode = @enumToInt(message);
try writer.writeIntNative(u32, objectId);
try writer.writeIntNative(u32, ((size + 8) << 16) | opcode);
try writer.writeAll(std.mem.asBytes(&message));
}
pub const Window = struct {
parent: Parent.Window,
width: u16,
height: u16,
pub fn init(self: *Window, parent: *Self, options: zwl.WindowOptions, writer: anytype) !void {
self.* = .{
.parent = .{
.platform = @ptrCast(*Parent, parent),
},
.width = options.width orelse 800,
.height = options.height orelse 600,
};
}
pub fn deinit(self: *Window) void {
// Do
}
pub fn configure(self: *Window, options: zwl.WindowOptions) !void {
// Do
}
pub fn getSize(self: *Window) [2]u16 {
return [2]u16{ self.width, self.height };
}
pub fn mapPixels(self: *Window) !zwl.PixelBuffer {
return error.Unimplemented;
}
pub fn submitPixels(self: *Window, pdates: []const zwl.UpdateArea) !void {
return error.Unimplemented;
}
};
};
}
fn displayConnect() !std.fs.File {
const XDG_RUNTIME_DIR = if (std.os.getenv("XDG_RUNTIME_DIR")) |val| val else return error.NoXDGRuntimeDirSpecified;
const WAYLAND_DISPLAY = if (std.os.getenv("WAYLAND_DISPLAY")) |val| val else "wayland-0";
var membuf: [256]u8 = undefined;
var allocator = std.heap.FixedBufferAllocator.init(&membuf);
const path = try std.mem.join(allocator.allocator(), "/", &[_][]const u8{ XDG_RUNTIME_DIR, WAYLAND_DISPLAY });
const opt_non_block = if (std.io.is_async) os.SOCK_NONBLOCK else 0;
var socket = try std.os.socket(std.os.AF_UNIX, std.os.SOCK_STREAM | std.os.SOCK_CLOEXEC | opt_non_block, 0);
errdefer std.os.close(socket);
var addr = std.os.sockaddr_un{ .path = [_]u8{0} ** 108 };
std.mem.copy(u8, addr.path[0..], path);
try std.os.connect(socket, @ptrCast(*const std.os.sockaddr, &addr), @sizeOf(std.os.sockaddr_un) - @intCast(u32, addr.path.len - path.len));
return std.fs.File{ .handle = socket };
} | didot-zwl/zwl/src/wayland.zig |
const std = @import("std");
const debug = std.debug;
const assert = std.debug.assert;
const testing = std.testing;
fn interleaveT(comptime T: type) type {
return struct {
const Self = @This();
list1: []const T,
list2: []const T,
const Iterator = struct {
list1: []const T,
list2: []const T,
_1: usize,
_2: usize,
fromFirst: bool,
fn next(self: *Iterator) ?T {
if (self.fromFirst) {
if (self._1 < self.list1.len) {
self.fromFirst = false;
const a = self.list1[self._1];
self._1 = self._1 + 1;
return a;
}
if (self.list2.len == self._2) return null;
const a = self.list2[self._2];
self._2 = self._2 + 1;
return a;
} else if (self._2 < self.list2.len) {
self.fromFirst = true;
const a = self.list2[self._2];
self._2 = self._2 + 1;
return a;
} else {
self.fromFirst = true;
if (self.list1.len == self._1) return null;
const a = self.list1[self._1];
self._1 = self._1 + 1;
return a;
}
}
};
fn init(list1: []const T, list2: []const T) Self {
return Self{
.list1 = list1,
.list2 = list2,
};
}
fn iterator(self: *Self) Iterator {
return Iterator{
.list1 = self.list1,
.list2 = self.list2,
._1 = 0,
._2 = 0,
.fromFirst = true,
};
}
};
}
fn interleave(list1: var, list2: var) interleaveT(@typeOf(list1).Child).Iterator {
const T = @typeOf(list1).Child;
return interleaveT(T).init(list1, list2).iterator();
}
test "interleave.equal_len" {
var list1 = ([]i32{1,3,5})[0..];
var list2 = ([]i32{2,4,6})[0..];
var iter = interleave(list1, list2);
testing.expect(iter.next().? == 1);
testing.expect(iter.next().? == 2);
testing.expect(iter.next().? == 3);
testing.expect(iter.next().? == 4);
testing.expect(iter.next().? == 5);
testing.expect(iter.next().? == 6);
testing.expect(iter.next() == null);
testing.expect(iter.next() == null);
}
test "interleave.first_shorter" {
var list1 = ([]i32{1,3})[0..];
var list2 = ([]i32{2,4,5})[0..];
var iter = interleave(list1, list2);
testing.expect(iter.next().? == 1);
testing.expect(iter.next().? == 2);
testing.expect(iter.next().? == 3);
testing.expect(iter.next().? == 4);
testing.expect(iter.next().? == 5);
testing.expect(iter.next() == null);
testing.expect(iter.next() == null);
}
test "interleave.first_longer" {
var list1 = ([]i32{1,3,5})[0..];
var list2 = ([]i32{2,4})[0..];
var iter = interleave(list1, list2);
testing.expect(iter.next().? == 1);
testing.expect(iter.next().? == 2);
testing.expect(iter.next().? == 3);
testing.expect(iter.next().? == 4);
testing.expect(iter.next().? == 5);
testing.expect(iter.next() == null);
testing.expect(iter.next() == null);
}
test "interleave.first_empty" {
var list1 = ([]i32{})[0..];
var list2 = ([]i32{1,2})[0..];
var iter = interleave(list1, list2);
testing.expect(iter.next().? == 1);
testing.expect(iter.next().? == 2);
testing.expect(iter.next() == null);
testing.expect(iter.next() == null);
}
test "interleave.second_empty" {
var list1 = ([]i32{1})[0..];
var list2 = ([]i32{})[0..];
var iter = interleave(list1, list2);
testing.expect(iter.next().? == 1);
testing.expect(iter.next() == null);
testing.expect(iter.next() == null);
} | src/interleave.zig |
const std = @import("std");
const assert = std.debug.assert;
const fmt = std.fmt;
const mem = std.mem;
const net = std.net;
const os = std.os;
const config = @import("config.zig");
const vr = @import("vr.zig");
const usage = fmt.comptimePrint(
\\Usage: tigerbeetle [options]
\\
\\ -h, --help
\\ Print this help message and exit.
\\
\\Required Configuration Options:
\\
\\ --cluster-id=<hex id>
\\ Set the cluster ID to the provided non-zero 128-bit hexadecimal number.
\\
\\ --replica-addresses=<addresses>
\\ Set the addresses of all replicas in the cluster. Accepts a
\\ comma-separated list of IPv4 addresses with port numbers.
\\ Either the IPv4 address or port number, but not both, may be
\\ ommited in which case a default of {[default_address]s} or {[default_port]d}
\\ will be used.
\\
\\ --replica-index=<index>
\\ Set the address in the array passed to the --replica-addresses option that
\\ will be used for this replica process. The value of this option is
\\ interpreted as a zero-based index into the array.
\\
\\Examples:
\\
\\ tigerbeetle --cluster-id=1a2b3c --replica-addresses=127.0.0.1:3003,127.0.0.1:3001,127.0.0.1:3002 --replica-index=0
\\
\\ tigerbeetle --cluster-id=1a2b3c --replica-addresses=3003,3001,3002 --replica-index=1
\\
\\ tigerbeetle --cluster-id=1a2b3c --replica-addresses=192.168.0.1,192.168.0.2,192.168.0.3 --replica-index=2
\\
, .{
.default_address = config.address,
.default_port = config.port,
});
pub const Args = struct {
cluster: u128,
configuration: []net.Address,
replica: u16,
};
/// Parse the command line arguments passed to the tigerbeetle binary.
/// Exits the program with a non-zero exit code if an error is found.
pub fn parse_args(allocator: *std.mem.Allocator) Args {
var maybe_cluster: ?[]const u8 = null;
var maybe_configuration: ?[]const u8 = null;
var maybe_replica: ?[]const u8 = null;
var args = std.process.args();
// Skip argv[0] which is the name of this executable
_ = args.nextPosix();
while (args.nextPosix()) |arg| {
if (mem.startsWith(u8, arg, "--cluster-id")) {
maybe_cluster = parse_flag("--cluster-id", arg);
} else if (mem.startsWith(u8, arg, "--replica-addresses")) {
maybe_configuration = parse_flag("--replica-addresses", arg);
} else if (mem.startsWith(u8, arg, "--replica-index")) {
maybe_replica = parse_flag("--replica-index", arg);
} else if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) {
std.io.getStdOut().writeAll(usage) catch os.exit(1);
os.exit(0);
} else {
print_error_exit("unexpected argument: '{s}'", .{arg});
}
}
const raw_cluster = maybe_cluster orelse
print_error_exit("required argument: --cluster-id", .{});
const raw_configuration = maybe_configuration orelse
print_error_exit("required argument: --replica-addresses", .{});
const raw_replica = maybe_replica orelse
print_error_exit("required argument: --replica-index", .{});
const cluster = parse_cluster(raw_cluster);
const configuration = parse_configuration(allocator, raw_configuration);
const replica = parse_replica(raw_replica, @intCast(u16, configuration.len));
return .{
.cluster = cluster,
.configuration = configuration,
.replica = replica,
};
}
/// Format and print an error message followed by the usage string to stderr,
/// then exit with an exit code of 1.
fn print_error_exit(comptime fmt_string: []const u8, args: anytype) noreturn {
const stderr = std.io.getStdErr().writer();
stderr.print("error: " ++ fmt_string ++ "\n\n" ++ usage, args) catch {};
os.exit(1);
}
/// Parse e.g. `--cluster=1a2b3c` into `1a2b3c` with error handling.
fn parse_flag(comptime flag: []const u8, arg: []const u8) []const u8 {
const value = arg[flag.len..];
if (value.len < 2) {
print_error_exit("{s} argument requires a value", .{flag});
}
if (value[0] != '=') {
print_error_exit("expected '=' after {s} but found '{c}'", .{ flag, value[0] });
}
return value[1..];
}
fn parse_cluster(raw_cluster: []const u8) u128 {
const cluster = fmt.parseUnsigned(u128, raw_cluster, 16) catch |err| switch (err) {
error.Overflow => print_error_exit(
\\--cluster-id: value does not fit into a 128-bit unsigned integer
, .{}),
error.InvalidCharacter => print_error_exit(
\\--cluster-id: value contains an invalid character
, .{}),
};
if (cluster == 0) {
print_error_exit("--cluster-id: a value of 0 is not permitted", .{});
}
return cluster;
}
/// Parse and allocate the configuration returning a slice into that array.
fn parse_configuration(allocator: *std.mem.Allocator, raw_configuration: []const u8) []net.Address {
return vr.parse_configuration(allocator, raw_configuration) catch |err| switch (err) {
error.AddressHasTrailingComma => {
print_error_exit("--replica-addresses: invalid trailing comma", .{});
},
error.AddressLimitExceeded => {
print_error_exit("--replica-addresses: too many addresses, at most {d} are allowed", .{
config.replicas_max,
});
},
error.AddressHasMoreThanOneColon => {
print_error_exit("--replica-addresses: invalid address with more than one colon", .{});
},
error.PortOverflow => print_error_exit("--replica-addresses: port exceeds 65535", .{}),
error.PortInvalid => print_error_exit("--replica-addresses: invalid port", .{}),
error.AddressInvalid => print_error_exit("--replica-addresses: invalid IPv4 address", .{}),
error.OutOfMemory => print_error_exit("--replica-addresses: out of memory", .{}),
};
}
fn parse_replica(raw_replica: []const u8, configuration_len: u16) u16 {
comptime assert(config.replicas_max <= std.math.maxInt(u16));
const replica = fmt.parseUnsigned(u16, raw_replica, 10) catch |err| switch (err) {
error.Overflow => print_error_exit(
\\--replica-index: value greater than length of address array
, .{}),
error.InvalidCharacter => print_error_exit(
\\--replica-index: value contains an invalid character
, .{}),
};
if (replica >= configuration_len) {
print_error_exit(
\\--replica-index: value greater than length of address array
, .{});
}
return replica;
} | src/cli.zig |
const std = @import("std");
const warn = std.debug.warn;
const mem = std.mem;
const c = @import("c.zig");
const msg = @import("message.zig");
const api = @import("api.zig");
const Config = @import("config.zig").Config;
const mhs = @import("message_handlers.zig");
pub const Client = struct {
sock: c_int,
config: Config,
message_handlers: std.StringHashMap(mhs.Handler),
const Self = @This();
pub fn handle(self: Self) !void {
var recv_buf: [2048]u8 = undefined;
const reqs = try api.initRequests(std.heap.c_allocator, self.config);
defer {
var itr = reqs.iterator();
while (itr.next()) |reqkv| reqkv.value.deinit();
reqs.deinit();
}
var ctx = mhs.Context{ .config = self.config, .requests = reqs };
while (true) {
const len = @intCast(usize, std.c.recv(self.sock, @ptrCast(*c_void, &recv_buf), recv_buf.len - 2, 0));
if (len == 0) {
warn("recv error. empty message. exiting. \n", .{});
break;
}
var time_buf: [200]u8 = undefined;
const time_len = c.get_time_str(time_buf[0..]);
const received = recv_buf[0..len];
warn("{}\n", .{time_buf[0..time_len]});
warn("{}\n", .{received});
try self.handleReceived(received, ctx);
}
}
pub fn handleReceived(self: Client, received: []const u8, ctx: mhs.Context) !void {
var line_itr = mem.separate(received, "\r\n");
while (line_itr.next()) |line| {
if (line.len == 0) continue;
// warn("line {}\n", .{line});
const m = msg.Message.parse(line) orelse {
warn("failed to parse '{}'\n", .{line});
continue;
};
// warn("{}, .command_text = {}, .command = {}, .params = {}\n", .{ m.prefix, m.command_text, m.command, m.params });
switch (m.command orelse continue) {
.PING => _ = try self.sendFmtErr("PONG :{}\r\n", .{m.params}),
.PRIVMSG => self.onPrivMsg(m, ctx) catch |e| {
warn("onPrivMsg error {}. message: {}\n", .{ e, m.params });
},
else => |cmd| warn("unhandled command {}\n", .{cmd}),
}
}
}
fn onPrivMsg(self: Client, m: msg.Message, ctx: mhs.Context) !void {
const params = m.params orelse return;
const sender = msg.strtok(params, ':') orelse return;
const message_text = params[sender.len + 1 ..];
// warn("sender {} text {}\n", .{ sender, message_text });
if (message_text[0] == '!') {
const command_name = msg.strtoks(message_text[1..], &[_]?u8{ ' ', null }) orelse return;
const handlerkv = self.message_handlers.get(command_name) orelse return;
var buf: [256]u8 = undefined;
if (try handlerkv.value(ctx, sender, message_text[command_name.len + 1 ..], &buf)) |handler_output| {
_ = try self.privmsg(handler_output[0..:0]);
}
}
}
pub fn initFromConfig(cfg: Config) !Self {
var map = std.StringHashMap(mhs.Handler).init(std.heap.c_allocator);
inline for (std.meta.declarations(mhs)) |decl| {
if (decl.is_pub) {
switch (decl.data) {
.Fn => if (decl.data.Fn.fn_type == mhs.Handler) _ = try map.put(decl.name, @field(mhs, decl.name)),
else => {},
}
}
}
const server = cfg.server[0..:0];
const port = cfg.port[0..:0];
var result = Self{
.sock = try c.get_socket(server, port),
.config = cfg,
.message_handlers = map,
};
return result;
}
pub fn deinit(self: Client) void {
self.message_handlers.deinit();
}
// various send functions with/without format along with corresponding sockSend follow
// *Err versions propogate errors
pub fn sendFmt(self: Self, comptime fmt: []const u8, values: var) void {
_ = self.sendFmtErr(fmt, values) catch |e| warn("send failure. ERROR {}\n", .{e});
}
pub fn sendFmtErr(self: Self, comptime fmt: [:0]const u8, values: var) !void {
_ = try sockSendFmt(self.sock, fmt, values);
}
pub fn send(self: Self, text: [:0]const u8) void {
_ = sockSend(self.sock, text) catch |e| warn("send failure. ERROR {}\n", .{e});
}
pub fn sendErr(self: Self, text: [:0]const u8) !void {
_ = try sockSend(self.sock, text);
}
pub fn privmsg(self: Self, text: []const u8) !void {
_ = try self.sendFmtErr("PRIVMSG #{} :{} \r\n", .{ self.config.channel, text });
}
pub fn sockSendFmt(sock: c_int, comptime fmt: [:0]const u8, values: var) !usize {
var buf: [256]u8 = undefined;
var m = try std.fmt.bufPrint(&buf, fmt, values);
var sent = try c.sck_send(sock, m[0..:0], m.len);
return sent;
}
pub fn sockSend(sock: c_int, text: [:0]const u8) !usize {
var sent = try c.sck_send(sock, text, text.len);
return sent;
}
pub fn identify(self: Self) !void {
_ = try self.sendFmtErr("CAP END \r\n", .{});
_ = try self.sendFmtErr("PASS {} \r\n", .{self.config.password});
_ = try self.sendFmtErr("NICK {} \r\n", .{self.config.nickname});
_ = try self.sendFmtErr("USER {} * 0 {} \r\n", .{ self.config.username, self.config.real_name });
_ = try self.sendFmtErr("JOIN #{} \r\n", .{self.config.channel});
}
}; | src/client.zig |
const std = @import("std");
const uefi = std.os.uefi;
const uefiAllocator = @import("uefi/allocator.zig");
const uefiMemory = @import("uefi/memory.zig");
const uefiConsole = @import("uefi/console.zig");
const uefiSystemInfo = @import("uefi/systeminfo.zig");
const graphics = @import("graphics.zig");
const Color = @import("color.zig");
const tty = @import("tty.zig");
const platform = @import("platform.zig");
const scheduler = @import("scheduler.zig");
const serial = @import("debug/serial.zig");
// Default panic handler for Zig.
pub const panic = serial.panic;
//fn os_banner() void {
// const title = "A/0 - v0.0.1";
// tty.alignCenter(title.len);
// tty.colorPrint(Color.LightRed, title ++ "\n\n");
//
// tty.colorPrint(Color.LightBlue, "Booting the microkernel:\n");
//}
fn user_fn() void {
while (true) {}
}
pub fn main() void {
// FIXME(Ryan): complete the Graphics & TTY kernel impl to enable scrolling.
// Then reuse it for everything else.
uefiMemory.initialize();
uefiConsole.initialize();
uefiConsole.puts("UEFI console initialized.\r\n");
serial.initialize(serial.SERIAL_COM1, 2);
uefiConsole.puts("User serial console initialized.\r\n");
graphics.initialize();
uefiConsole.puts("UEFI GOP initialized.\r\n");
// UEFI-specific initialization
const bootServices = uefi.system_table.boot_services.?;
uefiSystemInfo.dumpAndAssertPlatformState();
uefiConsole.puts("UEFI memory and debug console setup.\r\n");
scheduler.initialize(@frameAddress(), @frameSize(main), uefiAllocator.systemAllocator) catch |err| {
serial.ppanic("Failed to initialize scheduler: {}", .{err});
};
// scheduler.self_test_init(uefiAllocator.systemAllocator) catch |err| {
// serial.ppanic("Failed to initialize scheduler tests: {}", .{err});
// };
tty.initialize(uefiAllocator.systemAllocator);
tty.serialPrint("Platform preinitialization...\n", .{});
platform.preinitialize(uefiAllocator.systemAllocator);
tty.serialPrint("Platform preinitialized, can now exit boot services.\n", .{});
uefiMemory.memoryMap.refresh(); // Refresh the memory map before the exit.
var retCode = bootServices.exitBootServices(uefi.handle, uefiMemory.memoryMap.key);
if (retCode != uefi.Status.Success) {
return;
}
uefiConsole.disable(); // conOut is a boot service, so it's not available anymore.
tty.serialPrint("Boot services exitted. UEFI console is now unavailable.\n", .{});
tty.serialPrint("Platform initialization...\n", .{});
platform.initialize();
tty.serialPrint("Platform initialized.\n", .{});
// tty.serialPrint("Date and time: {}", .{platform.get_date()});
// scheduler.selfTest();
// TODO: graphics tests work well only when scheduler is disabled, or at low frequency. Seems a graphic buffer issue (?). Currently, freq = 19.
// graphics.selfTest();
// tty.serialPrint("Graphics subsystem self test completed.\n", .{});
// tty.selfTest();
// runtimeServices.set_virtual_address_map();
//mem.initialize(MEMORY_OFFSET);
//timer.initialize(100);
//scheduler.initialize();
//tty.colorPrint(Color.LightBlue, "\nLoading the servers (driverspace):\n");
// The OS is now running.
//var user_stack: [1024]u64 = undefined;
//platform.liftoff(&user_fn, &user_stack[1023]); // Go to userspace.
platform.hlt();
}
// This code solves the queens problem. Used to test if the code execution is correct
const N_QUEENS: i64 = 9;
var echiquier: [N_QUEENS][N_QUEENS]bool = undefined;
fn cellOk(x: usize, y: usize) bool {
var i: usize = 0;
while (i < N_QUEENS) : (i += 1) {
var j: usize = 0;
while (j < N_QUEENS) : (j += 1) {
if (echiquier[i][j]) {
if (i == x or j == y or x + j == y + i or x + y == i + j) {
return false;
}
}
}
}
return true;
}
fn solve(n: i64, i_deb: usize, j_deb: usize) i64 {
if (n == N_QUEENS) {
return 1;
}
var r: i64 = 0;
var i: usize = i_deb;
var j: usize = j_deb;
while (i < N_QUEENS) : (i += 1) {
while (j < N_QUEENS) : (j += 1) {
if (cellOk(i, j)) {
echiquier[i][j] = true;
r += solve(n + 1, i, j);
echiquier[i][j] = false;
}
}
j = 0;
}
return r;
}
fn doSomeTest() void {
var i: usize = 0;
while (i < N_QUEENS) : (i += 1) {
var j: usize = 0;
while (j < N_QUEENS) : (j += 1) {
echiquier[i][j] = false;
}
}
tty.serialPrint("Solutions: {}\n\n\n\n\n\n\n\n\n\n\n\n\n\n", .{solve(0, 0, 0)});
tty.serialPrint("========== END", .{});
} | src/kernel/main.zig |
const vcf = @import("vcf.zig");
const std = @import("std");
const stdout = std.io.getStdOut().writer();
const VCF = vcf.VCF;
const Field = vcf.Field;
const fname = "tests/exac.bcf";
const allocator = std.testing.allocator;
const Ai32 = std.ArrayList(i32);
const Af32 = std.ArrayList(f32);
test "that vcf open works" {
var ivcf = VCF.open(fname);
defer ivcf.?.deinit();
try std.testing.expect(ivcf != null);
}
test "that header to string works" {
var ivcf = VCF.open("tests/exac.bcf").?;
defer ivcf.deinit();
var h = ivcf.header.tostring(allocator);
try std.testing.expect(h != null);
try std.testing.expect(std.mem.indexOf(u8, h.?, "#CHROM") != null);
//try stdout.print("header:{s}\n", .{h.?});
allocator.free(h.?);
}
test "that variant to string works" {
var ivcf = VCF.open("tests/exac.bcf").?;
defer ivcf.deinit();
var variant = ivcf.next().?;
var s = variant.tostring(allocator);
try std.testing.expect(s != null);
try std.testing.expect(std.mem.indexOf(u8, s.?, "ENSG00000223972|") != null);
//try stdout.print("header:{s}\n", .{s.?});
allocator.free(s.?);
}
test "that variant attributes work" {
var ivcf = VCF.open("tests/exac.bcf").?;
defer ivcf.deinit();
var variant = ivcf.next().?;
try std.testing.expect(std.mem.eql(u8, variant.CHROM(), "1"));
try std.testing.expect(std.mem.eql(u8, variant.REF(), "G"));
try std.testing.expect(std.mem.eql(u8, variant.ALT0(), "C"));
try std.testing.expect(variant.start() == 13371);
try std.testing.expect(variant.stop() == 13372);
try std.testing.expect(variant.QUAL() == 608.91);
try std.testing.expect(std.mem.eql(u8, variant.FILTER(), "PASS"));
try std.testing.expect(std.mem.eql(u8, variant.ID(), "."));
}
test "info AC int" {
var ivcf = VCF.open("tests/exac.bcf").?;
defer ivcf.deinit();
var variant = ivcf.next().?;
var fld: []const u8 = "AC";
var values = Ai32.init(allocator);
defer values.deinit();
try variant.get(Field.info, i32, &values, fld);
try std.testing.expect(values.items.len == 1);
try std.testing.expect(values.items[0] == 3);
}
test "info AC float" {
var ivcf = VCF.open("tests/exac.bcf").?;
defer ivcf.deinit();
var variant = ivcf.next().?;
var fld: []const u8 = "AF";
var values = Af32.init(allocator);
defer values.deinit();
try variant.get(Field.info, f32, &values, fld);
try std.testing.expect(values.items.len == 1);
try std.testing.expect(values.items[0] == 6.998e-5);
}
test "missing INFO field gives undefined tag" {
var ivcf = VCF.open("tests/exac.bcf").?;
defer ivcf.deinit();
var variant = ivcf.next().?;
var values = Ai32.init(allocator);
defer values.deinit();
var fld: []const u8 = "MISSING_AC";
try std.testing.expectError(vcf.HTSError.UndefinedTag, variant.get(Field.info, i32, &values, fld));
}
test "format format field extraction" {
var ivcf = VCF.open("tests/test.snpeff.bcf").?;
defer ivcf.deinit();
_ = ivcf.next().?;
var variant = ivcf.next().?;
var fld = "AD";
var ad = Ai32.init(allocator);
defer ad.deinit();
try variant.get(vcf.Field.format, i32, &ad, fld);
try std.testing.expect(ad.items.len == 8);
try std.testing.expect(ad.items[0] == 7);
try std.testing.expect(ad.items[2] == 2);
try stdout.print("\nAD:{any}\n", .{ad.items});
try stdout.print("\n{any}\n", .{variant});
}
test "n_samples" {
var gvcf = VCF.open("tests/test.snpeff.bcf").?;
defer gvcf.deinit();
_ = gvcf.next().?;
var gvariant = gvcf.next().?;
try std.testing.expect(gvariant.n_samples() == 4);
try std.testing.expect(gvcf.n_samples() == 4);
}
test "get genotypes" {
var ivcf = VCF.open("tests/test.snpeff.bcf").?;
defer ivcf.deinit();
_ = ivcf.next().?;
var variant = ivcf.next().?;
var gts_mem = Ai32.init(allocator);
defer gts_mem.deinit();
var gts = try variant.genotypes(>s_mem);
try stdout.print("\n{any}\n", .{gts_mem.items});
try std.testing.expect(gts.gts.len == 8);
try std.testing.expect(gts.ploidy == 2);
}
test "get genotypes" {
var ivcf = VCF.open("tests/test.snpeff.bcf").?;
defer ivcf.deinit();
_ = ivcf.next().?;
_ = ivcf.next().?;
var variant = ivcf.next().?;
var gts_mem = Ai32.init(allocator);
defer gts_mem.deinit();
var gts = try variant.genotypes(>s_mem);
try stdout.print("\ngts:{any}\n", .{gts});
try stdout.print("\ngts.at(2):{any}\n", .{gts.at(2)});
var alts = try gts.alts(allocator);
try stdout.print("\nalts:{any}\n", .{alts});
// TODO: use arraylist for alts
allocator.free(alts);
}
test "get genotypes" {
var ivcf = VCF.open("tests/alts.vcf").?;
defer ivcf.deinit();
var variant = ivcf.next().?;
var gts_mem = Ai32.init(allocator);
defer gts_mem.deinit();
var gts = try variant.genotypes(>s_mem);
var alts = try gts.alts(allocator);
// 0/0 0/1 0/1 0/1 0/0 1/1 1/1 1/1 1/1 1/1 1/1 . 0/0 1/2 0/2 2/2
var expected = [_]i8{ -1, 0, 1, 1, 1, 0, 2, 2, 2, 2, 2, 2, -1, 0, 2, 1, 2 };
try std.testing.expect(std.mem.eql(i8, alts, expected[0..]));
allocator.free(alts);
}
test "query" {
var ivcf = VCF.open("tests/test.snpeff.bcf").?;
//var ivcf = VCF.open("tests/x.vcf.gz").?;
defer ivcf.deinit();
var chrom: []const u8 = "1";
try std.testing.expectError(vcf.HTSError.NotFound, ivcf.query(chrom, 69269, 69270));
chrom = "chr1";
var iter = try ivcf.query(chrom, 69269, 69270);
var i: i32 = 0;
while (iter.next()) |v| {
i += 1;
try std.testing.expect(v.start() == 69269);
}
try std.testing.expect(i == 1);
}
test "add_to_header" {
var ivcf = VCF.open("tests/test.snpeff.bcf").?;
defer ivcf.deinit();
var fld = "ASDFXX";
var desc = "added for test";
try ivcf.header.add(allocator, Field.info, fld, "1", "Integer", desc);
var h = ivcf.header.tostring(allocator);
defer allocator.free(h.?);
try std.testing.expect(std.mem.indexOf(u8, h.?, "ASDFXX") != null);
try std.testing.expect(std.mem.indexOf(u8, h.?, "AFXX") == null);
_ = try ivcf.header.add(allocator, Field.format, "GGGGG", "2", "Float", desc);
}
test "set info" {
var ivcf = VCF.open("tests/test.snpeff.bcf").?;
defer ivcf.deinit();
var v = ivcf.next().?;
var xa = [3]i32{ 24, 48, 96 };
var x: []i32 = xa[0..];
var fld = "XFX";
var desc = "added for test";
try ivcf.header.add(allocator, Field.info, fld, "3", "Integer", desc);
try v.set(Field.info, i32, x, fld);
var s = v.tostring(allocator);
try std.testing.expect(s != null);
try std.testing.expect(std.mem.indexOf(u8, s.?, "XFX=24,48,96") != null);
allocator.free(s.?);
fld = "XFF";
var xff = [_]f32{2.0};
var xf: []f32 = xff[0..];
try ivcf.header.add(allocator, Field.info, fld, "1", "Float", desc);
try v.set(Field.info, f32, xf, fld);
s = v.tostring(allocator);
try std.testing.expect(s != null);
try std.testing.expect(std.mem.indexOf(u8, s.?, "XFF=2") != null);
allocator.free(s.?);
}
test "header fromstring" {
var ivcf = VCF.open("tests/test.snpeff.bcf").?;
defer ivcf.deinit();
var h = ivcf.header.tostring(allocator);
defer allocator.free(h.?);
var hnew = vcf.Header{ .c = null };
try hnew.from_string(h.?);
defer hnew.deinit();
var hs = hnew.tostring(allocator);
defer allocator.free(hs.?);
var l = h.?.len;
try std.testing.expect(std.mem.eql(u8, h.?[100..l], hs.?[100..l]));
}
test "writing bcf" {
var ivcf = VCF.open("tests/test.snpeff.bcf").?;
defer ivcf.deinit();
// need to add to header before copying so that the variant has the header
// information available.
var fld = "gnomad_popmax_af";
try ivcf.header.add(allocator, Field.info, fld, "1", "Float", "AF from gnomad");
var ovcf = VCF.open_mode("_o.bcf", "wb").?;
ovcf.header.set(ivcf.header.c.?);
ovcf.write_header();
var xff = [_]f32{0.1};
var xf = xff[0..];
while (ivcf.next()) |v| {
try v.set(Field.info, f32, xf, fld);
try ovcf.write_variant(v);
}
ovcf.deinit();
var rvcf = VCF.open("_o.bcf").?;
defer rvcf.deinit();
var if32 = Af32.init(allocator);
defer if32.deinit();
while (rvcf.next()) |*v| {
try v.get(Field.info, f32, &if32, fld);
try std.testing.expect(if32.items[0] == 0.1);
}
}
test "set samples" {
var ivcf = VCF.open("tests/test.snpeff.bcf").?;
defer ivcf.deinit();
var asamples = [_][]const u8{ "1094PC0009", "1094PC0012" };
var samples = asamples[0..];
try ivcf.set_samples(samples, allocator);
try std.testing.expect(ivcf.n_samples() == 2);
while (ivcf.next()) |v| {
try std.testing.expect(v.n_samples() == 2);
}
} | src/vcf_test.zig |
const std = @import("std");
const util = @import("util.zig");
const data = @embedFile("../data/day18.txt");
const TreeNodeLeaf = struct {
value: i64,
};
const TreeNodeBranch = struct {
left: *TreeNode,
right: *TreeNode,
};
const TreeNodeType = enum {
leaf,
branch,
};
const TreeNodePayload = union(TreeNodeType) {
leaf: TreeNodeLeaf,
branch: TreeNodeBranch,
};
const TreeNode = struct {
parent: ?*TreeNode,
payload: TreeNodePayload,
};
fn buildTree(line: []const u8, pos: *usize, parent: ?*TreeNode, allocator: std.mem.Allocator) anyerror!*TreeNode {
var node = try allocator.create(TreeNode);
switch (line[pos.*]) {
'[' => {
pos.* += 1; // skip [
const left = try buildTree(line, pos, node, allocator);
assert(line[pos.*] == ',');
pos.* += 1; // skip ,
const right = try buildTree(line, pos, node, allocator);
assert(line[pos.*] == ']');
pos.* += 1; // skip ]
node.* = TreeNode{ .parent = parent, .payload = TreeNodePayload{ .branch = TreeNodeBranch{
.left = left,
.right = right,
} } };
},
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9' => {
var nums = std.mem.tokenize(u8, line[pos.*..], ",]");
const num_str = nums.next().?;
const num = try parseInt(u8, num_str, 10);
node.* = TreeNode{ .parent = parent, .payload = TreeNodePayload{ .leaf = TreeNodeLeaf{
.value = num,
} } };
pos.* += num_str.len;
},
else => unreachable,
}
return node;
}
fn freeTree(tree: *TreeNode, allocator: std.mem.Allocator) void {
switch (tree.payload) {
.branch => |branch| {
freeTree(branch.left, allocator);
freeTree(branch.right, allocator);
},
else => {},
}
allocator.destroy(tree);
}
fn writeTree(tree: *TreeNode, writer: *std.ArrayList(u8).Writer) anyerror!void {
switch (tree.payload) {
.branch => |branch| {
try writer.print("[", .{});
try writeTree(branch.left, writer);
try writer.print(",", .{});
try writeTree(branch.right, writer);
try writer.print("]", .{});
},
.leaf => |leaf| {
try writer.print("{d}", .{leaf.value});
},
}
}
fn printTree(tree: *TreeNode, allocator: std.mem.Allocator) !void {
var tree_str = std.ArrayList(u8).init(allocator);
defer tree_str.deinit();
var writer = tree_str.writer();
try writeTree(tree, &writer);
print("{s}\n", .{tree_str.items[0..]});
}
fn reduceExplode(tree: *TreeNode, depth: usize, allocator: std.mem.Allocator) anyerror!bool {
switch (tree.payload) {
.branch => |*branch| {
if (depth >= 4) {
// explode
assert(@as(TreeNodeType, branch.left.payload) == .leaf);
assert(@as(TreeNodeType, branch.right.payload) == .leaf);
// add left leaf's value to first leaf node to the left, if possible
const left_value = branch.left.payload.leaf.value;
var left_dest = tree;
while (left_dest.parent != null) : (left_dest = left_dest.parent.?) {
if (left_dest.parent.?.payload.branch.left != left_dest) {
// There is definitely a number in here somewhere;
left_dest = left_dest.parent.?.payload.branch.left;
while (@as(TreeNodeType, left_dest.payload) != .leaf) {
left_dest = left_dest.payload.branch.right;
}
left_dest.payload.leaf.value += left_value;
break;
}
}
// add right leaf's value to first leaf node to the right, if possible
const right_value = branch.right.payload.leaf.value;
var right_dest = tree;
while (right_dest.parent != null) : (right_dest = right_dest.parent.?) {
if (right_dest.parent.?.payload.branch.right != right_dest) {
// There is definitely a number in here somewhere;
right_dest = right_dest.parent.?.payload.branch.right;
while (@as(TreeNodeType, right_dest.payload) != .leaf) {
right_dest = right_dest.payload.branch.left;
}
right_dest.payload.leaf.value += right_value;
break;
}
}
// replace exploded branch node with a leaf node with value=0
allocator.destroy(branch.left);
allocator.destroy(branch.right);
tree.payload = TreeNodePayload{ .leaf = TreeNodeLeaf{ .value = 0 } };
//print("EXPLODE: pair [{d},{d}]\n", .{left_value, right_value});
return true;
} else {
return (try reduceExplode(branch.left, depth + 1, allocator)) or (try reduceExplode(branch.right, depth + 1, allocator));
}
},
.leaf => {}, // leafs do not explode
}
return false;
}
fn reduceSplit(tree: *TreeNode, allocator: std.mem.Allocator) anyerror!bool {
switch (tree.payload) {
.branch => |*branch| {
return (try reduceSplit(branch.left, allocator)) or (try reduceSplit(branch.right, allocator));
},
.leaf => |*leaf| {
if (leaf.value >= 10) {
// split
//print("SPLIT: {d}\n", .{leaf.value});
var left = try allocator.create(TreeNode);
const left_value = @divFloor(leaf.value, 2);
left.* = TreeNode{ .parent = tree, .payload = TreeNodePayload{ .leaf = TreeNodeLeaf{ .value = left_value } } };
var right = try allocator.create(TreeNode);
const right_value = @divFloor(leaf.value + 1, 2);
right.* = TreeNode{ .parent = tree, .payload = TreeNodePayload{ .leaf = TreeNodeLeaf{ .value = right_value } } };
tree.payload = TreeNodePayload{ .branch = TreeNodeBranch{
.left = left,
.right = right,
} };
return true;
}
},
}
return false;
}
fn addTrees(left: *TreeNode, right: *TreeNode, allocator: std.mem.Allocator) !*TreeNode {
var result = try allocator.create(TreeNode);
result.* = TreeNode{ .parent = null, .payload = TreeNodePayload{ .branch = TreeNodeBranch{
.left = left,
.right = right,
} } };
left.parent = result;
right.parent = result;
while (true) {
//print("Reducing ", .{});
//try printTree(result, allocator);
const had_explode = try reduceExplode(result, 0, allocator);
if (!had_explode) {
const had_split = try reduceSplit(result, allocator);
if (!had_split) {
break;
}
}
}
return result;
}
fn magnitude(tree: *TreeNode) i64 {
return switch (tree.payload) {
.branch => |branch| (3 * magnitude(branch.left)) + (2 * magnitude(branch.right)),
.leaf => |leaf| leaf.value,
};
}
const Input = struct {
lines: std.BoundedArray([]const u8, 100) = undefined,
allocator: std.mem.Allocator,
pub fn init(input_text: []const u8, allocator: std.mem.Allocator) !@This() {
_ = allocator;
var input = Input{
.lines = try std.BoundedArray([]const u8, 100).init(0),
.allocator = allocator,
};
errdefer input.deinit();
var lines = std.mem.tokenize(u8, input_text, "\r\n");
while (lines.next()) |line| {
try input.lines.append(line);
}
return input;
}
pub fn deinit(self: @This()) void {
_ = self;
}
};
fn part1(input: Input) i64 {
var sum: *TreeNode = undefined;
defer freeTree(sum, input.allocator);
for (input.lines.constSlice()) |line, i| {
var line_pos: usize = 0;
var tree = buildTree(line, &line_pos, null, input.allocator) catch unreachable;
assert(line_pos == line.len);
if (i == 0) {
sum = tree;
} else {
sum = addTrees(sum, tree, input.allocator) catch unreachable;
}
}
return magnitude(sum);
}
fn part2(input: Input) i64 {
var largest_magnitude: i64 = 0;
for (input.lines.constSlice()) |s1| {
for (input.lines.constSlice()) |s2| {
var s1_pos: usize = 0;
var tree1 = buildTree(s1, &s1_pos, null, input.allocator) catch unreachable;
var s2_pos: usize = 0;
var tree2 = buildTree(s2, &s2_pos, null, input.allocator) catch unreachable;
var sum: *TreeNode = undefined;
defer freeTree(sum, input.allocator);
sum = addTrees(tree1, tree2, input.allocator) catch unreachable;
const mag = magnitude(sum);
largest_magnitude = std.math.max(mag, largest_magnitude);
}
}
return largest_magnitude;
}
const test_data =
\\[[[0,[5,8]],[[1,7],[9,6]]],[[4,[1,2]],[[1,4],2]]]
\\[[[5,[2,8]],4],[5,[[9,9],0]]]
\\[6,[[[6,2],[5,6]],[[7,6],[4,7]]]]
\\[[[6,[0,7]],[0,9]],[4,[9,[9,0]]]]
\\[[[7,[6,4]],[3,[1,3]]],[[[5,5],1],9]]
\\[[6,[[7,3],[3,2]]],[[[3,8],[5,7]],4]]
\\[[[[5,4],[7,7]],8],[[8,3],8]]
\\[[9,3],[[9,9],[6,[4,9]]]]
\\[[2,[[7,7],7]],[[5,8],[[9,3],[0,2]]]]
\\[[[[5,2],5],[8,[3,7]]],[[5,[7,5]],[4,4]]]
;
const part1_test_solution: ?i64 = 4140;
const part1_solution: ?i64 = 4365;
const part2_test_solution: ?i64 = 3993;
const part2_solution: ?i64 = 4490;
// Just boilerplate below here, nothing to see
fn treesAreEqual(expected: *TreeNode, actual: *TreeNode, allocator: std.mem.Allocator) !void {
var result1 = std.ArrayList(u8).init(allocator);
defer result1.deinit();
var result1_writer = result1.writer();
try writeTree(expected, &result1_writer);
var result2 = std.ArrayList(u8).init(allocator);
defer result2.deinit();
var result2_writer = result2.writer();
try writeTree(actual, &result2_writer);
try std.testing.expectEqualStrings(result1.items[0..], result2.items[0..]);
}
fn testBuildTree(s: []const u8, allocator: std.mem.Allocator) !*TreeNode {
var pos: usize = 0;
var tree = try buildTree(s, &pos, null, allocator);
errdefer freeTree(tree, allocator);
try std.testing.expectEqual(s.len, pos);
var result = try std.ArrayList(u8).initCapacity(allocator, s.len);
defer result.deinit();
var result_writer = result.writer();
try writeTree(tree, &result_writer);
try std.testing.expectEqualStrings(s, result.items[0..]);
return tree;
}
fn testMagnitude(s: []const u8, expected: i64, allocator: std.mem.Allocator) !void {
var tree = try testBuildTree(s, allocator);
defer freeTree(tree, allocator);
try std.testing.expectEqual(expected, magnitude(tree));
}
fn testAddition(s1: []const u8, s2: []const u8, expected_sum: []const u8, allocator: std.mem.Allocator) !void {
var tree1 = try testBuildTree(s1, allocator);
var tree2 = try testBuildTree(s2, allocator);
var actual = try addTrees(tree1, tree2, allocator);
defer freeTree(actual, allocator);
var expected = try testBuildTree(expected_sum, allocator);
defer freeTree(expected, allocator);
try treesAreEqual(expected, actual, allocator);
}
fn testPart1() !void {
// Test magnitude
try testMagnitude("[9,1]", 29, std.testing.allocator);
try testMagnitude("[[9,1],[1,9]]", 129, std.testing.allocator);
try testMagnitude("[[1,2],[[3,4],5]]", 143, std.testing.allocator);
try testMagnitude("[[[[0,7],4],[[7,8],[6,0]]],[8,1]]", 1384, std.testing.allocator);
try testMagnitude("[[[[1,1],[2,2]],[3,3]],[4,4]]", 445, std.testing.allocator);
try testMagnitude("[[[[3,0],[5,3]],[4,4]],[5,5]]", 791, std.testing.allocator);
try testMagnitude("[[[[5,0],[7,4]],[5,5]],[6,6]]", 1137, std.testing.allocator);
try testMagnitude("[[[[8,7],[7,7]],[[8,6],[7,7]]],[[[0,7],[6,6]],[8,7]]]", 3488, std.testing.allocator);
// test addition
try testAddition("[[[[4,3],4],4],[7,[[8,4],9]]]", "[1,1]", "[[[[0,7],4],[[7,8],[6,0]]],[8,1]]", std.testing.allocator);
const longer_input =
\\[[[0,[4,5]],[0,0]],[[[4,5],[2,6]],[9,5]]]
\\[7,[[[3,7],[4,3]],[[6,3],[8,8]]]]
\\[[2,[[0,8],[3,4]]],[[[6,7],1],[7,[1,6]]]]
\\[[[[2,4],7],[6,[0,5]]],[[[6,8],[2,8]],[[2,1],[4,5]]]]
\\[7,[5,[[3,8],[1,4]]]]
\\[[2,[2,2]],[8,[8,1]]]
\\[2,9]
\\[1,[[[9,3],9],[[9,0],[0,7]]]]
\\[[[5,[7,4]],7],1]
\\[[[[4,2],2],6],[8,7]]
;
{
var lines = std.mem.tokenize(u8, longer_input, "\r\n");
var sum: ?*TreeNode = null;
defer freeTree(sum.?, std.testing.allocator);
while (lines.next()) |line| {
var line_pos: usize = 0;
var tree = buildTree(line, &line_pos, null, std.testing.allocator) catch unreachable;
assert(line_pos == line.len);
if (sum == null) {
//print(" ", .{});
//try printTree(tree, std.testing.allocator);
sum = tree;
} else {
//print("+ ", .{});
//try printTree(tree, std.testing.allocator);
sum = addTrees(sum.?, tree, std.testing.allocator) catch unreachable;
//print("= ", .{});
//try printTree(sum.?, std.testing.allocator);
}
}
}
if (part1_test_solution) |solution| {
var test_input = try Input.init(test_data, std.testing.allocator);
defer test_input.deinit();
try std.testing.expectEqual(solution, part1(test_input));
}
if (part1_solution) |solution| {
var timer = try std.time.Timer.start();
var input = try Input.init(data, std.testing.allocator);
defer input.deinit();
try std.testing.expectEqual(solution, part1(input));
print("part1 took {d:9.3}ms\n", .{@intToFloat(f64, timer.lap()) / 1000000.0});
}
}
fn testPart2() !void {
if (part2_test_solution) |solution| {
var test_input = try Input.init(test_data, std.testing.allocator);
defer test_input.deinit();
try std.testing.expectEqual(solution, part2(test_input));
}
if (part2_solution) |solution| {
var timer = try std.time.Timer.start();
var input = try Input.init(data, std.testing.allocator);
defer input.deinit();
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/day18.zig |
const std = @import("std");
const main = @import("main.zig");
const fs = std.fs;
const testing = std.testing;
const mem = std.mem;
fn printErrorSet(comptime fun: anytype) void {
const info = @typeInfo(@TypeOf(fun));
const ret_type = info.Fn.return_type.?;
inline for (@typeInfo(@typeInfo(ret_type).ErrorUnion.error_set).ErrorSet.?) |reterror| {
std.debug.print("{s}\n", .{reterror.name});
}
}
test "printErrors" {
printErrorSet(main.main);
}
//pub fn main() void {
// main2() catch |err| {
// switch (err) {
// else => fatal("error: {s}", .{@errorName(err)}),
// }
// };
//}
//const ReturnError = error{
// ControlChars,
// UnportableChars,
//};
test "resolvePosix" {
try testResolvePosix(&[_][]const u8{ "/test_folders/control_sequences/\x01/", ".." }, "/test_folders/control_sequences");
try testResolvePosix(&[_][]const u8{ "/test_folders/control_sequences/\x02/", ".." }, "/test_folders/control_sequences");
try testResolvePosix(&[_][]const u8{ "/test_folders/control_sequences/\x03/", ".." }, "/test_folders/control_sequences");
try testResolvePosix(&[_][]const u8{ "/test_folders/control_sequences/\x04/", ".." }, "/test_folders/control_sequences");
try testResolvePosix(&[_][]const u8{ "/test_folders/control_sequences/\x05/", ".." }, "/test_folders/control_sequences");
try testResolvePosix(&[_][]const u8{ "/test_folders/control_sequences/\x06/", ".." }, "/test_folders/control_sequences");
try testResolvePosix(&[_][]const u8{ "/test_folders/control_sequences/\x07/", ".." }, "/test_folders/control_sequences");
try testResolvePosix(&[_][]const u8{ "/test_folders/control_sequences/\x08/", ".." }, "/test_folders/control_sequences");
try testResolvePosix(&[_][]const u8{ "/test_folders/control_sequences/\x09/", ".." }, "/test_folders/control_sequences");
try testResolvePosix(&[_][]const u8{ "/test_folders/control_sequences/\x0a/", ".." }, "/test_folders/control_sequences");
try testResolvePosix(&[_][]const u8{ "/test_folders/control_sequences/\x0b/", ".." }, "/test_folders/control_sequences");
try testResolvePosix(&[_][]const u8{ "/test_folders/control_sequences/\x0c/", ".." }, "/test_folders/control_sequences");
try testResolvePosix(&[_][]const u8{ "/test_folders/control_sequences/\x0d/", ".." }, "/test_folders/control_sequences");
try testResolvePosix(&[_][]const u8{ "/test_folders/control_sequences/\x0e/", ".." }, "/test_folders/control_sequences");
try testResolvePosix(&[_][]const u8{ "/test_folders/control_sequences/\x0f/", ".." }, "/test_folders/control_sequences"); // 15
try testResolvePosix(&[_][]const u8{ "/test_folders/control_sequences/\x10/", ".." }, "/test_folders/control_sequences"); // 16
try testResolvePosix(&[_][]const u8{ "/test_folders/control_sequences/\x11/", ".." }, "/test_folders/control_sequences");
try testResolvePosix(&[_][]const u8{ "/test_folders/control_sequences/\x12/", ".." }, "/test_folders/control_sequences");
try testResolvePosix(&[_][]const u8{ "/test_folders/control_sequences/\x13/", ".." }, "/test_folders/control_sequences");
try testResolvePosix(&[_][]const u8{ "/test_folders/control_sequences/\x14/", ".." }, "/test_folders/control_sequences");
try testResolvePosix(&[_][]const u8{ "/test_folders/control_sequences/\x15/", ".." }, "/test_folders/control_sequences");
try testResolvePosix(&[_][]const u8{ "/test_folders/control_sequences/\x16/", ".." }, "/test_folders/control_sequences");
try testResolvePosix(&[_][]const u8{ "/test_folders/control_sequences/\x17/", ".." }, "/test_folders/control_sequences");
try testResolvePosix(&[_][]const u8{ "/test_folders/control_sequences/\x18/", ".." }, "/test_folders/control_sequences");
try testResolvePosix(&[_][]const u8{ "/test_folders/control_sequences/\x19/", ".." }, "/test_folders/control_sequences");
try testResolvePosix(&[_][]const u8{ "/test_folders/control_sequences/\x1a/", ".." }, "/test_folders/control_sequences");
try testResolvePosix(&[_][]const u8{ "/test_folders/control_sequences/\x1b/", ".." }, "/test_folders/control_sequences");
try testResolvePosix(&[_][]const u8{ "/test_folders/control_sequences/\x1c/", ".." }, "/test_folders/control_sequences");
try testResolvePosix(&[_][]const u8{ "/test_folders/control_sequences/\x1d/", ".." }, "/test_folders/control_sequences");
try testResolvePosix(&[_][]const u8{ "/test_folders/control_sequences/\x1e/", ".." }, "/test_folders/control_sequences");
try testResolvePosix(&[_][]const u8{ "/test_folders/control_sequences/\x1f/", ".." }, "/test_folders/control_sequences"); // 31
try testResolvePosix(&[_][]const u8{ "/test_folders/control_sequences/\x7f/", ".." }, "/test_folders/control_sequences");
}
fn testResolvePosix(paths: []const []const u8, expected: []const u8) !void {
const actual = try fs.path.resolvePosix(testing.allocator, paths);
defer testing.allocator.free(actual);
try testing.expect(mem.eql(u8, actual, expected));
} | src/helper.zig |
const std = @import("std");
/// Stolen from https://github.com/ziglang/zig/pull/6272
pub const va_list = switch (std.builtin.target.cpu.arch) {
.aarch64 => switch (std.builtin.target.os.tag) {
.windows => [*c]u8,
.ios, .macosx, .tvos, .watchos => [*c]u8,
else => [1]extern struct {
__stack: *c_void,
__gr_top: *c_void,
__vr_top: *c_void,
__gr_offs: c_int,
__vr_offs: c_int,
},
},
.sparc, .wasm32, .wasm64 => *c_void,
.powerpc => switch (std.builtin.target.os.tag) {
.ios, .macosx, .tvos, .watchos, .aix => [*c]u8,
else => [1]extern struct {
gpr: u8,
fpr: u8,
reserved: u16,
overflow_arg_area: *c_void,
reg_save_area: *c_void,
},
},
.s390x => [1]extern struct {
__gpr: c_long,
__fpr: c_long,
__overflow_arg_area: *c_void,
__reg_save_area: *c_void,
},
.i386 => [*c]u8,
.x86_64 => switch (std.builtin.target.os.tag) {
.windows => [*c]u8,
else => [1]extern struct {
gp_offset: c_uint,
fp_offset: c_uint,
overflow_arg_area: *c_void,
reg_save_area: *c_void,
},
},
else => @compileError("va_list not supported for this target yet"),
};
const os = std.builtin.target.os.tag;
const cpu_bit_count = std.builtin.target.cpu.arch.ptrBitWidth();
// TODO: Add support for every other missing os / architecture
// I haven't found a place that contains `jni_md.h`s for every
// possible os-arch combo, it seems we'll have to install Java
// sources for every combo and manually extract the file
// pub const JNICALL: std.builtin.CallingConvention = .Stdcall;
pub const JNICALL: std.builtin.CallingConvention = .C;
pub const jint = switch (os) {
.windows => c_long,
else => @compileError("Not supported bidoof"),
};
pub const jlong = switch (os) {
.windows => i64,
else => @compileError("Not supported bidoof"),
};
pub const jbyte = switch (os) {
.windows => i8,
else => @compileError("Not supported bidoof"),
};
pub const jboolean = u8;
pub const jchar = c_ushort;
pub const jshort = c_short;
pub const jfloat = f32;
pub const jdouble = f64;
pub const jsize = jint;
pub const jobject = ?*opaque {};
pub const jclass = jobject;
pub const jthrowable = jobject;
pub const jstring = jobject;
pub const jarray = jobject;
pub const jbooleanArray = jarray;
pub const jbyteArray = jarray;
pub const jcharArray = jarray;
pub const jshortArray = jarray;
pub const jintArray = jarray;
pub const jlongArray = jarray;
pub const jfloatArray = jarray;
pub const jdoubleArray = jarray;
pub const jobjectArray = jarray;
pub const jweak = jobject;
pub const NativeType = enum {
object,
boolean,
byte,
char,
short,
int,
long,
float,
double,
@"void",
};
pub fn MapNativeType(comptime native_type: NativeType) type {
return switch (native_type) {
.object => jobject,
.boolean => jboolean,
.byte => jbyte,
.char => jchar,
.short => jshort,
.int => jint,
.long => jlong,
.float => jfloat,
.double => jdouble,
.@"void" => void,
};
}
pub const jvalue = extern union {
z: jboolean,
b: jbyte,
c: jchar,
s: jshort,
i: jint,
j: jlong,
f: jfloat,
d: jdouble,
l: jobject,
pub fn toJValue(value: anytype) jvalue {
if (@typeInfo(@TypeOf(value)) == .Struct and @hasDecl(@TypeOf(value), "toJValue")) return @field(value, "toJValue")();
return switch (@TypeOf(value)) {
jboolean => .{ .z = value },
jbyte => .{ .b = value },
jchar => .{ .c = value },
jshort => .{ .s = value },
jint => .{ .i = value },
jlong => .{ .j = value },
jfloat => .{ .f = value },
jdouble => .{ .d = value },
jobject => .{ .l = value },
else => @compileError("invalid value!"),
};
}
};
pub const jfieldID = ?*opaque {};
pub const jmethodID = ?*opaque {};
pub const ObjectReferenceKind = enum(c_int) {
/// The reference is invalid (gced, null)
invalid,
/// The reference is local and will not exist in the future
local,
/// The reference is global and is guaranteed to exist in the future
global,
/// The reference is a weak global and is guaranteed to exist in the future, but its underlying object is not
weak_global,
/// Since references are typically implemented as pointers once deleted it is not specified what value GetObjectReferenceKind will return.
_,
};
// The new error handling model for jui is simple:
// 1. Handle known errors/exceptions mentioned in the JNI as Zig errors
// 2. Handle userland or unknown errors/exceptions separately
/// Errors are negative jints; 0 indicates success
pub const JNIFailureError = error{
/// Unknown error; value of -1
Unknown,
/// Thread detached from the VM; value of -2
ThreadDetached,
/// JNI version error; value of -3
BadVersion,
/// Not enough memory; value of -4
OutOfMemory,
/// VM already created; value of -5
VMAlreadyExists,
/// Invalid arguments; value of -6
InvalidArguments,
};
pub const JNINativeMethod = extern struct {
name: [*c]u8,
signature: [*c]u8,
fnPtr: ?*c_void,
};
const JNINativeInterface = extern struct {
reserved0: ?*c_void,
reserved1: ?*c_void,
reserved2: ?*c_void,
reserved3: ?*c_void,
GetVersion: fn ([*c]JNIEnv) callconv(JNICALL) jint,
DefineClass: fn ([*c]JNIEnv, [*c]const u8, jobject, [*c]const jbyte, jsize) callconv(JNICALL) jclass,
FindClass: fn ([*c]JNIEnv, [*c]const u8) callconv(JNICALL) jclass,
FromReflectedMethod: fn ([*c]JNIEnv, jobject) callconv(JNICALL) jmethodID,
FromReflectedField: fn ([*c]JNIEnv, jobject) callconv(JNICALL) jfieldID,
ToReflectedMethod: fn ([*c]JNIEnv, jclass, jmethodID, jboolean) callconv(JNICALL) jobject,
GetSuperclass: fn ([*c]JNIEnv, jclass) callconv(JNICALL) jclass,
IsAssignableFrom: fn ([*c]JNIEnv, jclass, jclass) callconv(JNICALL) jboolean,
ToReflectedField: fn ([*c]JNIEnv, jclass, jfieldID, jboolean) callconv(JNICALL) jobject,
Throw: fn ([*c]JNIEnv, jthrowable) callconv(JNICALL) jint,
ThrowNew: fn ([*c]JNIEnv, jclass, [*c]const u8) callconv(JNICALL) jint,
ExceptionOccurred: fn ([*c]JNIEnv) callconv(JNICALL) jthrowable,
ExceptionDescribe: fn ([*c]JNIEnv) callconv(JNICALL) void,
ExceptionClear: fn ([*c]JNIEnv) callconv(JNICALL) void,
FatalError: fn ([*c]JNIEnv, [*c]const u8) callconv(JNICALL) void,
PushLocalFrame: fn ([*c]JNIEnv, jint) callconv(JNICALL) jint,
PopLocalFrame: fn ([*c]JNIEnv, jobject) callconv(JNICALL) jobject,
NewGlobalRef: fn ([*c]JNIEnv, jobject) callconv(JNICALL) jobject,
DeleteGlobalRef: fn ([*c]JNIEnv, jobject) callconv(JNICALL) void,
DeleteLocalRef: fn ([*c]JNIEnv, jobject) callconv(JNICALL) void,
IsSameObject: fn ([*c]JNIEnv, jobject, jobject) callconv(JNICALL) jboolean,
NewLocalRef: fn ([*c]JNIEnv, jobject) callconv(JNICALL) jobject,
EnsureLocalCapacity: fn ([*c]JNIEnv, jint) callconv(JNICALL) jint,
AllocObject: fn ([*c]JNIEnv, jclass) callconv(JNICALL) jobject,
NewObject: fn ([*c]JNIEnv, jclass, jmethodID, ...) callconv(JNICALL) jobject,
NewObjectV: fn ([*c]JNIEnv, jclass, jmethodID, va_list) callconv(JNICALL) jobject,
NewObjectA: fn ([*c]JNIEnv, jclass, jmethodID, [*c]const jvalue) callconv(JNICALL) jobject,
GetObjectClass: fn ([*c]JNIEnv, jobject) callconv(JNICALL) jclass,
IsInstanceOf: fn ([*c]JNIEnv, jobject, jclass) callconv(JNICALL) jboolean,
GetMethodID: fn ([*c]JNIEnv, jclass, [*c]const u8, [*c]const u8) callconv(JNICALL) jmethodID,
CallObjectMethod: fn ([*c]JNIEnv, jobject, jmethodID, ...) callconv(JNICALL) jobject,
CallObjectMethodV: fn ([*c]JNIEnv, jobject, jmethodID, va_list) callconv(JNICALL) jobject,
CallObjectMethodA: fn ([*c]JNIEnv, jobject, jmethodID, [*c]const jvalue) callconv(JNICALL) jobject,
CallBooleanMethod: fn ([*c]JNIEnv, jobject, jmethodID, ...) callconv(JNICALL) jboolean,
CallBooleanMethodV: fn ([*c]JNIEnv, jobject, jmethodID, va_list) callconv(JNICALL) jboolean,
CallBooleanMethodA: fn ([*c]JNIEnv, jobject, jmethodID, [*c]const jvalue) callconv(JNICALL) jboolean,
CallByteMethod: fn ([*c]JNIEnv, jobject, jmethodID, ...) callconv(JNICALL) jbyte,
CallByteMethodV: fn ([*c]JNIEnv, jobject, jmethodID, va_list) callconv(JNICALL) jbyte,
CallByteMethodA: fn ([*c]JNIEnv, jobject, jmethodID, [*c]const jvalue) callconv(JNICALL) jbyte,
CallCharMethod: fn ([*c]JNIEnv, jobject, jmethodID, ...) callconv(JNICALL) jchar,
CallCharMethodV: fn ([*c]JNIEnv, jobject, jmethodID, va_list) callconv(JNICALL) jchar,
CallCharMethodA: fn ([*c]JNIEnv, jobject, jmethodID, [*c]const jvalue) callconv(JNICALL) jchar,
CallShortMethod: fn ([*c]JNIEnv, jobject, jmethodID, ...) callconv(JNICALL) jshort,
CallShortMethodV: fn ([*c]JNIEnv, jobject, jmethodID, va_list) callconv(JNICALL) jshort,
CallShortMethodA: fn ([*c]JNIEnv, jobject, jmethodID, [*c]const jvalue) callconv(JNICALL) jshort,
CallIntMethod: fn ([*c]JNIEnv, jobject, jmethodID, ...) callconv(JNICALL) jint,
CallIntMethodV: fn ([*c]JNIEnv, jobject, jmethodID, va_list) callconv(JNICALL) jint,
CallIntMethodA: fn ([*c]JNIEnv, jobject, jmethodID, [*c]const jvalue) callconv(JNICALL) jint,
CallLongMethod: fn ([*c]JNIEnv, jobject, jmethodID, ...) callconv(JNICALL) jlong,
CallLongMethodV: fn ([*c]JNIEnv, jobject, jmethodID, va_list) callconv(JNICALL) jlong,
CallLongMethodA: fn ([*c]JNIEnv, jobject, jmethodID, [*c]const jvalue) callconv(JNICALL) jlong,
CallFloatMethod: fn ([*c]JNIEnv, jobject, jmethodID, ...) callconv(JNICALL) jfloat,
CallFloatMethodV: fn ([*c]JNIEnv, jobject, jmethodID, va_list) callconv(JNICALL) jfloat,
CallFloatMethodA: fn ([*c]JNIEnv, jobject, jmethodID, [*c]const jvalue) callconv(JNICALL) jfloat,
CallDoubleMethod: fn ([*c]JNIEnv, jobject, jmethodID, ...) callconv(JNICALL) jdouble,
CallDoubleMethodV: fn ([*c]JNIEnv, jobject, jmethodID, va_list) callconv(JNICALL) jdouble,
CallDoubleMethodA: fn ([*c]JNIEnv, jobject, jmethodID, [*c]const jvalue) callconv(JNICALL) jdouble,
CallVoidMethod: fn ([*c]JNIEnv, jobject, jmethodID, ...) callconv(JNICALL) void,
CallVoidMethodV: fn ([*c]JNIEnv, jobject, jmethodID, va_list) callconv(JNICALL) void,
CallVoidMethodA: fn ([*c]JNIEnv, jobject, jmethodID, [*c]const jvalue) callconv(JNICALL) void,
CallNonvirtualObjectMethod: fn ([*c]JNIEnv, jobject, jclass, jmethodID, ...) callconv(JNICALL) jobject,
CallNonvirtualObjectMethodV: fn ([*c]JNIEnv, jobject, jclass, jmethodID, va_list) callconv(JNICALL) jobject,
CallNonvirtualObjectMethodA: fn ([*c]JNIEnv, jobject, jclass, jmethodID, [*c]const jvalue) callconv(JNICALL) jobject,
CallNonvirtualBooleanMethod: fn ([*c]JNIEnv, jobject, jclass, jmethodID, ...) callconv(JNICALL) jboolean,
CallNonvirtualBooleanMethodV: fn ([*c]JNIEnv, jobject, jclass, jmethodID, va_list) callconv(JNICALL) jboolean,
CallNonvirtualBooleanMethodA: fn ([*c]JNIEnv, jobject, jclass, jmethodID, [*c]const jvalue) callconv(JNICALL) jboolean,
CallNonvirtualByteMethod: fn ([*c]JNIEnv, jobject, jclass, jmethodID, ...) callconv(JNICALL) jbyte,
CallNonvirtualByteMethodV: fn ([*c]JNIEnv, jobject, jclass, jmethodID, va_list) callconv(JNICALL) jbyte,
CallNonvirtualByteMethodA: fn ([*c]JNIEnv, jobject, jclass, jmethodID, [*c]const jvalue) callconv(JNICALL) jbyte,
CallNonvirtualCharMethod: fn ([*c]JNIEnv, jobject, jclass, jmethodID, ...) callconv(JNICALL) jchar,
CallNonvirtualCharMethodV: fn ([*c]JNIEnv, jobject, jclass, jmethodID, va_list) callconv(JNICALL) jchar,
CallNonvirtualCharMethodA: fn ([*c]JNIEnv, jobject, jclass, jmethodID, [*c]const jvalue) callconv(JNICALL) jchar,
CallNonvirtualShortMethod: fn ([*c]JNIEnv, jobject, jclass, jmethodID, ...) callconv(JNICALL) jshort,
CallNonvirtualShortMethodV: fn ([*c]JNIEnv, jobject, jclass, jmethodID, va_list) callconv(JNICALL) jshort,
CallNonvirtualShortMethodA: fn ([*c]JNIEnv, jobject, jclass, jmethodID, [*c]const jvalue) callconv(JNICALL) jshort,
CallNonvirtualIntMethod: fn ([*c]JNIEnv, jobject, jclass, jmethodID, ...) callconv(JNICALL) jint,
CallNonvirtualIntMethodV: fn ([*c]JNIEnv, jobject, jclass, jmethodID, va_list) callconv(JNICALL) jint,
CallNonvirtualIntMethodA: fn ([*c]JNIEnv, jobject, jclass, jmethodID, [*c]const jvalue) callconv(JNICALL) jint,
CallNonvirtualLongMethod: fn ([*c]JNIEnv, jobject, jclass, jmethodID, ...) callconv(JNICALL) jlong,
CallNonvirtualLongMethodV: fn ([*c]JNIEnv, jobject, jclass, jmethodID, va_list) callconv(JNICALL) jlong,
CallNonvirtualLongMethodA: fn ([*c]JNIEnv, jobject, jclass, jmethodID, [*c]const jvalue) callconv(JNICALL) jlong,
CallNonvirtualFloatMethod: fn ([*c]JNIEnv, jobject, jclass, jmethodID, ...) callconv(JNICALL) jfloat,
CallNonvirtualFloatMethodV: fn ([*c]JNIEnv, jobject, jclass, jmethodID, va_list) callconv(JNICALL) jfloat,
CallNonvirtualFloatMethodA: fn ([*c]JNIEnv, jobject, jclass, jmethodID, [*c]const jvalue) callconv(JNICALL) jfloat,
CallNonvirtualDoubleMethod: fn ([*c]JNIEnv, jobject, jclass, jmethodID, ...) callconv(JNICALL) jdouble,
CallNonvirtualDoubleMethodV: fn ([*c]JNIEnv, jobject, jclass, jmethodID, va_list) callconv(JNICALL) jdouble,
CallNonvirtualDoubleMethodA: fn ([*c]JNIEnv, jobject, jclass, jmethodID, [*c]const jvalue) callconv(JNICALL) jdouble,
CallNonvirtualVoidMethod: fn ([*c]JNIEnv, jobject, jclass, jmethodID, ...) callconv(JNICALL) void,
CallNonvirtualVoidMethodV: fn ([*c]JNIEnv, jobject, jclass, jmethodID, va_list) callconv(JNICALL) void,
CallNonvirtualVoidMethodA: fn ([*c]JNIEnv, jobject, jclass, jmethodID, [*c]const jvalue) callconv(JNICALL) void,
GetFieldID: fn ([*c]JNIEnv, jclass, [*c]const u8, [*c]const u8) callconv(JNICALL) jfieldID,
GetObjectField: fn ([*c]JNIEnv, jobject, jfieldID) callconv(JNICALL) jobject,
GetBooleanField: fn ([*c]JNIEnv, jobject, jfieldID) callconv(JNICALL) jboolean,
GetByteField: fn ([*c]JNIEnv, jobject, jfieldID) callconv(JNICALL) jbyte,
GetCharField: fn ([*c]JNIEnv, jobject, jfieldID) callconv(JNICALL) jchar,
GetShortField: fn ([*c]JNIEnv, jobject, jfieldID) callconv(JNICALL) jshort,
GetIntField: fn ([*c]JNIEnv, jobject, jfieldID) callconv(JNICALL) jint,
GetLongField: fn ([*c]JNIEnv, jobject, jfieldID) callconv(JNICALL) jlong,
GetFloatField: fn ([*c]JNIEnv, jobject, jfieldID) callconv(JNICALL) jfloat,
GetDoubleField: fn ([*c]JNIEnv, jobject, jfieldID) callconv(JNICALL) jdouble,
SetObjectField: fn ([*c]JNIEnv, jobject, jfieldID, jobject) callconv(JNICALL) void,
SetBooleanField: fn ([*c]JNIEnv, jobject, jfieldID, jboolean) callconv(JNICALL) void,
SetByteField: fn ([*c]JNIEnv, jobject, jfieldID, jbyte) callconv(JNICALL) void,
SetCharField: fn ([*c]JNIEnv, jobject, jfieldID, jchar) callconv(JNICALL) void,
SetShortField: fn ([*c]JNIEnv, jobject, jfieldID, jshort) callconv(JNICALL) void,
SetIntField: fn ([*c]JNIEnv, jobject, jfieldID, jint) callconv(JNICALL) void,
SetLongField: fn ([*c]JNIEnv, jobject, jfieldID, jlong) callconv(JNICALL) void,
SetFloatField: fn ([*c]JNIEnv, jobject, jfieldID, jfloat) callconv(JNICALL) void,
SetDoubleField: fn ([*c]JNIEnv, jobject, jfieldID, jdouble) callconv(JNICALL) void,
GetStaticMethodID: fn ([*c]JNIEnv, jclass, [*c]const u8, [*c]const u8) callconv(JNICALL) jmethodID,
CallStaticObjectMethod: fn ([*c]JNIEnv, jclass, jmethodID, ...) callconv(JNICALL) jobject,
CallStaticObjectMethodV: fn ([*c]JNIEnv, jclass, jmethodID, va_list) callconv(JNICALL) jobject,
CallStaticObjectMethodA: fn ([*c]JNIEnv, jclass, jmethodID, [*c]const jvalue) callconv(JNICALL) jobject,
CallStaticBooleanMethod: fn ([*c]JNIEnv, jclass, jmethodID, ...) callconv(JNICALL) jboolean,
CallStaticBooleanMethodV: fn ([*c]JNIEnv, jclass, jmethodID, va_list) callconv(JNICALL) jboolean,
CallStaticBooleanMethodA: fn ([*c]JNIEnv, jclass, jmethodID, [*c]const jvalue) callconv(JNICALL) jboolean,
CallStaticByteMethod: fn ([*c]JNIEnv, jclass, jmethodID, ...) callconv(JNICALL) jbyte,
CallStaticByteMethodV: fn ([*c]JNIEnv, jclass, jmethodID, va_list) callconv(JNICALL) jbyte,
CallStaticByteMethodA: fn ([*c]JNIEnv, jclass, jmethodID, [*c]const jvalue) callconv(JNICALL) jbyte,
CallStaticCharMethod: fn ([*c]JNIEnv, jclass, jmethodID, ...) callconv(JNICALL) jchar,
CallStaticCharMethodV: fn ([*c]JNIEnv, jclass, jmethodID, va_list) callconv(JNICALL) jchar,
CallStaticCharMethodA: fn ([*c]JNIEnv, jclass, jmethodID, [*c]const jvalue) callconv(JNICALL) jchar,
CallStaticShortMethod: fn ([*c]JNIEnv, jclass, jmethodID, ...) callconv(JNICALL) jshort,
CallStaticShortMethodV: fn ([*c]JNIEnv, jclass, jmethodID, va_list) callconv(JNICALL) jshort,
CallStaticShortMethodA: fn ([*c]JNIEnv, jclass, jmethodID, [*c]const jvalue) callconv(JNICALL) jshort,
CallStaticIntMethod: fn ([*c]JNIEnv, jclass, jmethodID, ...) callconv(JNICALL) jint,
CallStaticIntMethodV: fn ([*c]JNIEnv, jclass, jmethodID, va_list) callconv(JNICALL) jint,
CallStaticIntMethodA: fn ([*c]JNIEnv, jclass, jmethodID, [*c]const jvalue) callconv(JNICALL) jint,
CallStaticLongMethod: fn ([*c]JNIEnv, jclass, jmethodID, ...) callconv(JNICALL) jlong,
CallStaticLongMethodV: fn ([*c]JNIEnv, jclass, jmethodID, va_list) callconv(JNICALL) jlong,
CallStaticLongMethodA: fn ([*c]JNIEnv, jclass, jmethodID, [*c]const jvalue) callconv(JNICALL) jlong,
CallStaticFloatMethod: fn ([*c]JNIEnv, jclass, jmethodID, ...) callconv(JNICALL) jfloat,
CallStaticFloatMethodV: fn ([*c]JNIEnv, jclass, jmethodID, va_list) callconv(JNICALL) jfloat,
CallStaticFloatMethodA: fn ([*c]JNIEnv, jclass, jmethodID, [*c]const jvalue) callconv(JNICALL) jfloat,
CallStaticDoubleMethod: fn ([*c]JNIEnv, jclass, jmethodID, ...) callconv(JNICALL) jdouble,
CallStaticDoubleMethodV: fn ([*c]JNIEnv, jclass, jmethodID, va_list) callconv(JNICALL) jdouble,
CallStaticDoubleMethodA: fn ([*c]JNIEnv, jclass, jmethodID, [*c]const jvalue) callconv(JNICALL) jdouble,
CallStaticVoidMethod: fn ([*c]JNIEnv, jclass, jmethodID, ...) callconv(JNICALL) void,
CallStaticVoidMethodV: fn ([*c]JNIEnv, jclass, jmethodID, va_list) callconv(JNICALL) void,
CallStaticVoidMethodA: fn ([*c]JNIEnv, jclass, jmethodID, [*c]const jvalue) callconv(JNICALL) void,
GetStaticFieldID: fn ([*c]JNIEnv, jclass, [*c]const u8, [*c]const u8) callconv(JNICALL) jfieldID,
GetStaticObjectField: fn ([*c]JNIEnv, jclass, jfieldID) callconv(JNICALL) jobject,
GetStaticBooleanField: fn ([*c]JNIEnv, jclass, jfieldID) callconv(JNICALL) jboolean,
GetStaticByteField: fn ([*c]JNIEnv, jclass, jfieldID) callconv(JNICALL) jbyte,
GetStaticCharField: fn ([*c]JNIEnv, jclass, jfieldID) callconv(JNICALL) jchar,
GetStaticShortField: fn ([*c]JNIEnv, jclass, jfieldID) callconv(JNICALL) jshort,
GetStaticIntField: fn ([*c]JNIEnv, jclass, jfieldID) callconv(JNICALL) jint,
GetStaticLongField: fn ([*c]JNIEnv, jclass, jfieldID) callconv(JNICALL) jlong,
GetStaticFloatField: fn ([*c]JNIEnv, jclass, jfieldID) callconv(JNICALL) jfloat,
GetStaticDoubleField: fn ([*c]JNIEnv, jclass, jfieldID) callconv(JNICALL) jdouble,
SetStaticObjectField: fn ([*c]JNIEnv, jclass, jfieldID, jobject) callconv(JNICALL) void,
SetStaticBooleanField: fn ([*c]JNIEnv, jclass, jfieldID, jboolean) callconv(JNICALL) void,
SetStaticByteField: fn ([*c]JNIEnv, jclass, jfieldID, jbyte) callconv(JNICALL) void,
SetStaticCharField: fn ([*c]JNIEnv, jclass, jfieldID, jchar) callconv(JNICALL) void,
SetStaticShortField: fn ([*c]JNIEnv, jclass, jfieldID, jshort) callconv(JNICALL) void,
SetStaticIntField: fn ([*c]JNIEnv, jclass, jfieldID, jint) callconv(JNICALL) void,
SetStaticLongField: fn ([*c]JNIEnv, jclass, jfieldID, jlong) callconv(JNICALL) void,
SetStaticFloatField: fn ([*c]JNIEnv, jclass, jfieldID, jfloat) callconv(JNICALL) void,
SetStaticDoubleField: fn ([*c]JNIEnv, jclass, jfieldID, jdouble) callconv(JNICALL) void,
NewString: fn ([*c]JNIEnv, [*c]const jchar, jsize) callconv(JNICALL) jstring,
GetStringLength: fn ([*c]JNIEnv, jstring) callconv(JNICALL) jsize,
GetStringChars: fn ([*c]JNIEnv, jstring, [*c]jboolean) callconv(JNICALL) [*c]const jchar,
ReleaseStringChars: fn ([*c]JNIEnv, jstring, [*c]const jchar) callconv(JNICALL) void,
NewStringUTF: fn ([*c]JNIEnv, [*c]const u8) callconv(JNICALL) jstring,
GetStringUTFLength: fn ([*c]JNIEnv, jstring) callconv(JNICALL) jsize,
GetStringUTFChars: fn ([*c]JNIEnv, jstring, [*c]jboolean) callconv(JNICALL) [*c]const u8,
ReleaseStringUTFChars: fn ([*c]JNIEnv, jstring, [*c]const u8) callconv(JNICALL) void,
GetArrayLength: fn ([*c]JNIEnv, jarray) callconv(JNICALL) jsize,
NewObjectArray: fn ([*c]JNIEnv, jsize, jclass, jobject) callconv(JNICALL) jobjectArray,
GetObjectArrayElement: fn ([*c]JNIEnv, jobjectArray, jsize) callconv(JNICALL) jobject,
SetObjectArrayElement: fn ([*c]JNIEnv, jobjectArray, jsize, jobject) callconv(JNICALL) void,
NewBooleanArray: fn ([*c]JNIEnv, jsize) callconv(JNICALL) jbooleanArray,
NewByteArray: fn ([*c]JNIEnv, jsize) callconv(JNICALL) jbyteArray,
NewCharArray: fn ([*c]JNIEnv, jsize) callconv(JNICALL) jcharArray,
NewShortArray: fn ([*c]JNIEnv, jsize) callconv(JNICALL) jshortArray,
NewIntArray: fn ([*c]JNIEnv, jsize) callconv(JNICALL) jintArray,
NewLongArray: fn ([*c]JNIEnv, jsize) callconv(JNICALL) jlongArray,
NewFloatArray: fn ([*c]JNIEnv, jsize) callconv(JNICALL) jfloatArray,
NewDoubleArray: fn ([*c]JNIEnv, jsize) callconv(JNICALL) jdoubleArray,
GetBooleanArrayElements: fn ([*c]JNIEnv, jbooleanArray, [*c]jboolean) callconv(JNICALL) [*c]jboolean,
GetByteArrayElements: fn ([*c]JNIEnv, jbyteArray, [*c]jboolean) callconv(JNICALL) [*c]jbyte,
GetCharArrayElements: fn ([*c]JNIEnv, jcharArray, [*c]jboolean) callconv(JNICALL) [*c]jchar,
GetShortArrayElements: fn ([*c]JNIEnv, jshortArray, [*c]jboolean) callconv(JNICALL) [*c]jshort,
GetIntArrayElements: fn ([*c]JNIEnv, jintArray, [*c]jboolean) callconv(JNICALL) [*c]jint,
GetLongArrayElements: fn ([*c]JNIEnv, jlongArray, [*c]jboolean) callconv(JNICALL) [*c]jlong,
GetFloatArrayElements: fn ([*c]JNIEnv, jfloatArray, [*c]jboolean) callconv(JNICALL) [*c]jfloat,
GetDoubleArrayElements: fn ([*c]JNIEnv, jdoubleArray, [*c]jboolean) callconv(JNICALL) [*c]jdouble,
ReleaseBooleanArrayElements: fn ([*c]JNIEnv, jbooleanArray, [*c]jboolean, jint) callconv(JNICALL) void,
ReleaseByteArrayElements: fn ([*c]JNIEnv, jbyteArray, [*c]jbyte, jint) callconv(JNICALL) void,
ReleaseCharArrayElements: fn ([*c]JNIEnv, jcharArray, [*c]jchar, jint) callconv(JNICALL) void,
ReleaseShortArrayElements: fn ([*c]JNIEnv, jshortArray, [*c]jshort, jint) callconv(JNICALL) void,
ReleaseIntArrayElements: fn ([*c]JNIEnv, jintArray, [*c]jint, jint) callconv(JNICALL) void,
ReleaseLongArrayElements: fn ([*c]JNIEnv, jlongArray, [*c]jlong, jint) callconv(JNICALL) void,
ReleaseFloatArrayElements: fn ([*c]JNIEnv, jfloatArray, [*c]jfloat, jint) callconv(JNICALL) void,
ReleaseDoubleArrayElements: fn ([*c]JNIEnv, jdoubleArray, [*c]jdouble, jint) callconv(JNICALL) void,
GetBooleanArrayRegion: fn ([*c]JNIEnv, jbooleanArray, jsize, jsize, [*c]jboolean) callconv(JNICALL) void,
GetByteArrayRegion: fn ([*c]JNIEnv, jbyteArray, jsize, jsize, [*c]jbyte) callconv(JNICALL) void,
GetCharArrayRegion: fn ([*c]JNIEnv, jcharArray, jsize, jsize, [*c]jchar) callconv(JNICALL) void,
GetShortArrayRegion: fn ([*c]JNIEnv, jshortArray, jsize, jsize, [*c]jshort) callconv(JNICALL) void,
GetIntArrayRegion: fn ([*c]JNIEnv, jintArray, jsize, jsize, [*c]jint) callconv(JNICALL) void,
GetLongArrayRegion: fn ([*c]JNIEnv, jlongArray, jsize, jsize, [*c]jlong) callconv(JNICALL) void,
GetFloatArrayRegion: fn ([*c]JNIEnv, jfloatArray, jsize, jsize, [*c]jfloat) callconv(JNICALL) void,
GetDoubleArrayRegion: fn ([*c]JNIEnv, jdoubleArray, jsize, jsize, [*c]jdouble) callconv(JNICALL) void,
SetBooleanArrayRegion: fn ([*c]JNIEnv, jbooleanArray, jsize, jsize, [*c]const jboolean) callconv(JNICALL) void,
SetByteArrayRegion: fn ([*c]JNIEnv, jbyteArray, jsize, jsize, [*c]const jbyte) callconv(JNICALL) void,
SetCharArrayRegion: fn ([*c]JNIEnv, jcharArray, jsize, jsize, [*c]const jchar) callconv(JNICALL) void,
SetShortArrayRegion: fn ([*c]JNIEnv, jshortArray, jsize, jsize, [*c]const jshort) callconv(JNICALL) void,
SetIntArrayRegion: fn ([*c]JNIEnv, jintArray, jsize, jsize, [*c]const jint) callconv(JNICALL) void,
SetLongArrayRegion: fn ([*c]JNIEnv, jlongArray, jsize, jsize, [*c]const jlong) callconv(JNICALL) void,
SetFloatArrayRegion: fn ([*c]JNIEnv, jfloatArray, jsize, jsize, [*c]const jfloat) callconv(JNICALL) void,
SetDoubleArrayRegion: fn ([*c]JNIEnv, jdoubleArray, jsize, jsize, [*c]const jdouble) callconv(JNICALL) void,
RegisterNatives: fn ([*c]JNIEnv, jclass, [*c]const JNINativeMethod, jint) callconv(JNICALL) jint,
UnregisterNatives: fn ([*c]JNIEnv, jclass) callconv(JNICALL) jint,
MonitorEnter: fn ([*c]JNIEnv, jobject) callconv(JNICALL) jint,
MonitorExit: fn ([*c]JNIEnv, jobject) callconv(JNICALL) jint,
GetJavaVM: fn ([*c]JNIEnv, [*c][*c]JavaVM) callconv(JNICALL) jint,
GetStringRegion: fn ([*c]JNIEnv, jstring, jsize, jsize, [*c]jchar) callconv(JNICALL) void,
GetStringUTFRegion: fn ([*c]JNIEnv, jstring, jsize, jsize, [*c]u8) callconv(JNICALL) void,
GetPrimitiveArrayCritical: fn ([*c]JNIEnv, jarray, [*c]jboolean) callconv(JNICALL) ?*c_void,
ReleasePrimitiveArrayCritical: fn ([*c]JNIEnv, jarray, ?*c_void, jint) callconv(JNICALL) void,
GetStringCritical: fn ([*c]JNIEnv, jstring, [*c]jboolean) callconv(JNICALL) [*c]const jchar,
ReleaseStringCritical: fn ([*c]JNIEnv, jstring, [*c]const jchar) callconv(JNICALL) void,
NewWeakGlobalRef: fn ([*c]JNIEnv, jobject) callconv(JNICALL) jweak,
DeleteWeakGlobalRef: fn ([*c]JNIEnv, jweak) callconv(JNICALL) void,
ExceptionCheck: fn ([*c]JNIEnv) callconv(JNICALL) jboolean,
NewDirectByteBuffer: fn ([*c]JNIEnv, ?*c_void, jlong) callconv(JNICALL) jobject,
GetDirectBufferAddress: fn ([*c]JNIEnv, jobject) callconv(JNICALL) ?*c_void,
GetDirectBufferCapacity: fn ([*c]JNIEnv, jobject) callconv(JNICALL) jlong,
GetObjectReferenceKind: fn ([*c]JNIEnv, jobject) callconv(JNICALL) ObjectReferenceKind,
GetModule: fn ([*c]JNIEnv, jclass) callconv(JNICALL) jobject,
};
const JNIInvokeInterface = extern struct {
reserved0: ?*c_void,
reserved1: ?*c_void,
reserved2: ?*c_void,
DestroyJavaVM: fn ([*c]JavaVM) callconv(JNICALL) jint,
AttachCurrentThread: fn ([*c]JavaVM, [*c]?*c_void, ?*c_void) callconv(JNICALL) jint,
DetachCurrentThread: fn ([*c]JavaVM) callconv(JNICALL) jint,
GetEnv: fn ([*c]JavaVM, [*c]?*c_void, jint) callconv(JNICALL) jint,
AttachCurrentThreadAsDaemon: fn ([*c]JavaVM, [*c]?*c_void, ?*c_void) callconv(JNICALL) jint,
};
fn handleFailureError(return_val: jint) JNIFailureError!void {
if (return_val < 0 and return_val >= -6) {
inline for (comptime std.meta.fields(JNIFailureError)) |err, i| {
if (i == -return_val - 1)
return @field(JNIFailureError, err.name);
}
}
if (return_val < 0) return JNIFailureError.Unknown;
}
pub const JNIVersion = packed struct {
minor: u16,
major: u16,
};
pub const JNIEnv = extern struct {
const Self = @This();
interface: *const JNINativeInterface,
// Utils
pub fn getClassNameOfObject(self: *Self, obj: jobject) jstring {
var cls = self.getObjectClass(obj);
// First get the class object
var mid = self.interface.GetMethodID(self, cls, "getClass", "()Ljava/lang/Class;");
var clsObj = self.interface.CallObjectMethod(self, obj, mid);
// Now get the class object's class descriptor
cls = self.getObjectClass(clsObj);
// Find the getName() method on the class object
mid = self.interface.GetMethodID(self, cls, "getName", "()Ljava/lang/String;");
// Call the getName() to get a jstring object back
var strObj = self.interface.CallObjectMethod(self, clsObj, mid);
return strObj;
}
/// Handles a known error
/// Only use this if you're 100% sure an error/exception has occurred
fn handleKnownError(self: *Self, comptime Set: type) Set {
var throwable = self.getPendingException();
var name_str = self.getClassNameOfObject(throwable);
var name = self.interface.GetStringUTFChars(self, name_str, null);
defer self.interface.ReleaseStringUTFChars(self, name_str, name);
var n = std.mem.span(@ptrCast([*:0]const u8, name));
var eon = n[std.mem.lastIndexOf(u8, n, ".").? + 1 ..];
var x = std.hash.Wyhash.hash(0, eon);
inline for (comptime std.meta.fields(Set)) |err| {
var z = std.hash.Wyhash.hash(0, err.name);
if (x == z) {
self.clearPendingException();
return @field(Set, err.name);
}
}
const first = comptime std.meta.fields(Set)[0];
return @field(Set, first.name);
}
// Version Information
/// Gets the JNI version (not the Java version!)
pub fn getJNIVersion(self: *Self) JNIVersion {
var version = self.interface.GetVersion(self);
return @bitCast(JNIVersion, version);
}
// Class Operations
pub const DefineClassError = error{
/// The class data does not specify a valid class
ClassFormatError,
/// A class or interface would be its own superclass or superinterface
ClassCircularityError,
OutOfMemoryError,
/// The caller attempts to define a class in the "java" package tree
SecurityException,
};
/// Takes a ClassLoader and buffer containing a classfile
/// Buffer can be discarded after use
/// The name is always null as it is a redudant argument
pub fn defineClass(self: *Self, loader: jobject, buf: []const u8) DefineClassError!jclass {
var maybe_class = self.interface.DefineClass(self, null, loader, @ptrCast([*c]const jbyte, buf), @intCast(jsize, buf.len));
return if (maybe_class) |class|
class
else
return self.handleKnownError(DefineClassError);
}
pub const FindClassError = error{
/// The class data does not specify a valid class
ClassFormatError,
/// A class or interface would be its own superclass or superinterface
ClassCircularityError,
/// No definition for a requested class or interface can be found
NoClassDefFoundError,
OutOfMemoryError,
};
/// This function loads a locally-defined class
pub fn findClass(self: *Self, name: [*:0]const u8) FindClassError!jclass {
var maybe_class = self.interface.FindClass(self, name);
return if (maybe_class) |class|
class
else
return self.handleKnownError(FindClassError);
}
/// Gets superclass of class
/// If class specifies the class Object, or class represents an interface, this function returns null
pub fn getSuperclass(self: *Self, class: jclass) jclass {
return self.interface.GetSuperclass(self, class);
}
/// Determines whether an object of class1 can be safely cast to class2
pub fn canBeCastTo(self: *Self, class1: jclass, class2: jclass) bool {
return self.interface.IsAssignableFrom(class1, class2) == 1;
}
// Module Operations
/// Returns the java.lang.Module object for the module that the class is a member of
/// If the class is not in a named module then the unnamed module of the class loader for the class is returned
/// If the class represents an array type then this function returns the Module object for the element type
/// If the class represents a primitive type or void, then the Module object for the java.base module is returned
pub fn getModule(self: *Self, class: jclass) jobject {
return self.interface.GetModule(self, class);
}
// Exceptions
/// Causes a java.lang.Throwable object to be thrown
pub fn throw(self: *Self, throwable: jthrowable) JNIFailureError!void {
try handleFailureError(self.interface.Throw(self, throwable));
}
/// Constructs an exception object from the specified class with the message specified by message and causes that exception to be thrown
pub fn throwNew(self: *Self, class: jclass, message: [*:0]const u8) JNIFailureError!void {
try handleFailureError(self.interface.ThrowNew(self, class, message));
}
/// Throws a generic java.lang.Excpetion with the specified message
pub fn throwGeneric(self: *Self, message: [*:0]const u8) !void {
var class = try self.findClass("java/lang/Exception");
return self.throwNew(class, message);
}
/// Gets the exception object that is currently in the process of being thrown
pub fn getPendingException(self: *Self) jthrowable {
return self.interface.ExceptionOccurred(self);
}
/// Prints an exception and a backtrace of the stack to a system error-reporting channel, such as stderr
pub fn describeException(self: *Self) void {
self.interface.ExceptionDescribe(self);
}
/// Clears any exception that is currently being thrown
pub fn clearPendingException(self: *Self) void {
self.interface.ExceptionClear(self);
}
/// Raises a fatal error and does not expect the VM to recover
pub fn fatalError(self: *Self, message: [*:0]const u8) noreturn {
self.interface.FatalError(self, message);
}
/// Determines if an exception is being thrown
pub fn hasPendingException(self: *Self) bool {
return self.interface.ExceptionCheck(self) == 1;
}
// References
pub const NewReferenceError = error{
/// Errors/exceptions returned by New*Ref are super ambigious so sadly this is the best solution :(
ReferenceError,
};
/// Create a new reference based on an existing reference
pub fn newReference(self: *Self, kind: ObjectReferenceKind, reference: jobject) NewReferenceError!jobject {
var maybe_reference = switch (kind) {
.global => self.interface.NewGlobalRef(self, reference),
.local => self.interface.NewLocalRef(self, reference),
.weak_global => self.interface.NewWeakGlobalRef(self, reference),
else => unreachable,
};
if (maybe_reference) |new_reference| {
return new_reference;
} else {
self.clearPendingException();
return error.ReferenceError;
}
}
/// Deletes a reference
pub fn deleteReference(self: *Self, kind: ObjectReferenceKind, reference: jobject) void {
switch (kind) {
.global => self.interface.DeleteGlobalRef(self, reference),
.local => self.interface.DeleteLocalRef(self, reference),
.weak_global => self.interface.DeleteWeakGlobalRef(self, reference),
else => unreachable,
}
}
/// Ensures that at least a given number of local references can be created in the current thread
pub fn ensureLocalCapacity(self: *Self, capacity: jint) JNIFailureError!void {
std.debug.assert(capacity >= 0);
return handleFailureError(self.interface.EnsureLocalCapacity(self, capacity));
}
/// Creates a new local reference frame, in which at least a given number of local references can be created
/// Useful for not polluting the thread frame
/// Think of it like an ArenaAllocator for your native function
pub fn pushLocalFrame(self: *Self, capacity: jint) JNIFailureError!void {
std.debug.assert(capacity > 0);
return handleFailureError(self.interface.PushLocalFrame(self, capacity));
}
/// Pops a local frame
/// Result is an object you want to pass back to the previous frame
/// If you don't want to pass anything back, it can be null
pub fn popLocalFrame(self: *Self, result: jobject) jobject {
return self.interface.PopLocalFrame(self, result);
}
// Object Operations
pub const AllocObjectError = error{
/// The class is an interface or an abstract class
InstantiationException,
OutOfMemoryError,
};
/// Allocates a new Java object without invoking any of the constructors for the object, then returns a reference to the object
/// NOTE: Objects created with this function are not eligible for finalization
pub fn allocObject(self: *Self, class: jclass) AllocObjectError!jobject {
var maybe_object = self.interface.AllocObject(self, class);
return if (maybe_object) |object|
object
else
return self.handleKnownError(AllocObjectError);
}
pub const NewObjectError = error{
/// Any exception thrown by the constructor
Exception,
/// The class is an interface or an abstract class
InstantiationException,
OutOfMemoryError,
};
/// Constructs a new Java object
/// The passed method_id must be a constructor, and args must match
/// Class must not be an array (see newArray!)
pub fn newObject(self: *Self, class: jclass, method_id: jmethodID, args: ?[*]const jvalue) NewObjectError!jobject {
var maybe_object = self.interface.NewObjectA(self, class, method_id, args);
return if (maybe_object) |object|
object
else
return self.handleKnownError(NewObjectError);
}
/// Returns the class of an object
pub fn getObjectClass(self: *Self, object: jobject) jclass {
std.debug.assert(object != null);
return self.interface.GetObjectClass(self, object);
}
/// Returns the type of an reference, see ObjectReferenceKind for details
pub fn getObjectReferenceKind(self: *Self, object: jobject) ObjectReferenceKind {
return self.interface.GetObjectReferenceKind(self, object);
}
/// Tests whether an object is an instance of a class
pub fn isInstanceOf(self: *Self, object: jobject, class: jclass) bool {
return self.interface.IsInstanceOf(self, object, class) == 1;
}
/// Tests whether two references refer to the same Java object
/// NOTE: This is **not** `.equals`, it's `==` - we're comparing references, not values!
pub fn isSameObject(self: *Self, object1: jobject, object2: jobject) bool {
return self.interface.IsSameObject(self, object1, object2) == 1;
}
// Accessing Fields of Objects
pub const GetFieldIdError = error{
/// The specified field cannot be found
NoSuchFieldError,
/// The class initializer fails due to an exception
ExceptionInInitializerError,
OutOfMemoryError,
};
/// Returns the field ID for an instance (nonstatic) field of a class; the field is specified by its name and signature
pub fn getFieldId(self: *Self, class: jclass, name: [*:0]const u8, signature: [*:0]const u8) GetFieldIdError!jfieldID {
var maybe_jfieldid = self.interface.GetFieldID(self, class, name, signature);
return if (maybe_jfieldid) |object|
object
else
return self.handleKnownError(GetFieldIdError);
}
/// Gets the value of a field
pub fn getField(self: *Self, comptime native_type: NativeType, object: jobject, field_id: jfieldID) MapNativeType(native_type) {
return (switch (native_type) {
.object => self.interface.GetObjectField,
.boolean => self.interface.GetBooleanField,
.byte => self.interface.GetByteField,
.char => self.interface.GetCharField,
.short => self.interface.GetShortField,
.int => self.interface.GetIntField,
.long => self.interface.GetLongField,
.float => self.interface.GetFloatField,
.double => self.interface.GetDoubleField,
.void => @compileError("Field cannot be of type 'void'"),
})(self, object, field_id);
}
/// Sets the value of a field
pub fn setField(self: *Self, comptime native_type: NativeType, object: jobject, field_id: jobject, value: MapNativeType(native_type)) void {
(switch (native_type) {
.object => self.interface.SetObjectField,
.boolean => self.interface.SetBooleanField,
.byte => self.interface.SetByteField,
.char => self.interface.SetCharField,
.short => self.interface.SetShortField,
.int => self.interface.SetIntField,
.long => self.interface.SetLongField,
.float => self.interface.SetFloatField,
.double => self.interface.SetDoubleField,
.void => @compileError("Field cannot be of type 'void'"),
})(self, object, field_id, value);
}
// Calling Instance Methods
pub const GetMethodIdError = error{
/// The specified method cannot be found
NoSuchMethodError,
/// The class initializer fails due to an exception
ExceptionInInitializerError,
OutOfMemoryError,
};
/// Returns the method ID for an instance (nonstatic) method of a class or interface
pub fn getMethodId(self: *Self, class: jclass, name: [*:0]const u8, signature: [*:0]const u8) GetMethodIdError!jmethodID {
var maybe_jmethodid = self.interface.GetMethodID(self, class, name, signature);
return if (maybe_jmethodid) |object|
object
else
return self.handleKnownError(GetMethodIdError);
}
pub const CallMethodError = error{Exception};
/// Invoke an instance (nonstatic) method on a Java object
pub fn callMethod(self: *Self, comptime native_type: NativeType, object: jobject, method_id: jmethodID, args: ?[*]const jvalue) CallMethodError!MapNativeType(native_type) {
var value = (switch (native_type) {
.object => self.interface.CallObjectMethodA,
.boolean => self.interface.CallBooleanMethodA,
.byte => self.interface.CallByteMethodA,
.char => self.interface.CallCharMethodA,
.short => self.interface.CallShortMethodA,
.int => self.interface.CallIntMethodA,
.long => self.interface.CallLongMethodA,
.float => self.interface.CallFloatMethodA,
.double => self.interface.CallDoubleMethodA,
.void => self.interface.CallVoidMethodA,
})(self, object, method_id, args);
return if (self.hasPendingException()) error.Exception else value;
}
pub const CallNonVirtualMethodError = error{Exception};
/// Invoke an instance (nonstatic) method on a Java object based on `class`'s implementation of the method
pub fn callNonVirtualMethod(self: *Self, comptime native_type: NativeType, object: jobject, class: jclass, method_id: jmethodID, args: ?[*]const jvalue) CallNonVirtualMethodError!MapNativeType(native_type) {
var value = (switch (native_type) {
.object => self.interface.CallNonvirtualObjectMethodA,
.boolean => self.interface.CallNonvirtualBooleanMethodA,
.byte => self.interface.CallNonvirtualByteMethodA,
.char => self.interface.CallNonvirtualCharMethodA,
.short => self.interface.CallNonvirtualShortMethodA,
.int => self.interface.CallNonvirtualIntMethodA,
.long => self.interface.CallNonvirtualLongMethodA,
.float => self.interface.CallNonvirtualFloatMethodA,
.double => self.interface.CallNonvirtualDoubleMethodA,
.void => self.interface.CallNonvirtualVoidMethodA,
})(self, object, class, method_id, args);
return if (self.hasPendingException()) error.Exception else value;
}
// Accessing Static Fields
pub const GetStaticFieldIdError = error{
/// The specified field cannot be found
NoSuchFieldError,
/// The class initializer fails due to an exception
ExceptionInInitializerError,
OutOfMemoryError,
};
pub fn getStaticFieldId(self: *Self, class: jclass, name: [*:0]const u8, signature: [*:0]const u8) GetStaticFieldIdError!jfieldID {
var maybe_jfieldid = self.interface.GetStaticFieldID(self, class, name, signature);
return if (maybe_jfieldid) |object|
object
else
return self.handleKnownError(GetStaticFieldIdError);
}
/// Gets the value of a field
pub fn getStaticField(self: *Self, comptime native_type: NativeType, class: jclass, field_id: jfieldID) MapNativeType(native_type) {
return (switch (native_type) {
.object => self.interface.GetStaticObjectField,
.boolean => self.interface.GetStaticBooleanField,
.byte => self.interface.GetStaticByteField,
.char => self.interface.GetStaticCharField,
.short => self.interface.GetStaticShortField,
.int => self.interface.GetStaticIntField,
.long => self.interface.GetStaticLongField,
.float => self.interface.GetStaticFloatField,
.double => self.interface.GetStaticDoubleField,
.void => @compileError("Field cannot be of type 'void'"),
})(self, class, field_id);
}
/// Sets the value of a field
pub fn setStaticField(self: *Self, comptime native_type: NativeType, class: jclass, field_id: jobject, value: MapNativeType(native_type)) void {
(switch (native_type) {
.object => self.interface.SetStaticObjectField,
.boolean => self.interface.SetStaticBooleanField,
.byte => self.interface.SetStaticByteField,
.char => self.interface.SetStaticCharField,
.short => self.interface.SetStaticShortField,
.int => self.interface.SetStaticIntField,
.long => self.interface.SetStaticLongField,
.float => self.interface.SetStaticFloatField,
.double => self.interface.SetStaticDoubleField,
.void => unreachable,
})(self, class, field_id, value);
}
// Calling Static Methods
pub const GetStaticMethodIdError = error{
/// The specified method cannot be found
NoSuchMethodError,
/// The class initializer fails due to an exception
ExceptionInInitializerError,
OutOfMemoryError,
};
/// Returns the method ID for a static method of a class
pub fn getStaticMethodId(self: *Self, class: jclass, name: [*:0]const u8, signature: [*:0]const u8) GetStaticMethodIdError!jmethodID {
var maybe_jmethodid = self.interface.GetStaticMethodID(self, class, name, signature);
return if (maybe_jmethodid) |object|
object
else
return self.handleKnownError(GetStaticMethodIdError);
}
pub const CallStaticMethodError = error{Exception};
/// Invoke an instance (nonstatic) method on a Java object
pub fn callStaticMethod(self: *Self, comptime native_type: NativeType, class: jclass, method_id: jmethodID, args: ?[*]const jvalue) CallStaticMethodError!MapNativeType(native_type) {
var value = (switch (native_type) {
.object => self.interface.CallStaticObjectMethodA,
.boolean => self.interface.CallStaticBooleanMethodA,
.byte => self.interface.CallStaticByteMethodA,
.char => self.interface.CallStaticCharMethodA,
.short => self.interface.CallStaticShortMethodA,
.int => self.interface.CallStaticIntMethodA,
.long => self.interface.CallStaticLongMethodA,
.float => self.interface.CallStaticFloatMethodA,
.double => self.interface.CallStaticDoubleMethodA,
.void => self.interface.CallStaticVoidMethodA,
})(self, class, method_id, args);
return if (self.hasPendingException()) error.Exception else value;
}
// String Operations
pub const NewStringError = error{OutOfMemoryError};
/// Constructs a new java.lang.String object from an array of Unicode characters
pub fn newString(self: *Self, unicode_chars: []const u16) NewStringError!jstring {
var maybe_jstring = self.interface.NewString(self, @ptrCast([*]const u16, unicode_chars), @intCast(jsize, unicode_chars.len));
return if (maybe_jstring) |string|
string
else
return self.handleKnownError(NewStringError);
}
/// Returns the length (the count of Unicode characters) of a Java string
pub fn getStringLength(self: *Self, string: jstring) jsize {
return self.interface.GetStringLength(self, string);
}
pub const GetStringCharsError = error{Unknown};
pub const GetStringCharsReturn = struct { chars: [*]const u16, is_copy: bool };
/// Returns a pointer to the array of Unicode characters of the string
/// Caller must release chars with `releaseStringChars`
pub fn getStringChars(self: *Self, string: jstring) GetStringCharsError!GetStringCharsReturn {
var is_copy: u8 = 0;
var maybe_chars = self.interface.GetStringChars(self, string, &is_copy);
return if (maybe_chars) |chars|
GetStringCharsReturn{ .chars = chars, .is_copy = is_copy == 1 }
else
error.Unknown;
}
/// Informs the VM that the native code no longer needs access to chars
pub fn releaseStringChars(self: *Self, string: jstring, chars: [*]const u16) void {
self.interface.ReleaseStringChars(self, string, chars);
}
pub const NewStringUTFError = error{OutOfMemoryError};
/// Constructs a new java.lang.String object from an array of characters in modified UTF-8 encoding
pub fn newStringUTF(self: *Self, buf: [*:0]const u8) NewStringUTFError!jstring {
var maybe_jstring = self.interface.NewStringUTF(self, buf);
return if (maybe_jstring) |string|
string
else
return self.handleKnownError(NewStringUTFError);
}
/// Returns the length in bytes of the modified UTF-8 representation of a string
pub fn getStringUTFLength(self: *Self, string: jstring) jsize {
return self.interface.GetStringUTFLength(self, string);
}
pub const GetStringUTFCharsError = error{Unknown};
pub const GetStringUTFCharsReturn = struct { chars: [*]const u8, is_copy: bool };
/// Returns a pointer to an array of bytes representing the string in modified UTF-8 encoding
/// Caller must release chars with `releaseStringUTFChars`
pub fn getStringUTFChars(self: *Self, string: jstring) GetStringUTFCharsError!GetStringUTFCharsReturn {
var is_copy: u8 = 0;
var maybe_chars = self.interface.GetStringUTFChars(self, string, &is_copy);
return if (maybe_chars) |chars|
GetStringUTFCharsReturn{ .chars = chars, .is_copy = is_copy == 1 }
else
error.Unknown;
}
/// Informs the VM that the native code no longer needs access to chars
pub fn releaseStringUTFChars(self: *Self, string: jstring, chars: [*:0]const u8) void {
self.interface.ReleaseStringUTFChars(self, string, chars);
}
pub const GetStringRegionError = error{StringIndexOutOfBoundsException};
/// Copies len number of Unicode characters beginning at offset start to the given buffer buf
pub fn getStringRegion(self: *Self, string: jstring, start: jsize, len: jsize, buf: []u16) GetStringRegionError!void {
var string_length = self.getStringLength(string);
std.debug.assert(start >= 0 and start < string_length);
std.debug.assert(len >= 0 and start + len < string_length);
self.interface.GetStringRegion(self, string, start, len, buf);
if (self.hasPendingException())
return error.StringIndexOutOfBoundsException;
}
pub const GetStringUTFRegionError = error{StringIndexOutOfBoundsException};
/// Translates len number of Unicode characters beginning at offset start into modified UTF-8 encoding and place the result in the given buffer buf
pub fn getStringUTFRegion(self: *Self, string: jstring, start: jsize, len: jsize, buf: []u8) GetStringUTFRegionError!void {
var string_length = self.getStringUTFLength(string);
std.debug.assert(start >= 0 and start < string_length);
std.debug.assert(len >= 0 and start + len < string_length);
self.interface.GetStringUTFRegion(self, string, start, len, buf);
if (self.hasPendingException())
return error.StringIndexOutOfBoundsException;
}
pub const GetStringCriticalError = error{Unknown};
pub const GetStringCriticalReturn = struct { chars: [*]const u16, is_copy: bool };
/// NOTE: This should only be used in non-blocking, fast-finishing functions
/// Returns a pointer to an array of bytes representing the string in modified UTF-8 encoding
/// Caller must release chars with `releaseStringCritical`
pub fn getStringCritical(self: *Self, string: jstring) GetStringCriticalError!GetStringCriticalReturn {
var is_copy: u8 = 0;
var maybe_chars = self.interface.GetStringCritical(self, string, &is_copy);
return if (maybe_chars) |chars|
GetStringCriticalReturn{ .chars = chars, .is_copy = is_copy == 1 }
else
error.Unknown;
}
/// Informs the VM that the native code no longer needs access to chars
pub fn releaseStringCritical(self: *Self, string: jstring, chars: [*]const u16) void {
self.interface.ReleaseStringCritical(self, string, chars);
}
// Variety Pack
};
pub const JavaVM = extern struct {
const Self = @This();
interface: *const JNIInvokeInterface,
pub fn getEnv(self: *Self, version: JNIVersion) JNIFailureError!*JNIEnv {
var env: *JNIEnv = undefined;
try handleFailureError(self.interface.GetEnv(self, @ptrCast([*c]?*c_void, &env), @bitCast(jint, version)));
return env;
}
}; | src/types.zig |
const std = @import("std");
const mem = std.mem;
const leb = std.leb;
const math = std.math;
const unicode = std.unicode;
const common = @import("common.zig");
const instruction = @import("instruction.zig");
const Instruction = @import("instruction.zig").Instruction;
const Instance = @import("instance.zig").Instance;
const ArrayList = std.ArrayList;
const opcode = @import("opcode.zig");
const Opcode = @import("opcode.zig").Opcode;
const ParseIterator = instruction.ParseIterator;
const OpcodeIterator = instruction.OpcodeIterator;
const FuncType = common.FuncType;
const ValueType = common.ValueType;
const Import = common.Import;
const Export = common.Export;
const Limit = common.Limit;
const LimitType = common.LimitType;
const Mutability = common.Mutability;
const Global = common.Global;
const Element = common.Element;
const Code = function.Code;
const Segment = common.Segment;
const Tag = common.Tag;
const LocalType = common.LocalType;
const Interpreter = @import("interpreter.zig").Interpreter;
const Store = @import("store.zig").ArrayListStore;
const Function = @import("function.zig").Function;
const RuntimeOpcode = @import("instruction.zig").RuntimeOpcode;
const function = @import("function.zig");
pub const Module = struct {
decoded: bool = false,
alloc: *mem.Allocator,
module: []const u8 = undefined,
buf: std.io.FixedBufferStream([]const u8) = undefined,
version: u32 = 0,
customs: Section(Custom),
types: Section(FuncType),
imports: Section(Import),
functions: Section(common.Function),
tables: Section(Limit),
memories: Section(Limit),
globals: Section(Global),
exports: Section(Export),
start: ?u32,
elements: Section(Segment),
codes: Section(Code),
datas: Section(Segment),
parsed_code: ArrayList(Instruction),
local_types: ArrayList(LocalType),
br_table_indices: ArrayList(u32),
function_index_start: ?usize,
pub fn init(alloc: *mem.Allocator, module: []const u8) Module {
return Module{
.alloc = alloc,
.module = module,
.buf = std.io.fixedBufferStream(module),
.customs = Section(Custom).init(alloc),
.types = Section(FuncType).init(alloc),
.imports = Section(Import).init(alloc),
.functions = Section(common.Function).init(alloc),
.tables = Section(Limit).init(alloc),
.memories = Section(Limit).init(alloc),
.globals = Section(Global).init(alloc),
.exports = Section(Export).init(alloc),
.start = null,
.elements = Section(Segment).init(alloc),
.codes = Section(Code).init(alloc),
.datas = Section(Segment).init(alloc),
.parsed_code = ArrayList(Instruction).init(alloc),
.local_types = ArrayList(LocalType).init(alloc),
.br_table_indices = ArrayList(u32).init(alloc),
.function_index_start = null,
};
}
pub fn decode(self: *Module) !void {
const rd = self.buf.reader();
const magic = try rd.readBytesNoEof(4);
if (!mem.eql(u8, magic[0..], "\x00asm")) return error.MagicNumberNotFound;
const version = try rd.readIntLittle(u32);
if (version != 1) return error.UnknownBinaryVersion;
// Push an initial return instruction so we don't have to
// track the end of a function to use its return on invoke
try self.parsed_code.append(.@"return");
var i: usize = 0;
while (true) : (i += 1) {
self.decodeSection() catch |err| {
switch (err) {
error.EndOfStream => {
break;
},
else => return err,
}
};
try self.verify();
}
try self.verify();
if (self.codes.list.items.len != nonImportCount(self.functions.list.items)) return error.FunctionCodeSectionsInconsistent;
self.decoded = true;
}
pub fn verify(self: *Module) !void {
if (self.types.count != self.types.list.items.len) return error.TypeCountMismatch;
if (self.imports.count != self.imports.list.items.len) return error.ImportsCountMismatch;
if (self.functions.count != nonImportCount(self.functions.list.items)) return error.FunctionsCountMismatch;
if (self.tables.count != nonImportCount(self.tables.list.items)) return error.TablesCountMismatch;
if (self.memories.count != nonImportCount(self.memories.list.items)) return error.MemoriesCountMismatch;
if (self.globals.count != nonImportCount(self.globals.list.items)) return error.GlobalsCountMismatch;
if (self.exports.count != self.exports.list.items.len) return error.ExportsCountMismatch;
if (self.elements.count != self.elements.list.items.len) return error.ElementsCountMismatch;
if (self.codes.count != self.codes.list.items.len) return error.CodesCountMismatch;
if (self.datas.count != self.datas.list.items.len) return error.DatasCountMismatch;
}
// Some types can be imported. For validation we want to check the non-imported
// counts of each type match the what is stated in the binary. This function
// counts the non-imports.
fn nonImportCount(imported_type: anytype) usize {
var count: usize = 0;
for (imported_type) |import| {
if (import.import == null) count += 1;
}
return count;
}
pub fn decodeSection(self: *Module) !void {
const rd = self.buf.reader();
const id: SectionType = rd.readEnum(SectionType, .Little) catch |err| switch (err) {
error.InvalidValue => return error.UnknownSectionId,
else => return err,
};
const size = leb.readULEB128(u32, rd) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
const section_start = rd.context.pos;
switch (id) {
.Custom => try self.decodeCustomSection(size),
.Type => try self.decodeTypeSection(),
.Import => try self.decodeImportSection(),
.Function => try self.decodeFunctionSection(),
.Table => try self.decodeTableSection(),
.Memory => try self.decodeMemorySection(),
.Global => try self.decodeGlobalSection(),
.Export => try self.decodeExportSection(),
.Start => try self.decodeStartSection(),
.Element => try self.decodeElementSection(),
.Code => try self.decodeCodeSection(),
.Data => try self.decodeDataSection(),
}
const section_end = rd.context.pos;
if (section_end - section_start != size) return error.MalformedSectionMismatchedSize;
}
fn decodeTypeSection(self: *Module) !void {
const rd = self.buf.reader();
const count = leb.readULEB128(u32, rd) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
self.types.count = count;
var f: usize = 0;
while (f < count) : (f += 1) {
const tag: u8 = rd.readByte() catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
if (tag != 0x60) return error.ExpectedFuncTypeTag;
const param_count = leb.readULEB128(u32, rd) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
const params_start = rd.context.pos;
{
var i: usize = 0;
while (i < param_count) : (i += 1) {
_ = rd.readEnum(ValueType, .Little) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
}
}
const params_end = rd.context.pos;
const results_count = leb.readULEB128(u32, rd) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
const results_start = rd.context.pos;
{
var i: usize = 0;
while (i < results_count) : (i += 1) {
_ = rd.readEnum(ValueType, .Little) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
}
}
const results_end = rd.context.pos;
var params = self.module[params_start..params_end];
var results = self.module[results_start..results_end];
var params_value_type: []const ValueType = undefined;
params_value_type.ptr = @ptrCast([*]const ValueType, params.ptr);
params_value_type.len = params.len;
var results_value_type: []const ValueType = undefined;
results_value_type.ptr = @ptrCast([*]const ValueType, results.ptr);
results_value_type.len = results.len;
try self.types.list.append(FuncType{
.params = params_value_type,
.results = results_value_type,
});
}
}
fn decodeImportSection(self: *Module) !void {
const rd = self.buf.reader();
const count = leb.readULEB128(u32, rd) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
self.imports.count = count;
var i: usize = 0;
while (i < count) : (i += 1) {
const module_name_length = leb.readULEB128(u32, rd) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
const module_name_start = rd.context.pos;
rd.skipBytes(module_name_length, .{}) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
const module_name = self.module[module_name_start .. module_name_start + module_name_length];
if (!unicode.utf8ValidateSlice(module_name)) return error.NameNotUTF8;
const name_length = leb.readULEB128(u32, rd) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
const name_start = rd.context.pos;
rd.skipBytes(name_length, .{}) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
const name = self.module[name_start .. name_start + name_length];
if (!unicode.utf8ValidateSlice(name)) return error.NameNotUTF8;
const tag = rd.readEnum(Tag, .Little) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
if (i > math.maxInt(u32)) return error.ExpectedU32Index;
const import_index = @truncate(u32, i);
_ = switch (tag) {
.Func => try self.decodeFunction(import_index),
.Table => try self.decodeTable(import_index),
.Mem => try self.decodeMemory(import_index),
.Global => try self.decodeGlobal(import_index),
};
try self.imports.list.append(Import{
.module = module_name,
.name = name,
.desc_tag = tag,
});
}
}
fn decodeFunctionSection(self: *Module) !void {
const rd = self.buf.reader();
const count = leb.readULEB128(u32, rd) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
self.functions.count = count;
var i: usize = 0;
while (i < count) : (i += 1) {
try self.decodeFunction(null);
}
}
fn decodeFunction(self: *Module, import: ?u32) !void {
const rd = self.buf.reader();
const type_index = leb.readULEB128(u32, rd) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
if (type_index >= self.types.list.items.len) return error.ValidatorInvalidTypeIndex;
if (import == null and self.function_index_start == null) {
self.function_index_start = self.functions.list.items.len;
}
try self.functions.list.append(common.Function{
.typeidx = type_index,
.import = import,
});
}
fn decodeTableSection(self: *Module) !void {
const rd = self.buf.reader();
const count = leb.readULEB128(u32, rd) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
self.tables.count = count;
var i: usize = 0;
while (i < count) : (i += 1) {
try self.decodeTable(null);
}
}
fn decodeTable(self: *Module, import: ?u32) !void {
if (self.tables.list.items.len > 0) return error.ValidatorMultipleTables;
const rd = self.buf.reader();
const tag = rd.readByte() catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
if (tag != 0x70) return error.ExpectedTable;
const limit_type = rd.readEnum(LimitType, .Little) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
switch (limit_type) {
.Min => {
const min = leb.readULEB128(u32, rd) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
try self.tables.list.append(Limit{
.min = min,
.max = null,
.import = import,
});
},
.MinMax => {
const min = leb.readULEB128(u32, rd) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
const max = leb.readULEB128(u32, rd) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
if (min > max) return error.ValidatorTableMinGreaterThanMax;
try self.tables.list.append(Limit{
.min = min,
.max = max,
.import = import,
});
},
}
}
fn decodeMemorySection(self: *Module) !void {
const rd = self.buf.reader();
const count = leb.readULEB128(u32, rd) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
self.memories.count = count;
var i: usize = 0;
while (i < count) : (i += 1) {
try self.decodeMemory(null);
}
}
fn decodeMemory(self: *Module, import: ?u32) !void {
if (self.memories.list.items.len > 0) return error.ValidatorMultipleMemories;
const rd = self.buf.reader();
const limit_type = rd.readEnum(LimitType, .Little) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
switch (limit_type) {
.Min => {
const min = leb.readULEB128(u32, rd) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
if (min > 65536) return error.ValidatorMemoryMinTooLarge;
try self.memories.list.append(Limit{
.min = min,
.max = null,
.import = import,
});
},
.MinMax => {
const min = leb.readULEB128(u32, rd) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
const max = leb.readULEB128(u32, rd) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
if (min > max) return error.ValidatorMemoryMinGreaterThanMax;
if (min > 65536) return error.ValidatorMemoryMinTooLarge;
if (max > 65536) return error.ValidatorMemoryMaxTooLarge;
try self.memories.list.append(Limit{
.min = min,
.max = max,
.import = import,
});
},
}
}
fn decodeGlobalSection(self: *Module) !void {
const rd = self.buf.reader();
const count = leb.readULEB128(u32, rd) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
self.globals.count = count;
var i: usize = 0;
while (i < count) : (i += 1) {
try self.decodeGlobal(null);
}
}
fn decodeGlobal(self: *Module, import: ?u32) !void {
const rd = self.buf.reader();
const global_type = rd.readEnum(ValueType, .Little) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
const mutability = rd.readEnum(Mutability, .Little) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
const offset = rd.context.pos;
var code: ?[]const u8 = null;
var parsed_code: ?StartWithDepth = null;
// If we're not importing the global we will expect
// an expression
if (import == null) {
// TODO: this isn't right because I think we might have more than one end
var j: usize = 0;
while (true) : (j += 1) {
const byte = rd.readByte() catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
if (byte == @enumToInt(Opcode.end)) break;
}
code = self.module[offset .. offset + j + 1];
parsed_code = try self.parseConstantCode(code orelse return error.NoCode, global_type);
}
if (code == null and import == null) return error.ExpectedOneOrTheOther;
if (code != null and import != null) return error.ExpectedOneOrTheOther;
try self.globals.list.append(Global{
.value_type = global_type,
.mutability = mutability,
.start = if (parsed_code) |pc| pc.start else null,
.import = import,
});
}
fn decodeExportSection(self: *Module) !void {
const rd = self.buf.reader();
const count = leb.readULEB128(u32, rd) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
self.exports.count = count;
var i: usize = 0;
while (i < count) : (i += 1) {
const name_length = leb.readULEB128(u32, rd) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
const name_start = rd.context.pos;
rd.skipBytes(name_length, .{}) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
const name = self.module[name_start .. name_start + name_length];
if (!unicode.utf8ValidateSlice(name)) return error.NameNotUTF8;
for (self.exports.list.items) |exprt| {
if (mem.eql(u8, name, exprt.name)) return error.ValidatorDuplicateExportName;
}
const tag = rd.readEnum(Tag, .Little) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
const index = leb.readULEB128(u32, rd) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
switch (tag) {
.Func => if (index >= self.functions.list.items.len) return error.ValidatorExportUnknownFunction,
.Table => if (index >= self.tables.list.items.len) return error.ValidatorExportUnknownTable,
.Mem => if (index >= self.memories.list.items.len) return error.ValidatorExportUnknownMemory,
.Global => if (index >= self.globals.list.items.len) return error.ValidatorExportUnknownGlobal,
}
try self.exports.list.append(Export{
.name = name,
.tag = tag,
.index = index,
});
}
}
fn decodeStartSection(self: *Module) !void {
if (self.start != null) return error.MultipleStartSections;
const rd = self.buf.reader();
const index = leb.readULEB128(u32, rd) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
if (index >= self.functions.list.items.len) return error.ValidatorStartFunctionUnknown;
const func = self.functions.list.items[index];
const function_type = self.types.list.items[func.typeidx];
if (function_type.params.len != 0 or function_type.results.len != 0) return error.ValidatorNotStartFunctionType;
self.start = index;
}
fn decodeElementSection(self: *Module) !void {
const rd = self.buf.reader();
const count = leb.readULEB128(u32, rd) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
self.elements.count = count;
var i: usize = 0;
while (i < count) : (i += 1) {
const table_index = leb.readULEB128(u32, rd) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
if (table_index >= self.tables.list.items.len) return error.ValidatorElemUnknownTable;
const expr_start = rd.context.pos;
const expr = self.module[expr_start..];
const meta = try opcode.findExprEnd(expr);
rd.skipBytes(meta.offset + 1, .{}) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
// Number of u32's in our data (not the length in bytes!)
const data_length = leb.readULEB128(u32, rd) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
const data_start = rd.context.pos;
var j: usize = 0;
while (j < data_length) : (j += 1) {
// When we pre-process all this data we can just store this
// but for the moment we're just using it to skip over
const func_index = leb.readULEB128(u32, rd) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
if (func_index >= self.functions.list.items.len) return error.ValidatorElemUnknownFunctionIndex;
}
const parsed_code = try self.parseConstantCode(self.module[expr_start .. expr_start + meta.offset + 1], .I32);
try self.elements.list.append(Segment{
.index = table_index,
.start = parsed_code.start,
.count = data_length,
.data = self.module[data_start..rd.context.pos],
});
}
}
fn decodeCodeSection(self: *Module) !void {
const rd = self.buf.reader();
const count = leb.readULEB128(u32, rd) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
self.codes.count = count;
const function_index_start = self.function_index_start orelse return error.FunctionCodeSectionsInconsistent;
var i: usize = 0;
while (i < count) : (i += 1) {
const size = leb.readULEB128(u32, rd) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
}; // includes bytes defining locals
const offset = rd.context.pos;
const locals_definitions_count = leb.readULEB128(u32, rd) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
const locals_start = self.local_types.items.len;
// Iterate over local definitions counting them
var j: usize = 0;
var locals_count: usize = 0;
while (j < locals_definitions_count) : (j += 1) {
const type_count = leb.readULEB128(u32, rd) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
const local_type = rd.readEnum(ValueType, .Little) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
locals_count += type_count;
try self.local_types.append(.{ .count = type_count, .value_type = local_type });
}
if (locals_count > 0x100000000) return error.TooManyLocals;
const code_start = rd.context.pos;
const code_length = try math.sub(usize, size, code_start - offset);
rd.skipBytes(code_length, .{}) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
const locals = self.local_types.items[locals_start .. locals_start + locals_definitions_count];
const code = self.module[code_start..rd.context.pos];
if (function_index_start + i >= self.functions.list.items.len) return error.FunctionCodeSectionsInconsistent;
const parsed_code = try self.parseFunction(locals, code, function_index_start + i);
try self.codes.list.append(Code{
.locals_count = locals_count,
.start = parsed_code.start,
.required_stack_space = parsed_code.max_depth,
});
}
}
fn decodeDataSection(self: *Module) !void {
const rd = self.buf.reader();
const count = leb.readULEB128(u32, rd) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
self.datas.count = count;
var i: usize = 0;
while (i < count) : (i += 1) {
const mem_idx = leb.readULEB128(u32, rd) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
if (mem_idx >= self.memories.list.items.len) return error.ValidatorDataMemoryReferenceInvalid;
const expr_start = rd.context.pos;
const expr = self.module[expr_start..];
const meta = try opcode.findExprEnd(expr);
rd.skipBytes(meta.offset + 1, .{}) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
const data_length = leb.readULEB128(u32, rd) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
const data_start = rd.context.pos;
rd.skipBytes(data_length, .{}) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
const parsed_code = try self.parseConstantCode(self.module[expr_start .. expr_start + meta.offset + 1], .I32);
try self.datas.list.append(Segment{
.index = mem_idx,
.start = parsed_code.start,
.count = data_length,
.data = self.module[data_start..rd.context.pos],
});
}
}
fn decodeCustomSection(self: *Module, size: u32) !void {
const rd = self.buf.reader();
const offset = rd.context.pos;
const name_length = leb.readULEB128(u32, rd) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
const name_start = rd.context.pos;
rd.skipBytes(name_length, .{}) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
const name = self.module[name_start .. name_start + name_length];
if (!unicode.utf8ValidateSlice(name)) return error.NameNotUTF8;
const data_start = rd.context.pos;
const data_size = try math.sub(usize, size, (rd.context.pos - offset));
rd.skipBytes(data_size, .{}) catch |err| switch (err) {
error.EndOfStream => return error.UnexpectedEndOfInput,
else => return err,
};
const data = self.module[data_start .. data_start + data_size];
try self.customs.list.append(Custom{
.name = name,
.data = data,
});
}
const StartWithDepth = struct {
start: usize,
max_depth: usize,
};
pub fn parseConstantCode(self: *Module, code: []const u8, value_type: ValueType) !StartWithDepth {
_ = try opcode.findFunctionEnd(code);
var continuation_stack: [1024]usize = [_]usize{0} ** 1024;
const code_start = self.parsed_code.items.len;
var it = ParseIterator.init(self, code, &self.parsed_code, continuation_stack[0..]);
const in: [0]ValueType = [_]ValueType{} ** 0;
var out: [1]ValueType = [_]ValueType{.I32} ** 1;
out[0] = value_type;
try it.validator.pushControlFrame(
.block,
in[0..0],
out[0..1],
);
while (try it.next()) |instr| {
switch (instr) {
.@"i32.const" => |_| {},
.@"i64.const" => |_| {},
.@"f32.const" => |_| {},
.@"f64.const" => |_| {},
.@"global.get" => |_| {},
.end => |_| {},
else => return error.ValidatorConstantExpressionRequired,
}
try self.parsed_code.append(instr);
}
var parsed_code = self.parsed_code.items[code_start..self.parsed_code.items.len];
// Patch last end so that it is return
self.parsed_code.items[self.parsed_code.items.len - 1] = .@"return";
return StartWithDepth{ .start = code_start, .max_depth = it.validator.max_depth };
}
pub fn parseFunction(self: *Module, locals: []LocalType, code: []const u8, func_index: usize) !StartWithDepth {
_ = try opcode.findFunctionEnd(code);
var continuation_stack: [1024]usize = [_]usize{0} ** 1024;
const code_start = self.parsed_code.items.len;
var it = ParseIterator.init(self, code, &self.parsed_code, continuation_stack[0..]);
try it.pushFunction(locals, func_index);
while (try it.next()) |instr| {
try self.parsed_code.append(instr);
}
var parsed_code = self.parsed_code.items[code_start..self.parsed_code.items.len];
// Patch last end so that it is return
self.parsed_code.items[self.parsed_code.items.len - 1] = .@"return";
return StartWithDepth{ .start = code_start, .max_depth = it.validator.max_depth };
}
pub fn getExport(self: *Module, tag: Tag, name: []const u8) !usize {
for (self.exports.list.items) |exported| {
if (tag == exported.tag and mem.eql(u8, name, exported.name)) return exported.index;
}
return error.ExportNotFound;
}
pub fn signaturesEqual(params: []const ValueType, results: []const ValueType, b: FuncType) bool {
if (params.len != b.params.len) return false;
if (results.len != b.results.len) return false;
for (params) |p_a, i| {
if (p_a != b.params[i]) return false;
}
for (results) |r_a, i| {
if (r_a != b.results[i]) return false;
}
return true;
}
pub fn print(module: *Module) void {
std.debug.warn(" Types: {}\n", .{module.types.list.items.len});
std.debug.warn("Functions: {}\n", .{module.functions.list.items.len});
std.debug.warn(" Tables: {}\n", .{module.tables.list.items.len});
std.debug.warn(" Memories: {}\n", .{module.memories.list.items.len});
std.debug.warn(" Globals: {}\n", .{module.globals.list.items.len});
std.debug.warn(" Exports: {}\n", .{module.exports.list.items.len});
std.debug.warn(" Imports: {}\n", .{module.imports.list.items.len});
std.debug.warn(" Codes: {}\n", .{module.codes.list.items.len});
std.debug.warn(" Datas: {}\n", .{module.datas.list.items.len});
std.debug.warn(" Customs: {}\n", .{module.customs.list.items.len});
}
};
fn Section(comptime T: type) type {
return struct {
count: usize = 0,
list: ArrayList(T),
const Self = @This();
pub fn init(alloc: *mem.Allocator) Self {
return Self{
.list = ArrayList(T).init(alloc),
};
}
pub fn itemsSlice(self: *Self) []T {
return self.list.items;
}
};
}
const Custom = struct {
name: []const u8,
data: []const u8,
};
const SectionType = enum(u8) {
Custom = 0x00,
Type = 0x01,
Import = 0x02,
Function = 0x03,
Table = 0x04,
Memory = 0x05,
Global = 0x06,
Export = 0x07,
Start = 0x08,
Element = 0x09,
Code = 0x0a,
Data = 0x0b,
};
const testing = std.testing;
test "module loading (simple add function)" {
const ArenaAllocator = std.heap.ArenaAllocator;
var arena = ArenaAllocator.init(testing.allocator);
defer _ = arena.deinit();
const bytes = @embedFile("../test/test.wasm");
var store: Store = Store.init(&arena.allocator);
var module = Module.init(&arena.allocator, bytes);
try module.decode();
var new_inst = Instance.init(&arena.allocator, &store, module);
const index = try store.addInstance(new_inst);
var inst = try store.instance(index);
try inst.instantiate(index);
var in = [2]u64{ 22, 23 };
var out = [1]u64{0};
try inst.invoke("add", in[0..], out[0..], .{});
try testing.expectEqual(@as(i32, 45), @bitCast(i32, @truncate(u32, out[0])));
}
test "module loading (fib)" {
const ArenaAllocator = std.heap.ArenaAllocator;
var arena = ArenaAllocator.init(testing.allocator);
defer _ = arena.deinit();
const bytes = @embedFile("../test/fib.wasm");
var store: Store = Store.init(&arena.allocator);
var module = Module.init(&arena.allocator, bytes);
try module.decode();
var new_inst = Instance.init(&arena.allocator, &store, module);
const index = try store.addInstance(new_inst);
var inst = try store.instance(index);
try inst.instantiate(index);
var in = [1]u64{0};
var out = [1]u64{0};
try inst.invoke("fib", in[0..], out[0..], .{});
try testing.expectEqual(@as(i32, 0), @bitCast(i32, @truncate(u32, out[0])));
in[0] = 1;
try inst.invoke("fib", in[0..], out[0..], .{});
try testing.expectEqual(@as(i32, 1), @bitCast(i32, @truncate(u32, out[0])));
in[0] = 2;
try inst.invoke("fib", in[0..], out[0..], .{});
try testing.expectEqual(@as(i32, 1), @bitCast(i32, @truncate(u32, out[0])));
in[0] = 3;
try inst.invoke("fib", in[0..], out[0..], .{});
try testing.expectEqual(@as(i32, 2), @bitCast(i32, @truncate(u32, out[0])));
in[0] = 4;
try inst.invoke("fib", in[0..], out[0..], .{});
try testing.expectEqual(@as(i32, 3), @bitCast(i32, @truncate(u32, out[0])));
in[0] = 5;
try inst.invoke("fib", in[0..], out[0..], .{});
try testing.expectEqual(@as(i32, 5), @bitCast(i32, @truncate(u32, out[0])));
in[0] = 6;
try inst.invoke("fib", in[0..], out[0..], .{});
try testing.expectEqual(@as(i32, 8), @bitCast(i32, @truncate(u32, out[0])));
}
test "module loading (fact)" {
const ArenaAllocator = std.heap.ArenaAllocator;
var arena = ArenaAllocator.init(testing.allocator);
defer _ = arena.deinit();
const bytes = @embedFile("../test/fact.wasm");
var store: Store = Store.init(&arena.allocator);
var module = Module.init(&arena.allocator, bytes);
try module.decode();
var new_inst = Instance.init(&arena.allocator, &store, module);
const index = try store.addInstance(new_inst);
var inst = try store.instance(index);
try inst.instantiate(index);
var in = [1]u64{1};
var out = [1]u64{0};
try inst.invoke("fact", in[0..], out[0..], .{});
try testing.expectEqual(@as(i32, 1), @bitCast(i32, @truncate(u32, out[0])));
in[0] = 2;
try inst.invoke("fact", in[0..], out[0..], .{});
try testing.expectEqual(@as(i32, 2), @bitCast(i32, @truncate(u32, out[0])));
in[0] = 3;
try inst.invoke("fact", in[0..], out[0..], .{});
try testing.expectEqual(@as(i32, 6), @bitCast(i32, @truncate(u32, out[0])));
in[0] = 4;
try inst.invoke("fact", in[0..], out[0..], .{});
try testing.expectEqual(@as(i32, 24), @bitCast(i32, @truncate(u32, out[0])));
in[0] = 12;
try inst.invoke("fact", in[0..], out[0..], .{});
try testing.expectEqual(@as(i32, 479001600), @bitCast(i32, @truncate(u32, out[0])));
} | src/module.zig |
const std = @import("std");
const ds = @import("ds/ds.zig");
const stdx = @import("stdx");
const t = stdx.testing;
const log = stdx.log.scoped(.mem);
/// Dupe with new target alignment.
pub fn dupeAlign(alloc: std.mem.Allocator, comptime T: type, comptime A: u8, src: []const T) ![] align (A) T {
var aligned = try alloc.alignedAlloc(T, A, src.len);
std.mem.copy(T, aligned, src);
return aligned;
}
pub fn ptrCastTo(ptr_to_ptr: anytype, from: anytype) void {
const Ptr = std.meta.Child(@TypeOf(ptr_to_ptr));
ptr_to_ptr.* = @ptrCast(Ptr, from);
}
/// @alignCast seems to be broken (does not insert runtime checks) when passed a comptime int from an expression like @typeInfo(Ptr).Pointer.alignment (for cases where Ptr has a custom alignment, eg. *align(1) u32).
/// Current fix is to branch to common alignments.
pub fn ptrCastAlign(comptime Ptr: type, ptr: anytype) Ptr {
const alignment = @typeInfo(Ptr).Pointer.alignment;
switch (alignment) {
0 => return @ptrCast(Ptr, ptr),
1 => return @ptrCast(Ptr, @alignCast(1, ptr)),
2 => return @ptrCast(Ptr, @alignCast(2, ptr)),
4 => return @ptrCast(Ptr, @alignCast(4, ptr)),
8 => return @ptrCast(Ptr, @alignCast(8, ptr)),
else => unreachable,
}
}
// Same as std.mem.replace except we write to an ArrayList.
pub fn replaceIntoList(comptime T: type, input: []const T, needle: []const T, replacement: []const T, output: *std.ArrayList(T)) usize {
// Clear the array list.
output.clearRetainingCapacity();
var i: usize = 0;
var slide: usize = 0;
var replacements: usize = 0;
while (slide < input.len) {
if (std.mem.indexOf(T, input[slide..], needle) == @as(usize, 0)) {
output.appendSlice(replacement) catch unreachable;
i += replacement.len;
slide += needle.len;
replacements += 1;
} else {
output.append(input[slide]) catch unreachable;
i += 1;
slide += 1;
}
}
return replacements;
}
// Copy to dest, truncates if overflows buffer.
pub fn copyTrunc(src: []const u8, dst: []u8) void {
const len = std.math.min(dst.len, src.len);
std.mem.copy(dst[0..len], src[0..len]);
}
pub fn readFloat32Little(ptr: *[4]u8) f32 {
return @bitCast(f32, std.mem.readIntLittle(u32, ptr));
}
pub fn freeOpaqueWithSize(alloc: std.mem.Allocator, ptr: *ds.Opaque, size: usize) void {
alloc.free(@ptrCast([*]u8, ptr)[0..size]);
}
pub fn indexOfNth(comptime T: type, haystack: []const T, needle: []const T, n: u32) ?usize {
var pos: usize = 0;
var i: u32 = 0;
while (i <= n) : (i += 1) {
pos = if (std.mem.indexOfPos(T, haystack, pos, needle)) |new_pos| new_pos + 1 else return null;
}
return pos - 1;
}
test "indexOfNth" {
const s = "\nfoo\nfoo\n";
try t.eq(indexOfNth(u8, s, "\n", 0), 0);
try t.eq(indexOfNth(u8, s, "\n", 1), 4);
try t.eq(indexOfNth(u8, s, "\n", 2), 8);
try t.eq(indexOfNth(u8, s, "\n", 3), null);
}
pub fn lastIndexOfNth(comptime T: type, haystack: []const T, needle: []const T, n: u32) ?usize {
var pos: usize = haystack.len - needle.len;
var i: u32 = 0;
while (i <= n) : (i += 1) {
if (lastIndexOfPos(T, haystack, pos, needle)) |new_pos| pos = new_pos +% @bitCast(usize, @intCast(i64, -1)) else return null;
}
return pos +% 1;
}
test "lastIndexOfNth" {
const s = "\nfoo\nfoo\n";
try t.eq(lastIndexOfNth(u8, s, "\n", 0), 8);
try t.eq(lastIndexOfNth(u8, s, "\n", 1), 4);
try t.eq(lastIndexOfNth(u8, s, "\n", 2), 0);
try t.eq(lastIndexOfNth(u8, s, "\n", 3), null);
}
pub fn lastIndexOfPos(comptime T: type, haystack: []const T, start: usize, needle: []const T) ?usize {
var i: usize = start;
if (start > haystack.len - needle.len) {
return null;
}
while (i > 0) : (i -= 1) {
if (std.mem.eql(T, haystack[i .. i + needle.len], needle)) return i;
}
if (std.mem.eql(T, haystack[0..needle.len], needle)) return i else return null;
}
pub fn removeConst(comptime T: type, val: *const T) *T {
return @intToPtr(*T, @ptrToInt(val));
} | stdx/mem.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/day07.txt");
const CrabList = Map(usize, usize);
fn fuelAt(crabs: CrabList, pos: usize) usize {
var fuel: usize = 0;
var iter = crabs.iterator();
while (iter.next()) |kv| {
const c_pos = kv.key_ptr.*;
const c_count = kv.value_ptr.*;
var distance = if (pos > c_pos) (pos - c_pos) else (c_pos - pos);
fuel += c_count * distance * (distance + 1) / 2;
}
return fuel;
}
fn fuelAt_pt1(crabs: CrabList, pos: usize) usize {
var fuel: usize = 0;
var iter = crabs.iterator();
while (iter.next()) |kv| {
const c_pos = kv.key_ptr.*;
const c_count = kv.value_ptr.*;
fuel += c_count * (if (pos > c_pos) (pos - c_pos) else (c_pos - pos));
}
return fuel;
}
pub fn main() !void {
var crabs = CrabList.init(gpa);
var numtext = tokenize(u8, data, ",\n");
var max_pos: usize = 0;
while (numtext.next()) |pos_str| {
var pos = try parseInt(usize, pos_str, 10);
var cur = crabs.get(pos) orelse 0;
cur += 1;
try crabs.put(pos, cur);
if (pos > max_pos) max_pos = pos;
}
var min_fuel: usize = fuelAt(crabs, 0);
while (max_pos >= 1) : (max_pos -= 1) {
var fuel = fuelAt(crabs, max_pos);
if (fuel < min_fuel) {
print("{d} takes {d}\n", .{ max_pos, fuelAt(crabs, max_pos) });
min_fuel = fuel;
}
}
}
// 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/day07.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(.{}){};
pub fn flipInstruction(inst: *Instruction) void {
switch (inst.typ) {
InstType.JMP => {
inst.typ = InstType.NOP;
},
InstType.NOP => {
inst.typ = InstType.JMP;
},
else => unreachable,
}
}
const InstType = enum {
ACC, JMP, NOP
};
const Instruction = struct {
typ: InstType,
val: isize,
visited: bool = false,
pub fn initFromLine(line: []const u8) Instruction {
var tokens = std.mem.tokenize(line, " ");
const typ_str = tokens.next() orelse unreachable;
const val_str = tokens.next() orelse unreachable;
var typ: InstType = switch (typ_str[0]) {
'a' => InstType.ACC,
'j' => InstType.JMP,
'n' => InstType.NOP,
else => unreachable,
};
return Instruction{
.typ = typ,
.val = fmt.parseInt(isize, val_str, 10) catch unreachable,
};
}
};
const Program = struct {
allo: *std.mem.Allocator = undefined,
mem: []Instruction = undefined,
ptr: isize = 0,
cnt: isize = 0,
pub fn init(allo: *std.mem.Allocator) Program {
return Program{
.allo = allo,
.mem = allo.alloc(Instruction, 0) catch unreachable,
};
}
pub fn deinit(self: Program) void {
self.allo.free(self.mem);
}
pub fn appendInstruction(self: *Program, inst: Instruction) void {
const cur_len = self.mem.len;
self.mem = self.allo.realloc(self.mem, cur_len + 1) catch unreachable;
self.mem[cur_len] = inst;
}
pub fn run(self: *Program) !void {
self.reset();
while (true) {
const ptr = @intCast(usize, self.ptr);
if (ptr >= self.mem.len) {
// p2 case
return error.END;
}
var inst = self.mem[ptr];
if (inst.visited) {
// p1 case
return error.VISITED;
}
self.mem[ptr].visited = true;
switch (inst.typ) {
InstType.ACC => {
self.cnt += inst.val;
self.ptr += 1;
},
InstType.NOP => {
self.ptr += 1;
},
InstType.JMP => {
self.ptr += inst.val;
},
}
}
}
fn reset(self: *Program) void {
self.ptr = 0;
self.cnt = 0;
for (self.mem) |*inst| {
inst.visited = 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);
// business logic
//
var program = Program.init(allo);
defer program.deinit();
while (lines.next()) |line| {
const inst = Instruction.initFromLine(line);
program.appendInstruction(inst);
}
// do p1
//
program.run() catch |e| {
print("p1 [{}]: {}\n", .{ e, program.cnt });
};
// do p2
//
var candidate = allo.alloc(usize, program.mem.len) catch unreachable;
defer allo.free(candidate);
var cnt: usize = 0;
for (program.mem) |*inst, i| {
// we only want to flip visited instructions
if (!inst.visited) {
continue;
}
// skip if flipping instr would move us to visited instruction
switch (inst.typ) {
InstType.ACC => {
continue;
},
InstType.NOP => {
const offset = @intCast(usize, @intCast(isize, i) + inst.val);
const jump_candidate = program.mem[offset];
if (jump_candidate.visited) {
continue;
}
},
InstType.JMP => {
const step_candidate = program.mem[i + 1];
if (step_candidate.visited) {
continue;
}
},
}
candidate[cnt] = i;
cnt += 1;
}
for (candidate[0..cnt]) |w| {
// flip a good candidate and see where we end up
var inst = &program.mem[w];
flipInstruction(inst);
program.run() catch |e| {
if (e != error.VISITED) {
print("p2 [{}]: {}\n", .{ e, program.cnt });
break;
}
};
flipInstruction(inst);
}
const delta = @divTrunc(std.time.nanoTimestamp(), 1000) - begin;
print("all done in {} microseconds\n", .{delta});
} | day_08/src/main.zig |
const std = @import("std");
const data = @embedFile("input.txt");
const STEPS = 40;
const BYTE_MASK: u16 = std.math.maxInt(u8);
fn convertPair(k_str: []const u8) u16 {
return k_str[0] | (@intCast(u16, k_str[1]) << 8);
}
fn combinePair(k1: u16, k2: u16) u16 {
return (k1 & BYTE_MASK) | ((k2 & BYTE_MASK) << 8);
}
fn increment(comptime K: type, comptime V: type, map: *std.AutoHashMap(K, V), key: K, value: V) !void {
if (!map.contains(key)) {
return map.put(key, value);
} else {
map.getPtr(key).?.* += value;
}
}
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
var alloc = &arena.allocator;
defer arena.deinit();
var rules = std.AutoHashMap(u16, u8).init(alloc);
var pairs = std.AutoHashMap(u16, usize).init(alloc);
var mutations = std.AutoHashMap(u16, usize).init(alloc);
var chars = std.AutoHashMap(u8, usize).init(alloc);
{
var line_iter = std.mem.split(data, "\n");
var tmpl_opt = line_iter.next();
if (tmpl_opt) |tmpl| {
var i: usize = 0;
while(i < (tmpl.len - 1)) : (i += 1) {
var kpair = convertPair(tmpl[i..i+2]);
try increment(u16, usize, &pairs, kpair, 1);
try increment(u8, usize, &chars, tmpl[i], 1);
}
try increment(u8, usize, &chars, tmpl[tmpl.len - 1], 1);
}
_ = line_iter.next();
while(line_iter.next()) |line| {
var iter = std.mem.split(line, " -> ");
if (iter.next()) |k_str| {
if (k_str.len > 0) {
var kpair = convertPair(k_str);
var val = iter.next().?[0];
try rules.put(kpair, val);
try mutations.put(kpair, 0);
if (!pairs.contains(kpair))
try pairs.put(kpair, 0);
}
}
}
}
comptime var step: usize = 0;
inline while(step < STEPS) : (step += 1) {
// Evaluate all pairs "immutably"
var iter = pairs.iterator();
while(iter.next()) |it| {
const value = it.value_ptr.*;
if(value > 0) {
const char_val = rules.get(it.key_ptr.*).?;
try increment(u8, usize, &chars, char_val, value);
var kpair1 = combinePair(it.key_ptr.*, @intCast(u16, char_val));
var kpair2 = combinePair(@intCast(u16, char_val), (it.key_ptr.* >> 8));
mutations.getPtr(kpair1).?.* += value;
mutations.getPtr(kpair2).?.* += value;
it.value_ptr.* -= value;
}
}
// Apply mutations back to pairs
iter = mutations.iterator();
while(iter.next()) |mutation| {
pairs.getPtr(mutation.key_ptr.*).?.* += mutation.value_ptr.*;
mutation.value_ptr.* = 0;
}
}
// Get result numbers
var min: usize = std.math.maxInt(usize);
var max: usize = 0;
var len: usize = 0;
var char_iter = chars.iterator();
while(char_iter.next()) |it| {
if (it.value_ptr.* < min) min = it.value_ptr.*;
if (it.value_ptr.* > max) max = it.value_ptr.*;
len += it.value_ptr.*;
}
var diff = max - min;
std.debug.print("Polymer length: {d}\n", .{len});
std.debug.print("Result: {d}\n", .{diff});
} | day14/main.zig |
const std = @import("std");
const mem = std.mem;
const fs = std.fs;
const fileExists = @import("util.zig").fileExists;
const OS = struct {
name: []const u8,
id: []const u8,
};
pub fn osname(allocator: *mem.Allocator) !OS {
var file: fs.File = undefined;
var os_id_prefix: []const u8 = undefined;
var os_name_prefix: []const u8 = undefined;
var os_name: []const u8 = "generic";
var os_id: []const u8 = "generic";
if (fileExists("/etc/lsb-release")) {
file = try fs.openFileAbsolute(
"/etc/lsb-release",
.{ .read = true },
);
os_id_prefix =
\\DISTRIB_ID=
;
os_name_prefix =
\\DISTRIB_DESCRIPTION="
;
} else if (fileExists("/etc/os-release")) {
file = try fs.openFileAbsolute(
"/etc/os-release",
.{ .read = true },
);
os_id_prefix =
\\ID=
;
os_name_prefix =
\\PRETTY_NAME="
;
}
const file_read = try file.readToEndAlloc(allocator, 0x200);
file.close();
defer allocator.free(file_read);
var lines = mem.tokenize(u8, file_read, "\n");
while (true) {
var line = lines.next() orelse break;
if (mem.startsWith(u8, line, os_name_prefix)) {
os_name = line[os_name_prefix.len .. line.len - 1];
}
if (mem.startsWith(u8, line, os_id_prefix)) {
os_id = line[os_id_prefix.len..];
}
}
// return &[2][]const u8{ os_name, os_id };
const res1 = try allocator.dupe(u8, os_name);
const res2 = try allocator.dupe(u8, os_id);
errdefer allocator.free(res1);
errdefer allocator.free(res2);
return OS{ .name = res1, .id = res2 };
}
pub fn kernel(allocator: *mem.Allocator) ![]const u8 {
var file: fs.File = undefined;
if (fileExists("/proc/version")) {
file = try fs.openFileAbsolute("/proc/version", .{ .read = true });
}
const file_read = try file.readToEndAlloc(allocator, 0x100);
file.close();
defer allocator.free(file_read);
var info = mem.tokenize(u8, file_read, " ");
var kernel_ver: []const u8 = undefined;
while (true) {
var word = info.next() orelse break;
if (mem.eql(u8, word, "version")) {
kernel_ver = info.next().?;
break;
}
}
const res = try allocator.dupe(u8, kernel_ver);
errdefer allocator.free(res);
return res;
}
pub fn uptime(allocator: *mem.Allocator) ![]const u8 {
var file: fs.File = undefined;
var file_read: []const u8 = undefined;
var uptime_nanos: u64 = undefined;
if (fileExists("/proc/uptime")) {
file = try fs.openFileAbsolute("/proc/uptime", .{ .read = true });
file_read = try file.readToEndAlloc(allocator, 0x40);
var uptime_data = mem.tokenize(u8, file_read, ".");
const real_uptime = uptime_data.next().?;
uptime_nanos =
(try std.fmt.parseUnsigned(u64, real_uptime, 10)) * 1_000_000_000;
} else if (fileExists("/proc/stat")) {
const epoch = @intCast(u64, @divTrunc(std.time.milliTimestamp(), 1000));
var btime: []const u8 = undefined;
file = try fs.openFileAbsolute("/proc/stat", .{ .read = true });
file_read = try file.readToEndAlloc(allocator, 0x1000);
var uptime_data = mem.tokenize(u8, file_read, "\n");
const prefix = "btime ";
while (true) {
var line = uptime_data.next() orelse break;
if (mem.startsWith(u8, line, prefix)) {
btime = line[prefix.len..];
uptime_nanos =
(epoch - (try std.fmt.parseUnsigned(u64, btime, 10))) * 1_000_000_000;
break;
}
}
}
file.close();
defer allocator.free(file_read);
const formatted = try std.fmt.allocPrint(
allocator,
"{}",
.{std.fmt.fmtDuration(uptime_nanos)},
);
defer allocator.free(formatted);
const res = try allocator.dupe(u8, formatted);
errdefer allocator.free(res);
return res;
} | src/layers.zig |
const rom = @import("../rom.zig");
const script = @import("../script.zig");
const std = @import("std");
const mem = std.mem;
const li32 = rom.int.li32;
const lu16 = rom.int.lu16;
const lu32 = rom.int.lu32;
pub fn getScriptOffsets(data: []const u8) []const li32 {
var len: usize = 0;
while (true) : (len += 1) {
const rest = data[len * 4 ..];
if (rest.len < 4 or (rest[0] == 0x13 and rest[1] == 0xfd))
break;
}
return mem.bytesAsSlice(li32, data[0 .. len * 4]);
}
pub const CommandDecoder = script.CommandDecoder(Command, struct {
fn isEnd(cmd: Command) bool {
switch (cmd.tag) {
.end,
.@"return",
.return2,
.jump,
=> return true,
else => return false,
}
}
}.isEnd);
// These commands are only valid in dia/pearl/plat
pub const Command = packed struct {
tag: Kind,
_data: Data,
/// HACK: Zig crashes when trying to access `_data` during code generation. This
/// seem to happen because &cmd.data gives a bit aligned pointer, which then
/// does not get properly handled in codegen. This function works around this
/// by manually skipping the tag field to get the data field.
pub fn data(cmd: *Command) *Data {
const bytes = mem.asBytes(cmd);
return mem.bytesAsValue(Data, bytes[@sizeOf(Kind)..][0..@sizeOf(Data)]);
}
const Data = packed union {
nop0: void,
nop1: void,
end: void,
return2: Return2,
cmd_a: Cmd_a,
@"if": If,
if2: If2,
call_standard: CallStandard,
exit_standard: void,
jump: Jump,
call: Call,
@"return": void,
compare_last_result_jump: CompareLastResultJump,
compare_last_result_call: CompareLastResultCall,
set_flag: SetFlag,
clear_flag: ClearFlag,
check_flag: CheckFlag,
cmd_21: Cmd_21,
cmd_22: Cmd_22,
set_trainer_id: SetTrainerId,
cmd_24: Cmd_24,
clear_trainer_id: ClearTrainerId,
script_cmd__add_value: ScriptCmd_AddValue,
script_cmd__sub_value: ScriptCmd_SubValue,
set_var: SetVar,
copy_var: CopyVar,
message2: Message2,
message: Message,
message3: Message3,
message4: Message4,
message5: Message5,
cmd_30: void,
wait_button: void,
cmd_32: void,
cmd_33: void,
close_msg_on_key_press: void,
freeze_message_box: void,
call_message_box: CallMessageBox,
color_msg_box: ColorMsgBox,
type_message_box: TypeMessageBox,
no_map_message_box: void,
call_text_msg_box: void,
store_menu_status: StoreMenuStatus,
show_menu: void,
yes_no_box: YesNoBox,
multi: Multi,
multi2: Multi2,
cmd_42: Cmd_42,
close_multi: void,
multi3: Multi3,
multi4: Multi4,
txt_msg_scrp_multi: TxtMsgScrpMulti,
close_multi4: void,
play_fanfare: PlayFanfare,
multi_row: MultiRow,
play_fanfare2: PlayFanfare2,
wait_fanfare: WaitFanfare,
play_cry: PlayCry,
wait_cry: void,
soundfr: Soundfr,
cmd_4f: void,
play_sound: PlaySound,
stop: Stop,
restart: void,
cmd_53: Cmd_53,
switch_music: SwitchMusic,
store_saying_learned: StoreSayingLearned,
play_sound2: PlaySound2,
cmd_58: Cmd_58,
check_saying_learned: CheckSayingLearned,
swith_music2: SwithMusic2,
act_microphone: void,
deact_microphone: void,
cmd_5d: void,
apply_movement: ApplyMovement,
wait_movement: void,
lock_all: void,
release_all: void,
lock: Lock,
release: Release,
add_people: AddPeople,
remove_people: RemovePeople,
lock_cam: LockCam,
zoom_cam: void,
face_player: void,
check_sprite_position: CheckSpritePosition,
check_person_position: CheckPersonPosition,
continue_follow: ContinueFollow,
follow_hero: FollowHero,
take_money: TakeMoney,
check_money: CheckMoney,
show_money: ShowMoney,
hide_money: void,
update_money: void,
show_coins: ShowCoins,
hide_coins: void,
update_coins: void,
check_coins: CheckCoins,
give_coins: GiveCoins,
take_coins: TakeCoins,
take_item: TakeItem,
give_item: GiveItem,
check_store_item: CheckStoreItem,
check_item: CheckItem,
store_item_taken: StoreItemTaken,
store_item_type: StoreItemType,
send_item_type1: SendItemType1,
cmd_84: Cmd_84,
check_underground_pc_status: CheckUndergroundPcStatus,
cmd_86: Cmd_86,
send_item_type2: SendItemType2,
cmd_88: Cmd_88,
cmd_89: Cmd_89,
cmd_8a: Cmd_8a,
cmd_8b: Cmd_8b,
cmd_8c: Cmd_8c,
cmd_8d: Cmd_8d,
cmd_8e: Cmd_8e,
send_item_type3: SendItemType3,
check_pokemon_party: CheckPokemonParty,
store_pokemon_party: StorePokemonParty,
set_pokemon_party_stored: SetPokemonPartyStored,
give_pokemon: GivePokemon,
give_egg: GiveEgg,
check_move: CheckMove,
check_place_stored: CheckPlaceStored,
cmd_9b: Cmd_9b,
cmd_9c: void,
cmd_9d: void,
cmd_9e: void,
cmd_9f: void,
cmd_a0: void,
call_end: void,
cmd__a2: void,
wfc_: void,
cmd_a4: Cmd_a4,
interview: void,
dress_pokemon: DressPokemon,
display_dressed_pokemon: DisplayDressedPokemon,
display_contest_pokemon: DisplayContestPokemon,
open_ball_capsule: void,
open_sinnoh_maps: void,
open_pc_function: OpenPcFunction,
draw_union: void,
trainer_case_union: void,
trade_union: void,
record_mixing_union: void,
end_game: void,
hall_fame_anm: void,
store_wfc_status: StoreWfcStatus,
start_wfc: StartWfc,
choose_starter: void,
battle_starter: void,
battle_id: BattleId,
set_var_battle: SetVarBattle,
check_battle_type: CheckBattleType,
set_var_battle2: SetVarBattle2,
choose_poke_nick: ChoosePokeNick,
fade_screen: FadeScreen,
reset_screen: void,
warp: Warp,
rock_climb_animation: RockClimbAnimation,
surf_animation: void,
waterfall_animation: WaterfallAnimation,
flash_animation: void,
defog_animation: void,
prep_hm_effect: PrepHmEffect,
tuxedo: void,
check_bike: CheckBike,
ride_bike: RideBike,
ride_bike2: RideBike2,
give_poke_hiro_anm: GivePokeHiroAnm,
stop_give_poke_hiro_anm: void,
set_var_hero: SetVarHero,
set_variable_rival: SetVariableRival,
set_var_alter: SetVarAlter,
set_var_poke: SetVarPoke,
set_var_item: SetVarItem,
set_var_item_num: SetVarItemNum,
set_var_atk_item: SetVarAtkItem,
set_var_atk: SetVarAtk,
set_variable_number: SetVariableNumber,
set_var_poke_nick: SetVarPokeNick,
set_var_obj: SetVarObj,
set_var_trainer: SetVarTrainer,
set_var_wi_fi_sprite: SetVarWiFiSprite,
set_var_poke_stored: SetVarPokeStored,
set_var_str_hero: SetVarStrHero,
set_var_str_rival: SetVarStrRival,
store_starter: StoreStarter,
cmd_df: Cmd_df,
set_var_item_stored: SetVarItemStored,
set_var_item_stored2: SetVarItemStored2,
set_var_swarm_poke: SetVarSwarmPoke,
check_swarm_poke: CheckSwarmPoke,
start_battle_analysis: StartBattleAnalysis,
trainer_battle: TrainerBattle,
endtrainer_battle: EndtrainerBattle,
trainer_battle_stored: TrainerBattleStored,
trainer_battle_stored2: TrainerBattleStored2,
check_trainer_status: CheckTrainerStatus,
store_league_trainer: StoreLeagueTrainer,
lost_go_pc: void,
check_trainer_lost: CheckTrainerLost,
check_trainer_status2: CheckTrainerStatus2,
store_poke_party_defeated: StorePokePartyDefeated,
chs_friend: ChsFriend,
wire_battle_wait: WireBattleWait,
cmd_f6: void,
pokecontest: void,
start_ovation: StartOvation,
stop_ovation: StopOvation,
cmd_fa: Cmd_fa,
cmd_fb: Cmd_fb,
cmd_fc: Cmd_fc,
setvar_other_entry: SetvarOtherEntry,
cmd_fe: Cmd_fe,
setvat_hiro_entry: SetvatHiroEntry,
cmd_100: void,
black_flash_effect: void,
setvar_type_contest: SetvarTypeContest,
setvar_rank_contest: SetvarRankContest,
cmd_104: Cmd_104,
cmd_105: Cmd_105,
cmd_106: Cmd_106,
cmd_107: Cmd_107,
store_people_id_contest: StorePeopleIdContest,
cmd_109: Cmd_109,
setvat_hiro_entry2: SetvatHiroEntry2,
act_people_contest: ActPeopleContest,
cmd_10c: Cmd_10c,
cmd_10d: Cmd_10d,
cmd_10e: Cmd_10e,
cmd_10f: Cmd_10f,
cmd_110: Cmd_110,
flash_contest: FlashContest,
end_flash: void,
carpet_anm: void,
cmd_114: void,
cmd_115: Cmd_115,
show_lnk_cnt_record: void,
cmd_117: void,
cmd_118: void,
store_pokerus: StorePokerus,
warp_map_elevator: WarpMapElevator,
check_floor: CheckFloor,
start_lift: StartLift,
store_sin_pokemon_seen: StoreSinPokemonSeen,
cmd_11f: Cmd_11f,
store_tot_pokemon_seen: StoreTotPokemonSeen,
store_nat_pokemon_seen: StoreNatPokemonSeen,
set_var_text_pokedex: SetVarTextPokedex,
wild_battle: WildBattle,
starter_battle: StarterBattle,
explanation_battle: void,
honey_tree_battle: void,
check_if_honey_slathered: CheckIfHoneySlathered,
random_battle: void,
stop_random_battle: void,
write_autograph: void,
store_save_data: StoreSaveData,
check_save_data: CheckSaveData,
check_dress: CheckDress,
check_contest_win: CheckContestWin,
store_photo_name: StorePhotoName,
give_poketch: void,
check_ptch_appl: CheckPtchAppl,
act_pktch_appl: ActPktchAppl,
store_poketch_app: StorePoketchApp,
friend_b_t: FriendBT,
friend_b_t2: void,
cmd_138: Cmd_138,
open_union_function2: OpenUnionFunction2,
start_union: void,
link_closed: void,
set_union_function_id: SetUnionFunctionId,
close_union_function: void,
close_union_function2: void,
set_var_union_message: SetVarUnionMessage,
store_your_decision_union: StoreYourDecisionUnion,
store_other_decision_union: StoreOtherDecisionUnion,
cmd_142: void,
check_other_decision_union: CheckOtherDecisionUnion,
store_your_decision_union2: StoreYourDecisionUnion2,
store_other_decision_union2: StoreOtherDecisionUnion2,
check_other_decision_union2: CheckOtherDecisionUnion2,
pokemart: Pokemart,
pokemart1: Pokemart1,
pokemart2: Pokemart2,
pokemart3: Pokemart3,
defeat_go_pokecenter: void,
act_bike: ActBike,
check_gender: CheckGender,
heal_pokemon: void,
deact_wireless: void,
delete_entry: void,
cmd_151: void,
underground_id: UndergroundId,
union_room: void,
open_wi_fi_sprite: void,
store_wi_fi_sprite: StoreWiFiSprite,
act_wi_fi_sprite: ActWiFiSprite,
cmd_157: Cmd_157,
activate_pokedex: void,
give_running_shoes: void,
check_badge: CheckBadge,
enable_badge: EnableBadge,
disable_badge: DisableBadge,
check_follow: CheckFollow,
start_follow: void,
stop_follow: void,
cmd_164: void,
cmd_166: Cmd_166,
prepare_door_animation: PrepareDoorAnimation,
wait_action: WaitAction,
wait_close: WaitClose,
open_door: OpenDoor,
close_door: CloseDoor,
act_dcare_function: void,
store_p_d_care_num: StorePDCareNum,
pastoria_city_function: void,
pastoria_city_function2: void,
hearthrome_gym_function: void,
hearthrome_gym_function2: void,
canalave_gym_function: void,
veilstone_gym_function: void,
sunishore_gym_function: SunishoreGymFunction,
sunishore_gym_function2: SunishoreGymFunction2,
check_party_number: CheckPartyNumber,
open_berry_pouch: OpenBerryPouch,
cmd_179: Cmd_179,
cmd_17a: Cmd_17a,
cmd_17b: Cmd_17b,
set_nature_pokemon: SetNaturePokemon,
cmd_17d: Cmd_17d,
cmd_17e: Cmd_17e,
cmd_17f: Cmd_17f,
cmd_180: Cmd_180,
cmd_181: Cmd_181,
check_deoxis: CheckDeoxis,
cmd_183: Cmd_183,
cmd_184: Cmd_184,
cmd_185: void,
change_ow_position: ChangeOwPosition,
set_ow_position: SetOwPosition,
change_ow_movement: ChangeOwMovement,
release_ow: ReleaseOw,
set_tile_passable: SetTilePassable,
set_tile_locked: SetTileLocked,
set_ows_follow: SetOwsFollow,
show_clock_save: void,
hide_clock_save: void,
cmd_18f: Cmd_18f,
set_save_data: SetSaveData,
chs_pokemenu: void,
chs_pokemenu2: void,
store_poke_menu2: StorePokeMenu2,
chs_poke_contest: ChsPokeContest,
store_poke_contest: StorePokeContest,
show_poke_info: ShowPokeInfo,
store_poke_move: StorePokeMove,
check_poke_egg: CheckPokeEgg,
compare_poke_nick: ComparePokeNick,
check_party_number_union: CheckPartyNumberUnion,
check_poke_party_health: CheckPokePartyHealth,
check_poke_party_num_d_care: CheckPokePartyNumDCare,
check_egg_union: CheckEggUnion,
underground_function: UndergroundFunction,
underground_function2: UndergroundFunction2,
underground_start: void,
take_money_d_care: TakeMoneyDCare,
take_pokemon_d_care: TakePokemonDCare,
act_egg_day_c_man: void,
deact_egg_day_c_man: void,
set_var_poke_and_money_d_care: SetVarPokeAndMoneyDCare,
check_money_d_care: CheckMoneyDCare,
egg_animation: void,
set_var_poke_and_level_d_care: SetVarPokeAndLevelDCare,
set_var_poke_chosen_d_care: SetVarPokeChosenDCare,
give_poke_d_care: GivePokeDCare,
add_people2: AddPeople2,
remove_people2: RemovePeople2,
mail_box: void,
check_mail: CheckMail,
show_record_list: ShowRecordList,
check_time: CheckTime,
check_id_player: CheckIdPlayer,
random_text_stored: RandomTextStored,
store_happy_poke: StoreHappyPoke,
store_happy_status: StoreHappyStatus,
set_var_data_day_care: SetVarDataDayCare,
check_face_position: CheckFacePosition,
store_poke_d_care_love: StorePokeDCareLove,
check_status_solaceon_event: CheckStatusSolaceonEvent,
check_poke_party: CheckPokeParty,
copy_pokemon_height: CopyPokemonHeight,
set_variable_pokemon_height: SetVariablePokemonHeight,
compare_pokemon_height: ComparePokemonHeight,
check_pokemon_height: CheckPokemonHeight,
show_move_info: void,
store_poke_delete: StorePokeDelete,
store_move_delete: StoreMoveDelete,
check_move_num_delete: CheckMoveNumDelete,
store_delete_move: StoreDeleteMove,
check_delete_move: CheckDeleteMove,
setvar_move_delete: SetvarMoveDelete,
cmd_1cc: void,
de_activate_leader: DeActivateLeader,
hm_functions: HmFunctions,
flash_duration: FlashDuration,
defog_duration: DefogDuration,
give_accessories: GiveAccessories,
check_accessories: CheckAccessories,
cmd_1d4: Cmd_1d4,
give_accessories2: GiveAccessories2,
check_accessories2: CheckAccessories2,
berry_poffin: BerryPoffin,
set_var_b_tower_chs: SetVarBTowerChs,
battle_room_result: BattleRoomResult,
activate_b_tower: void,
store_b_tower_data: StoreBTowerData,
close_b_tower: void,
call_b_tower_functions: CallBTowerFunctions,
random_team_b_tower: RandomTeamBTower,
store_prize_num_b_tower: StorePrizeNumBTower,
store_people_id_b_tower: StorePeopleIdBTower,
call_b_tower_wire_function: CallBTowerWireFunction,
store_p_chosen_wire_b_tower: StorePChosenWireBTower,
store_rank_data_wire_b_tower: StoreRankDataWireBTower,
cmd_1e4: Cmd_1e4,
random_event: RandomEvent,
check_sinnoh_pokedex: CheckSinnohPokedex,
check_national_pokedex: CheckNationalPokedex,
show_sinnoh_sheet: void,
show_national_sheet: void,
cmd_1ec: void,
store_trophy_pokemon: StoreTrophyPokemon,
cmd_1ef: Cmd_1ef,
cmd_1f0: Cmd_1f0,
check_act_fossil: CheckActFossil,
cmd_1f2: void,
cmd_1f3: void,
check_item_chosen: CheckItemChosen,
compare_item_poke_fossil: CompareItemPokeFossil,
check_pokemon_level: CheckPokemonLevel,
check_is_pokemon_poisoned: CheckIsPokemonPoisoned,
pre_wfc: void,
store_furniture: StoreFurniture,
copy_furniture: CopyFurniture,
set_b_castle_function_id: SetBCastleFunctionId,
b_castle_funct_return: BCastleFunctReturn,
cmd_200: Cmd_200,
check_effect_hm: CheckEffectHm,
great_marsh_function: GreatMarshFunction,
battle_poke_colosseum: BattlePokeColosseum,
warp_last_elevator: void,
open_geo_net: void,
great_marsh_bynocule: void,
store_poke_colosseum_lost: StorePokeColosseumLost,
pokemon_picture: PokemonPicture,
hide_picture: void,
cmd_20a: Cmd_20a,
cmd_20b: void,
cmd_20c: void,
setvar_mt_coronet: SetvarMtCoronet,
cmd_20e: void,
check_quic_trine_coordinates: CheckQuicTrineCoordinates,
setvar_quick_train_coordinates: SetvarQuickTrainCoordinates,
move_train_anm: MoveTrainAnm,
store_poke_nature: StorePokeNature,
check_poke_nature: CheckPokeNature,
random_hallowes: RandomHallowes,
start_amity: void,
cmd_216: Cmd_216,
cmd_217: Cmd_217,
chs_r_s_poke: ChsRSPoke,
set_s_poke: SetSPoke,
check_s_poke: CheckSPoke,
cmd_21b: void,
act_swarm_poke: ActSwarmPoke,
cmd_21d: Cmd_21d,
cmd_21e: void,
check_move_remember: CheckMoveRemember,
cmd_220: void,
store_poke_remember: StorePokeRemember,
cmd_222: void,
store_remember_move: void,
teach_move: TeachMove,
check_teach_move: CheckTeachMove,
set_trade_id: SetTradeId,
check_pokemon_trade: CheckPokemonTrade,
trade_chosen_pokemon: TradeChosenPokemon,
stop_trade: void,
cmd_22b: void,
close_oak_assistant_event: void,
check_nat_pokedex_status: CheckNatPokedexStatus,
check_ribbon_number: CheckRibbonNumber,
check_ribbon: CheckRibbon,
give_ribbon: GiveRibbon,
setvar_ribbon: SetvarRibbon,
check_happy_ribbon: CheckHappyRibbon,
check_pokemart: CheckPokemart,
check_furniture: CheckFurniture,
cmd_236: Cmd_236,
check_phrase_box_input: CheckPhraseBoxInput,
check_status_phrase_box: CheckStatusPhraseBox,
decide_rules: DecideRules,
check_foot_step: CheckFootStep,
heal_pokemon_animation: HealPokemonAnimation,
store_elevator_direction: StoreElevatorDirection,
ship_animation: ShipAnimation,
cmd_23e: Cmd_23e,
store_phrase_box1_w: StorePhraseBox1W,
store_phrase_box2_w: StorePhraseBox2W,
setvar_phrase_box1_w: SetvarPhraseBox1W,
store_mt_coronet: StoreMtCoronet,
check_first_poke_party: CheckFirstPokeParty,
check_poke_type: CheckPokeType,
check_phrase_box_input2: CheckPhraseBoxInput2,
store_und_time: StoreUndTime,
prepare_pc_animation: PreparePcAnimation,
open_pc_animation: OpenPcAnimation,
close_pc_animation: ClosePcAnimation,
check_lotto_number: CheckLottoNumber,
compare_lotto_number: CompareLottoNumber,
setvar_id_poke_boxes: SetvarIdPokeBoxes,
cmd_250: void,
check_boxes_number: CheckBoxesNumber,
stop_great_marsh: StopGreatMarsh,
check_poke_catching_show: CheckPokeCatchingShow,
close_catching_show: void,
check_catching_show_records: CheckCatchingShowRecords,
sprt_save: void,
ret_sprt_save: void,
elev_lg_animation: void,
check_elev_lg_anm: CheckElevLgAnm,
elev_ir_anm: void,
stop_elev_anm: void,
check_elev_position: CheckElevPosition,
galact_anm: void,
galact_anm2: void,
main_event: MainEvent,
check_accessories3: CheckAccessories3,
act_deoxis_form_change: ActDeoxisFormChange,
change_form_deoxis: ChangeFormDeoxis,
check_coombe_event: CheckCoombeEvent,
act_contest_map: void,
cmd_266: void,
pokecasino: Pokecasino,
check_time2: CheckTime2,
regigigas_anm: RegigigasAnm,
cresselia_anm: CresseliaAnm,
check_regi: CheckRegi,
check_massage: CheckMassage,
unown_message_box: UnownMessageBox,
check_p_catching_show: CheckPCatchingShow,
cmd_26f: void,
shaymin_anm: ShayminAnm,
thank_name_insert: ThankNameInsert,
setvar_shaymin: SetvarShaymin,
setvar_accessories2: SetvarAccessories2,
cmd_274: Cmd_274,
check_record_casino: CheckRecordCasino,
check_coins_casino: CheckCoinsCasino,
srt_random_num: SrtRandomNum,
check_poke_level2: CheckPokeLevel2,
cmd_279: Cmd_279,
league_castle_view: void,
cmd_27b: void,
setvar_amity_pokemon: SetvarAmityPokemon,
cmd_27d: Cmd_27d,
check_first_time_v_shop: CheckFirstTimeVShop,
cmd_27f: Cmd_27f,
setvar_id_number: SetvarIdNumber,
cmd_281: Cmd_281,
setvar_unk: SetvarUnk,
cmd_283: Cmd_283,
check_ruin_maniac: CheckRuinManiac,
check_turn_back: CheckTurnBack,
check_ug_people_num: CheckUgPeopleNum,
check_ug_fossil_num: CheckUgFossilNum,
check_ug_traps_num: CheckUgTrapsNum,
check_poffin_item: CheckPoffinItem,
check_poffin_case_status: CheckPoffinCaseStatus,
unk_funct2: UnkFunct2,
pokemon_party_picture: PokemonPartyPicture,
act_learning: void,
set_sound_learning: SetSoundLearning,
check_first_time_champion: CheckFirstTimeChampion,
choose_poke_d_care: ChoosePokeDCare,
store_poke_d_care: StorePokeDCare,
cmd_292: Cmd_292,
check_master_rank: CheckMasterRank,
show_battle_points_box: ShowBattlePointsBox,
hide_battle_points_box: void,
update_battle_points_box: void,
take_b_points: TakeBPoints,
check_b_points: CheckBPoints,
cmd_29c: Cmd_29c,
choice_multi: ChoiceMulti,
h_m_effect: HMEffect,
camera_bump_effect: CameraBumpEffect,
double_battle: DoubleBattle,
apply_movement2: ApplyMovement2,
cmd_2a2: Cmd_2a2,
store_act_hero_friend_code: StoreActHeroFriendCode,
store_act_other_friend_code: StoreActOtherFriendCode,
choose_trade_pokemon: void,
chs_prize_casino: ChsPrizeCasino,
check_plate: CheckPlate,
take_coins_casino: TakeCoinsCasino,
check_coins_casino2: CheckCoinsCasino2,
compare_phrase_box_input: ComparePhraseBoxInput,
store_seal_num: StoreSealNum,
activate_mystery_gift: void,
check_follow_battle: CheckFollowBattle,
cmd_2af: Cmd_2af,
cmd_2b0: void,
cmd_2b1: void,
cmd_2b2: void,
setvar_seal_random: SetvarSealRandom,
darkrai_function: DarkraiFunction,
cmd_2b6: Cmd_2b6,
store_poke_num_party: StorePokeNumParty,
store_poke_nickname: StorePokeNickname,
close_multi_union: void,
check_battle_union: CheckBattleUnion,
cmd_2_b_b: void,
check_wild_battle2: CheckWildBattle2,
wild_battle2: WildBattle,
store_trainer_card_star: StoreTrainerCardStar,
bike_ride: void,
cmd_2c0: Cmd_2c0,
show_save_box: void,
hide_save_box: void,
cmd_2c3: Cmd_2c3,
show_b_tower_some: ShowBTowerSome,
delete_saves_b_factory: DeleteSavesBFactory,
spin_trade_union: void,
check_version_game: CheckVersionGame,
show_b_arcade_recors: ShowBArcadeRecors,
eterna_gym_anm: void,
floral_clock_animation: void,
check_poke_party2: CheckPokeParty2,
check_poke_castle: CheckPokeCastle,
act_team_galactic_events: ActTeamGalacticEvents,
choose_wire_poke_b_castle: ChooseWirePokeBCastle,
cmd_2d0: Cmd_2d0,
cmd_2d1: Cmd_2d1,
cmd_2d2: Cmd_2d2,
cmd_2d3: Cmd_2d3,
cmd_2d4: Cmd_2d4,
cmd_2d5: Cmd_2d5,
cmd_2d6: void,
cmd_2d7: Cmd_2d7,
cmd_2d8: Cmd_2d8,
cmd_2d9: Cmd_2d9,
cmd_2da: Cmd_2da,
cmd_2db: Cmd_2db,
cmd_2dc: Cmd_2dc,
cmd_2dd: Cmd_2dd,
cmd_2de: Cmd_2de,
cmd_2df: Cmd_2df,
cmd_2e0: Cmd_2e0,
cmd_2e1: Cmd_2e1,
cmd_2e2: void,
cmd_2e3: void,
cmd_2e4: Cmd_2e4,
cmd_2e5: Cmd_2e5,
cmd_2e6: Cmd_2e6,
cmd_2e7: Cmd_2e7,
cmd_2e8: Cmd_2e8,
cmd_2e9: Cmd_2e9,
cmd_2ea: Cmd_2ea,
cmd_2eb: Cmd_2eb,
cmd_2ec: Cmd_2ec,
cmd_2ed: void,
cmd_2ee: Cmd_2ee,
cmd_2f0: void,
cmd_2f2: void,
cmd_2f3: Cmd_2f3,
cmd_2f4: Cmd_2f4,
cmd_2f5: Cmd_2f5,
cmd_2f6: Cmd_2f6,
cmd_2f7: Cmd_2f7,
cmd_2f8: void,
cmd_2f9: Cmd_2f9,
cmd_2fa: Cmd_2fa,
cmd_2fb: void,
cmd_2fc: Cmd_2fc,
cmd_2fd: Cmd_2fd,
cmd_2fe: Cmd_2fe,
cmd_2ff: Cmd_2ff,
cmd_300: void,
cmd_302: Cmd_302,
cmd_303: Cmd_303,
cmd_304: Cmd_304,
cmd_305: Cmd_305,
cmd_306: Cmd_306,
cmd_307: Cmd_307,
cmd_308: Cmd_308,
cmd_309: void,
cmd_30a: Cmd_30a,
cmd_30b: void,
cmd_30c: void,
cmd_30d: Cmd_30d,
cmd_30e: Cmd_30e,
cmd_30f: Cmd_30f,
cmd_310: void,
cmd_311: Cmd_311,
cmd_312: Cmd_312,
cmd_313: Cmd_313,
cmd_314: Cmd_314,
cmd_315: Cmd_315,
cmd_316: void,
cmd_317: Cmd_317,
wild_battle3: WildBattle,
cmd_319: Cmd_319,
cmd_31a: Cmd_31a,
cmd_31b: Cmd_31b,
cmd_31c: Cmd_31c,
cmd_31d: Cmd_31d,
cmd_31e: Cmd_31e,
cmd_31f: void,
cmd_320: void,
cmd_321: Cmd_321,
cmd_322: void,
cmd_323: Cmd_323,
cmd_324: Cmd_324,
cmd_325: Cmd_325,
cmd_326: Cmd_326,
cmd_327: Cmd_327,
portal_effect: PortalEffect,
cmd_329: Cmd_329,
cmd_32a: Cmd_32a,
cmd_32b: Cmd_32b,
cmd_32c: Cmd_32c,
cmd_32d: void,
cmd_32e: void,
cmd_32f: Cmd_32f,
cmd_330: void,
cmd_331: void,
cmd_332: void,
cmd_333: Cmd_333,
cmd_334: Cmd_334,
cmd_335: Cmd_335,
cmd_336: Cmd_336,
cmd_337: Cmd_337,
cmd_338: void,
cmd_339: void,
cmd_33a: Cmd_33a,
cmd_33c: Cmd_33c,
cmd_33d: Cmd_33d,
cmd_33e: Cmd_33e,
cmd_33f: Cmd_33f,
cmd_340: Cmd_340,
cmd_341: Cmd_341,
cmd_342: Cmd_342,
cmd_343: Cmd_343,
cmd_344: Cmd_344,
cmd_345: Cmd_345,
cmd_346: Cmd_346,
display_floor: DisplayFloor,
};
pub const Kind = enum(u16) {
nop0 = lu16.init(0x0).inner,
nop1 = lu16.init(0x1).inner,
end = lu16.init(0x2).inner,
return2 = lu16.init(0x3).inner,
cmd_a = lu16.init(0xa).inner,
@"if" = lu16.init(0x11).inner,
if2 = lu16.init(0x12).inner,
call_standard = lu16.init(0x14).inner,
exit_standard = lu16.init(0x15).inner,
jump = lu16.init(0x16).inner,
call = lu16.init(0x1a).inner,
@"return" = lu16.init(0x1b).inner,
compare_last_result_jump = lu16.init(0x1c).inner,
compare_last_result_call = lu16.init(0x1d).inner,
set_flag = lu16.init(0x1e).inner,
clear_flag = lu16.init(0x1f).inner,
check_flag = lu16.init(0x20).inner,
cmd_21 = lu16.init(0x21).inner,
cmd_22 = lu16.init(0x22).inner,
set_trainer_id = lu16.init(0x23).inner,
cmd_24 = lu16.init(0x24).inner,
clear_trainer_id = lu16.init(0x25).inner,
script_cmd__add_value = lu16.init(0x26).inner,
script_cmd__sub_value = lu16.init(0x27).inner,
set_var = lu16.init(0x28).inner,
copy_var = lu16.init(0x29).inner,
message2 = lu16.init(0x2b).inner,
message = lu16.init(0x2c).inner,
message3 = lu16.init(0x2d).inner,
message4 = lu16.init(0x2e).inner,
message5 = lu16.init(0x2f).inner,
cmd_30 = lu16.init(0x30).inner,
wait_button = lu16.init(0x31).inner,
cmd_32 = lu16.init(0x32).inner,
cmd_33 = lu16.init(0x33).inner,
close_msg_on_key_press = lu16.init(0x34).inner,
freeze_message_box = lu16.init(0x35).inner,
call_message_box = lu16.init(0x36).inner,
color_msg_box = lu16.init(0x37).inner,
type_message_box = lu16.init(0x38).inner,
no_map_message_box = lu16.init(0x39).inner,
call_text_msg_box = lu16.init(0x3a).inner,
store_menu_status = lu16.init(0x3b).inner,
show_menu = lu16.init(0x3c).inner,
yes_no_box = lu16.init(0x3e).inner,
multi = lu16.init(0x40).inner,
multi2 = lu16.init(0x41).inner,
cmd_42 = lu16.init(0x42).inner,
close_multi = lu16.init(0x43).inner,
multi3 = lu16.init(0x44).inner,
multi4 = lu16.init(0x45).inner,
txt_msg_scrp_multi = lu16.init(0x46).inner,
close_multi4 = lu16.init(0x47).inner,
play_fanfare = lu16.init(0x49).inner,
multi_row = lu16.init(0x48).inner,
play_fanfare2 = lu16.init(0x4a).inner,
wait_fanfare = lu16.init(0x4b).inner,
play_cry = lu16.init(0x4c).inner,
wait_cry = lu16.init(0x4d).inner,
soundfr = lu16.init(0x4e).inner,
cmd_4f = lu16.init(0x4f).inner,
play_sound = lu16.init(0x50).inner,
stop = lu16.init(0x51).inner,
restart = lu16.init(0x52).inner,
cmd_53 = lu16.init(0x53).inner,
switch_music = lu16.init(0x54).inner,
store_saying_learned = lu16.init(0x55).inner,
play_sound2 = lu16.init(0x57).inner,
cmd_58 = lu16.init(0x58).inner,
check_saying_learned = lu16.init(0x59).inner,
swith_music2 = lu16.init(0x5a).inner,
act_microphone = lu16.init(0x5b).inner,
deact_microphone = lu16.init(0x5c).inner,
cmd_5d = lu16.init(0x5d).inner,
apply_movement = lu16.init(0x5e).inner,
wait_movement = lu16.init(0x5f).inner,
lock_all = lu16.init(0x60).inner,
release_all = lu16.init(0x61).inner,
lock = lu16.init(0x62).inner,
release = lu16.init(0x63).inner,
add_people = lu16.init(0x64).inner,
remove_people = lu16.init(0x65).inner,
lock_cam = lu16.init(0x66).inner,
zoom_cam = lu16.init(0x67).inner,
face_player = lu16.init(0x68).inner,
check_sprite_position = lu16.init(0x69).inner,
check_person_position = lu16.init(0x6b).inner,
continue_follow = lu16.init(0x6c).inner,
follow_hero = lu16.init(0x6d).inner,
take_money = lu16.init(0x70).inner,
check_money = lu16.init(0x71).inner,
show_money = lu16.init(0x72).inner,
hide_money = lu16.init(0x73).inner,
update_money = lu16.init(0x74).inner,
show_coins = lu16.init(0x75).inner,
hide_coins = lu16.init(0x76).inner,
update_coins = lu16.init(0x77).inner,
check_coins = lu16.init(0x78).inner,
give_coins = lu16.init(0x79).inner,
take_coins = lu16.init(0x7a).inner,
take_item = lu16.init(0x7b).inner,
give_item = lu16.init(0x7c).inner,
check_store_item = lu16.init(0x7d).inner,
check_item = lu16.init(0x7e).inner,
store_item_taken = lu16.init(0x7f).inner,
store_item_type = lu16.init(0x80).inner,
send_item_type1 = lu16.init(0x83).inner,
cmd_84 = lu16.init(0x84).inner,
check_underground_pc_status = lu16.init(0x85).inner,
cmd_86 = lu16.init(0x86).inner,
send_item_type2 = lu16.init(0x87).inner,
cmd_88 = lu16.init(0x88).inner,
cmd_89 = lu16.init(0x89).inner,
cmd_8a = lu16.init(0x8a).inner,
cmd_8b = lu16.init(0x8b).inner,
cmd_8c = lu16.init(0x8c).inner,
cmd_8d = lu16.init(0x8d).inner,
cmd_8e = lu16.init(0x8e).inner,
send_item_type3 = lu16.init(0x8f).inner,
check_pokemon_party = lu16.init(0x93).inner,
store_pokemon_party = lu16.init(0x94).inner,
set_pokemon_party_stored = lu16.init(0x95).inner,
give_pokemon = lu16.init(0x96).inner,
give_egg = lu16.init(0x97).inner,
check_move = lu16.init(0x99).inner,
check_place_stored = lu16.init(0x9a).inner,
cmd_9b = lu16.init(0x9b).inner,
cmd_9c = lu16.init(0x9c).inner,
cmd_9d = lu16.init(0x9d).inner,
cmd_9e = lu16.init(0x9e).inner,
cmd_9f = lu16.init(0x9f).inner,
cmd_a0 = lu16.init(0xa0).inner,
call_end = lu16.init(0xa1).inner,
cmd__a2 = lu16.init(0xa2).inner,
wfc_ = lu16.init(0xa3).inner,
cmd_a4 = lu16.init(0xa4).inner,
interview = lu16.init(0xa5).inner,
dress_pokemon = lu16.init(0xa6).inner,
display_dressed_pokemon = lu16.init(0xa7).inner,
display_contest_pokemon = lu16.init(0xa8).inner,
open_ball_capsule = lu16.init(0xa9).inner,
open_sinnoh_maps = lu16.init(0xaa).inner,
open_pc_function = lu16.init(0xab).inner,
draw_union = lu16.init(0xac).inner,
trainer_case_union = lu16.init(0xad).inner,
trade_union = lu16.init(0xae).inner,
record_mixing_union = lu16.init(0xaf).inner,
end_game = lu16.init(0xb0).inner,
hall_fame_anm = lu16.init(0xb1).inner,
store_wfc_status = lu16.init(0xb2).inner,
start_wfc = lu16.init(0xb3).inner,
choose_starter = lu16.init(0xb4).inner,
battle_starter = lu16.init(0xb5).inner,
battle_id = lu16.init(0xb6).inner,
set_var_battle = lu16.init(0xb7).inner,
check_battle_type = lu16.init(0xb8).inner,
set_var_battle2 = lu16.init(0xb9).inner,
choose_poke_nick = lu16.init(0xbb).inner,
fade_screen = lu16.init(0xbc).inner,
reset_screen = lu16.init(0xbd).inner,
warp = lu16.init(0xbe).inner,
rock_climb_animation = lu16.init(0xbf).inner,
surf_animation = lu16.init(0xc0).inner,
waterfall_animation = lu16.init(0xc1).inner,
flash_animation = lu16.init(0xc3).inner,
defog_animation = lu16.init(0xc4).inner,
prep_hm_effect = lu16.init(0xc5).inner,
tuxedo = lu16.init(0xc6).inner,
check_bike = lu16.init(0xc7).inner,
ride_bike = lu16.init(0xc8).inner,
ride_bike2 = lu16.init(0xc9).inner,
give_poke_hiro_anm = lu16.init(0xcb).inner,
stop_give_poke_hiro_anm = lu16.init(0xcc).inner,
set_var_hero = lu16.init(0xcd).inner,
set_variable_rival = lu16.init(0xce).inner,
set_var_alter = lu16.init(0xcf).inner,
set_var_poke = lu16.init(0xd0).inner,
set_var_item = lu16.init(0xd1).inner,
set_var_item_num = lu16.init(0xd2).inner,
set_var_atk_item = lu16.init(0xd3).inner,
set_var_atk = lu16.init(0xd4).inner,
set_variable_number = lu16.init(0xd5).inner,
set_var_poke_nick = lu16.init(0xd6).inner,
set_var_obj = lu16.init(0xd7).inner,
set_var_trainer = lu16.init(0xd8).inner,
set_var_wi_fi_sprite = lu16.init(0xd9).inner,
set_var_poke_stored = lu16.init(0xda).inner,
set_var_str_hero = lu16.init(0xdb).inner,
set_var_str_rival = lu16.init(0xdc).inner,
store_starter = lu16.init(0xde).inner,
cmd_df = lu16.init(0xdf).inner,
set_var_item_stored = lu16.init(0xe0).inner,
set_var_item_stored2 = lu16.init(0xe1).inner,
set_var_swarm_poke = lu16.init(0xe2).inner,
check_swarm_poke = lu16.init(0xe3).inner,
start_battle_analysis = lu16.init(0xe4).inner,
trainer_battle = lu16.init(0xe5).inner,
endtrainer_battle = lu16.init(0xe6).inner,
trainer_battle_stored = lu16.init(0xe7).inner,
trainer_battle_stored2 = lu16.init(0xe8).inner,
check_trainer_status = lu16.init(0xe9).inner,
store_league_trainer = lu16.init(0xea).inner,
lost_go_pc = lu16.init(0xeb).inner,
check_trainer_lost = lu16.init(0xec).inner,
check_trainer_status2 = lu16.init(0xed).inner,
store_poke_party_defeated = lu16.init(0xee).inner,
chs_friend = lu16.init(0xf2).inner,
wire_battle_wait = lu16.init(0xf3).inner,
cmd_f6 = lu16.init(0xf6).inner,
pokecontest = lu16.init(0xf7).inner,
start_ovation = lu16.init(0xf8).inner,
stop_ovation = lu16.init(0xf9).inner,
cmd_fa = lu16.init(0xfa).inner,
cmd_fb = lu16.init(0xfb).inner,
cmd_fc = lu16.init(0xfc).inner,
setvar_other_entry = lu16.init(0xfd).inner,
cmd_fe = lu16.init(0xfe).inner,
setvat_hiro_entry = lu16.init(0xff).inner,
cmd_100 = lu16.init(0x100).inner,
black_flash_effect = lu16.init(0x101).inner,
setvar_type_contest = lu16.init(0x102).inner,
setvar_rank_contest = lu16.init(0x103).inner,
cmd_104 = lu16.init(0x104).inner,
cmd_105 = lu16.init(0x105).inner,
cmd_106 = lu16.init(0x106).inner,
cmd_107 = lu16.init(0x107).inner,
store_people_id_contest = lu16.init(0x108).inner,
cmd_109 = lu16.init(0x109).inner,
setvat_hiro_entry2 = lu16.init(0x10a).inner,
act_people_contest = lu16.init(0x10b).inner,
cmd_10c = lu16.init(0x10c).inner,
cmd_10d = lu16.init(0x10d).inner,
cmd_10e = lu16.init(0x10e).inner,
cmd_10f = lu16.init(0x10f).inner,
cmd_110 = lu16.init(0x110).inner,
flash_contest = lu16.init(0x111).inner,
end_flash = lu16.init(0x112).inner,
carpet_anm = lu16.init(0x113).inner,
cmd_114 = lu16.init(0x114).inner,
cmd_115 = lu16.init(0x115).inner,
show_lnk_cnt_record = lu16.init(0x116).inner,
cmd_117 = lu16.init(0x117).inner,
cmd_118 = lu16.init(0x118).inner,
store_pokerus = lu16.init(0x119).inner,
warp_map_elevator = lu16.init(0x11b).inner,
check_floor = lu16.init(0x11c).inner,
start_lift = lu16.init(0x11d).inner,
store_sin_pokemon_seen = lu16.init(0x11e).inner,
cmd_11f = lu16.init(0x11f).inner,
store_tot_pokemon_seen = lu16.init(0x120).inner,
store_nat_pokemon_seen = lu16.init(0x121).inner,
set_var_text_pokedex = lu16.init(0x123).inner,
wild_battle = lu16.init(0x124).inner,
starter_battle = lu16.init(0x125).inner,
explanation_battle = lu16.init(0x126).inner,
honey_tree_battle = lu16.init(0x127).inner,
check_if_honey_slathered = lu16.init(0x128).inner,
random_battle = lu16.init(0x129).inner,
stop_random_battle = lu16.init(0x12a).inner,
write_autograph = lu16.init(0x12b).inner,
store_save_data = lu16.init(0x12c).inner,
check_save_data = lu16.init(0x12d).inner,
check_dress = lu16.init(0x12e).inner,
check_contest_win = lu16.init(0x12f).inner,
store_photo_name = lu16.init(0x130).inner,
give_poketch = lu16.init(0x131).inner,
check_ptch_appl = lu16.init(0x132).inner,
act_pktch_appl = lu16.init(0x133).inner,
store_poketch_app = lu16.init(0x134).inner,
friend_b_t = lu16.init(0x135).inner,
friend_b_t2 = lu16.init(0x136).inner,
cmd_138 = lu16.init(0x138).inner,
open_union_function2 = lu16.init(0x139).inner,
start_union = lu16.init(0x13a).inner,
link_closed = lu16.init(0x13b).inner,
set_union_function_id = lu16.init(0x13c).inner,
close_union_function = lu16.init(0x13d).inner,
close_union_function2 = lu16.init(0x13e).inner,
set_var_union_message = lu16.init(0x13f).inner,
store_your_decision_union = lu16.init(0x140).inner,
store_other_decision_union = lu16.init(0x141).inner,
cmd_142 = lu16.init(0x142).inner,
check_other_decision_union = lu16.init(0x143).inner,
store_your_decision_union2 = lu16.init(0x144).inner,
store_other_decision_union2 = lu16.init(0x145).inner,
check_other_decision_union2 = lu16.init(0x146).inner,
pokemart = lu16.init(0x147).inner,
pokemart1 = lu16.init(0x148).inner,
pokemart2 = lu16.init(0x149).inner,
pokemart3 = lu16.init(0x14a).inner,
defeat_go_pokecenter = lu16.init(0x14b).inner,
act_bike = lu16.init(0x14c).inner,
check_gender = lu16.init(0x14d).inner,
heal_pokemon = lu16.init(0x14e).inner,
deact_wireless = lu16.init(0x14f).inner,
delete_entry = lu16.init(0x150).inner,
cmd_151 = lu16.init(0x151).inner,
underground_id = lu16.init(0x152).inner,
union_room = lu16.init(0x153).inner,
open_wi_fi_sprite = lu16.init(0x154).inner,
store_wi_fi_sprite = lu16.init(0x155).inner,
act_wi_fi_sprite = lu16.init(0x156).inner,
cmd_157 = lu16.init(0x157).inner,
activate_pokedex = lu16.init(0x158).inner,
give_running_shoes = lu16.init(0x15a).inner,
check_badge = lu16.init(0x15b).inner,
enable_badge = lu16.init(0x15c).inner,
disable_badge = lu16.init(0x15d).inner,
check_follow = lu16.init(0x160).inner,
start_follow = lu16.init(0x161).inner,
stop_follow = lu16.init(0x162).inner,
cmd_164 = lu16.init(0x164).inner,
cmd_166 = lu16.init(0x166).inner,
prepare_door_animation = lu16.init(0x168).inner,
wait_action = lu16.init(0x169).inner,
wait_close = lu16.init(0x16a).inner,
open_door = lu16.init(0x16b).inner,
close_door = lu16.init(0x16c).inner,
act_dcare_function = lu16.init(0x16d).inner,
store_p_d_care_num = lu16.init(0x16e).inner,
pastoria_city_function = lu16.init(0x16f).inner,
pastoria_city_function2 = lu16.init(0x170).inner,
hearthrome_gym_function = lu16.init(0x171).inner,
hearthrome_gym_function2 = lu16.init(0x172).inner,
canalave_gym_function = lu16.init(0x173).inner,
veilstone_gym_function = lu16.init(0x174).inner,
sunishore_gym_function = lu16.init(0x175).inner,
sunishore_gym_function2 = lu16.init(0x176).inner,
check_party_number = lu16.init(0x177).inner,
open_berry_pouch = lu16.init(0x178).inner,
cmd_179 = lu16.init(0x179).inner,
cmd_17a = lu16.init(0x17a).inner,
cmd_17b = lu16.init(0x17b).inner,
set_nature_pokemon = lu16.init(0x17c).inner,
cmd_17d = lu16.init(0x17d).inner,
cmd_17e = lu16.init(0x17e).inner,
cmd_17f = lu16.init(0x17f).inner,
cmd_180 = lu16.init(0x180).inner,
cmd_181 = lu16.init(0x181).inner,
check_deoxis = lu16.init(0x182).inner,
cmd_183 = lu16.init(0x183).inner,
cmd_184 = lu16.init(0x184).inner,
cmd_185 = lu16.init(0x185).inner,
change_ow_position = lu16.init(0x186).inner,
set_ow_position = lu16.init(0x187).inner,
change_ow_movement = lu16.init(0x188).inner,
release_ow = lu16.init(0x189).inner,
set_tile_passable = lu16.init(0x18a).inner,
set_tile_locked = lu16.init(0x18b).inner,
set_ows_follow = lu16.init(0x18c).inner,
show_clock_save = lu16.init(0x18d).inner,
hide_clock_save = lu16.init(0x18e).inner,
cmd_18f = lu16.init(0x18f).inner,
set_save_data = lu16.init(0x190).inner,
chs_pokemenu = lu16.init(0x191).inner,
chs_pokemenu2 = lu16.init(0x192).inner,
store_poke_menu2 = lu16.init(0x193).inner,
chs_poke_contest = lu16.init(0x194).inner,
store_poke_contest = lu16.init(0x195).inner,
show_poke_info = lu16.init(0x196).inner,
store_poke_move = lu16.init(0x197).inner,
check_poke_egg = lu16.init(0x198).inner,
compare_poke_nick = lu16.init(0x199).inner,
check_party_number_union = lu16.init(0x19a).inner,
check_poke_party_health = lu16.init(0x19b).inner,
check_poke_party_num_d_care = lu16.init(0x19c).inner,
check_egg_union = lu16.init(0x19d).inner,
underground_function = lu16.init(0x19e).inner,
underground_function2 = lu16.init(0x19f).inner,
underground_start = lu16.init(0x1a0).inner,
take_money_d_care = lu16.init(0x1a3).inner,
take_pokemon_d_care = lu16.init(0x1a4).inner,
act_egg_day_c_man = lu16.init(0x1a8).inner,
deact_egg_day_c_man = lu16.init(0x1a9).inner,
set_var_poke_and_money_d_care = lu16.init(0x1aa).inner,
check_money_d_care = lu16.init(0x1ab).inner,
egg_animation = lu16.init(0x1ac).inner,
set_var_poke_and_level_d_care = lu16.init(0x1ae).inner,
set_var_poke_chosen_d_care = lu16.init(0x1af).inner,
give_poke_d_care = lu16.init(0x1b0).inner,
add_people2 = lu16.init(0x1b1).inner,
remove_people2 = lu16.init(0x1b2).inner,
mail_box = lu16.init(0x1b3).inner,
check_mail = lu16.init(0x1b4).inner,
show_record_list = lu16.init(0x1b5).inner,
check_time = lu16.init(0x1b6).inner,
check_id_player = lu16.init(0x1b7).inner,
random_text_stored = lu16.init(0x1b8).inner,
store_happy_poke = lu16.init(0x1b9).inner,
store_happy_status = lu16.init(0x1ba).inner,
set_var_data_day_care = lu16.init(0x1bc).inner,
check_face_position = lu16.init(0x1bd).inner,
store_poke_d_care_love = lu16.init(0x1be).inner,
check_status_solaceon_event = lu16.init(0x1bf).inner,
check_poke_party = lu16.init(0x1c0).inner,
copy_pokemon_height = lu16.init(0x1c1).inner,
set_variable_pokemon_height = lu16.init(0x1c2).inner,
compare_pokemon_height = lu16.init(0x1c3).inner,
check_pokemon_height = lu16.init(0x1c4).inner,
show_move_info = lu16.init(0x1c5).inner,
store_poke_delete = lu16.init(0x1c6).inner,
store_move_delete = lu16.init(0x1c7).inner,
check_move_num_delete = lu16.init(0x1c8).inner,
store_delete_move = lu16.init(0x1c9).inner,
check_delete_move = lu16.init(0x1ca).inner,
setvar_move_delete = lu16.init(0x1cb).inner,
cmd_1cc = lu16.init(0x1cc).inner,
de_activate_leader = lu16.init(0x1cd).inner,
hm_functions = lu16.init(0x1cf).inner,
flash_duration = lu16.init(0x1d0).inner,
defog_duration = lu16.init(0x1d1).inner,
give_accessories = lu16.init(0x1d2).inner,
check_accessories = lu16.init(0x1d3).inner,
cmd_1d4 = lu16.init(0x1d4).inner,
give_accessories2 = lu16.init(0x1d5).inner,
check_accessories2 = lu16.init(0x1d6).inner,
berry_poffin = lu16.init(0x1d7).inner,
set_var_b_tower_chs = lu16.init(0x1d8).inner,
battle_room_result = lu16.init(0x1d9).inner,
activate_b_tower = lu16.init(0x1da).inner,
store_b_tower_data = lu16.init(0x1db).inner,
close_b_tower = lu16.init(0x1dc).inner,
call_b_tower_functions = lu16.init(0x1dd).inner,
random_team_b_tower = lu16.init(0x1de).inner,
store_prize_num_b_tower = lu16.init(0x1df).inner,
store_people_id_b_tower = lu16.init(0x1e0).inner,
call_b_tower_wire_function = lu16.init(0x1e1).inner,
store_p_chosen_wire_b_tower = lu16.init(0x1e2).inner,
store_rank_data_wire_b_tower = lu16.init(0x1e3).inner,
cmd_1e4 = lu16.init(0x1e4).inner,
random_event = lu16.init(0x1e5).inner,
check_sinnoh_pokedex = lu16.init(0x1e8).inner,
check_national_pokedex = lu16.init(0x1e9).inner,
show_sinnoh_sheet = lu16.init(0x1ea).inner,
show_national_sheet = lu16.init(0x1eb).inner,
cmd_1ec = lu16.init(0x1ec).inner,
store_trophy_pokemon = lu16.init(0x1ed).inner,
cmd_1ef = lu16.init(0x1ef).inner,
cmd_1f0 = lu16.init(0x1f0).inner,
check_act_fossil = lu16.init(0x1f1).inner,
cmd_1f2 = lu16.init(0x1f2).inner,
cmd_1f3 = lu16.init(0x1f3).inner,
check_item_chosen = lu16.init(0x1f4).inner,
compare_item_poke_fossil = lu16.init(0x1f5).inner,
check_pokemon_level = lu16.init(0x1f6).inner,
check_is_pokemon_poisoned = lu16.init(0x1f7).inner,
pre_wfc = lu16.init(0x1f8).inner,
store_furniture = lu16.init(0x1f9).inner,
copy_furniture = lu16.init(0x1fb).inner,
set_b_castle_function_id = lu16.init(0x1fe).inner,
b_castle_funct_return = lu16.init(0x1ff).inner,
cmd_200 = lu16.init(0x200).inner,
check_effect_hm = lu16.init(0x201).inner,
great_marsh_function = lu16.init(0x202).inner,
battle_poke_colosseum = lu16.init(0x203).inner,
warp_last_elevator = lu16.init(0x204).inner,
open_geo_net = lu16.init(0x205).inner,
great_marsh_bynocule = lu16.init(0x206).inner,
store_poke_colosseum_lost = lu16.init(0x207).inner,
pokemon_picture = lu16.init(0x208).inner,
hide_picture = lu16.init(0x209).inner,
cmd_20a = lu16.init(0x20a).inner,
cmd_20b = lu16.init(0x20b).inner,
cmd_20c = lu16.init(0x20c).inner,
setvar_mt_coronet = lu16.init(0x20d).inner,
cmd_20e = lu16.init(0x20e).inner,
check_quic_trine_coordinates = lu16.init(0x20f).inner,
setvar_quick_train_coordinates = lu16.init(0x210).inner,
move_train_anm = lu16.init(0x211).inner,
store_poke_nature = lu16.init(0x212).inner,
check_poke_nature = lu16.init(0x213).inner,
random_hallowes = lu16.init(0x214).inner,
start_amity = lu16.init(0x215).inner,
cmd_216 = lu16.init(0x216).inner,
cmd_217 = lu16.init(0x217).inner,
chs_r_s_poke = lu16.init(0x218).inner,
set_s_poke = lu16.init(0x219).inner,
check_s_poke = lu16.init(0x21a).inner,
cmd_21b = lu16.init(0x21b).inner,
act_swarm_poke = lu16.init(0x21c).inner,
cmd_21d = lu16.init(0x21d).inner,
cmd_21e = lu16.init(0x21e).inner,
check_move_remember = lu16.init(0x21f).inner,
cmd_220 = lu16.init(0x220).inner,
store_poke_remember = lu16.init(0x221).inner,
cmd_222 = lu16.init(0x222).inner,
store_remember_move = lu16.init(0x223).inner,
teach_move = lu16.init(0x224).inner,
check_teach_move = lu16.init(0x225).inner,
set_trade_id = lu16.init(0x226).inner,
check_pokemon_trade = lu16.init(0x228).inner,
trade_chosen_pokemon = lu16.init(0x229).inner,
stop_trade = lu16.init(0x22a).inner,
cmd_22b = lu16.init(0x22b).inner,
close_oak_assistant_event = lu16.init(0x22c).inner,
check_nat_pokedex_status = lu16.init(0x22d).inner,
check_ribbon_number = lu16.init(0x22f).inner,
check_ribbon = lu16.init(0x230).inner,
give_ribbon = lu16.init(0x231).inner,
setvar_ribbon = lu16.init(0x232).inner,
check_happy_ribbon = lu16.init(0x233).inner,
check_pokemart = lu16.init(0x234).inner,
check_furniture = lu16.init(0x235).inner,
cmd_236 = lu16.init(0x236).inner,
check_phrase_box_input = lu16.init(0x237).inner,
check_status_phrase_box = lu16.init(0x238).inner,
decide_rules = lu16.init(0x239).inner,
check_foot_step = lu16.init(0x23a).inner,
heal_pokemon_animation = lu16.init(0x23b).inner,
store_elevator_direction = lu16.init(0x23c).inner,
ship_animation = lu16.init(0x23d).inner,
cmd_23e = lu16.init(0x23e).inner,
store_phrase_box1_w = lu16.init(0x243).inner,
store_phrase_box2_w = lu16.init(0x244).inner,
setvar_phrase_box1_w = lu16.init(0x245).inner,
store_mt_coronet = lu16.init(0x246).inner,
check_first_poke_party = lu16.init(0x247).inner,
check_poke_type = lu16.init(0x248).inner,
check_phrase_box_input2 = lu16.init(0x249).inner,
store_und_time = lu16.init(0x24a).inner,
prepare_pc_animation = lu16.init(0x24b).inner,
open_pc_animation = lu16.init(0x24c).inner,
close_pc_animation = lu16.init(0x24d).inner,
check_lotto_number = lu16.init(0x24e).inner,
compare_lotto_number = lu16.init(0x24f).inner,
setvar_id_poke_boxes = lu16.init(0x251).inner,
cmd_250 = lu16.init(0x250).inner,
check_boxes_number = lu16.init(0x252).inner,
stop_great_marsh = lu16.init(0x253).inner,
check_poke_catching_show = lu16.init(0x254).inner,
close_catching_show = lu16.init(0x255).inner,
check_catching_show_records = lu16.init(0x256).inner,
sprt_save = lu16.init(0x257).inner,
ret_sprt_save = lu16.init(0x258).inner,
elev_lg_animation = lu16.init(0x259).inner,
check_elev_lg_anm = lu16.init(0x25a).inner,
elev_ir_anm = lu16.init(0x25b).inner,
stop_elev_anm = lu16.init(0x25c).inner,
check_elev_position = lu16.init(0x25d).inner,
galact_anm = lu16.init(0x25e).inner,
galact_anm2 = lu16.init(0x25f).inner,
main_event = lu16.init(0x260).inner,
check_accessories3 = lu16.init(0x261).inner,
act_deoxis_form_change = lu16.init(0x262).inner,
change_form_deoxis = lu16.init(0x263).inner,
check_coombe_event = lu16.init(0x264).inner,
act_contest_map = lu16.init(0x265).inner,
cmd_266 = lu16.init(0x266).inner,
pokecasino = lu16.init(0x267).inner,
check_time2 = lu16.init(0x268).inner,
regigigas_anm = lu16.init(0x269).inner,
cresselia_anm = lu16.init(0x26a).inner,
check_regi = lu16.init(0x26b).inner,
check_massage = lu16.init(0x26c).inner,
unown_message_box = lu16.init(0x26d).inner,
check_p_catching_show = lu16.init(0x26e).inner,
cmd_26f = lu16.init(0x26f).inner,
shaymin_anm = lu16.init(0x270).inner,
thank_name_insert = lu16.init(0x271).inner,
setvar_shaymin = lu16.init(0x272).inner,
setvar_accessories2 = lu16.init(0x273).inner,
cmd_274 = lu16.init(0x274).inner,
check_record_casino = lu16.init(0x275).inner,
check_coins_casino = lu16.init(0x276).inner,
srt_random_num = lu16.init(0x277).inner,
check_poke_level2 = lu16.init(0x278).inner,
cmd_279 = lu16.init(0x279).inner,
league_castle_view = lu16.init(0x27a).inner,
cmd_27b = lu16.init(0x27b).inner,
setvar_amity_pokemon = lu16.init(0x27c).inner,
cmd_27d = lu16.init(0x27d).inner,
check_first_time_v_shop = lu16.init(0x27e).inner,
cmd_27f = lu16.init(0x27f).inner,
setvar_id_number = lu16.init(0x280).inner,
cmd_281 = lu16.init(0x281).inner,
setvar_unk = lu16.init(0x282).inner,
cmd_283 = lu16.init(0x283).inner,
check_ruin_maniac = lu16.init(0x284).inner,
check_turn_back = lu16.init(0x285).inner,
check_ug_people_num = lu16.init(0x286).inner,
check_ug_fossil_num = lu16.init(0x287).inner,
check_ug_traps_num = lu16.init(0x288).inner,
check_poffin_item = lu16.init(0x289).inner,
check_poffin_case_status = lu16.init(0x28a).inner,
unk_funct2 = lu16.init(0x28b).inner,
pokemon_party_picture = lu16.init(0x28c).inner,
act_learning = lu16.init(0x28d).inner,
set_sound_learning = lu16.init(0x28e).inner,
check_first_time_champion = lu16.init(0x28f).inner,
choose_poke_d_care = lu16.init(0x290).inner,
store_poke_d_care = lu16.init(0x291).inner,
cmd_292 = lu16.init(0x292).inner,
check_master_rank = lu16.init(0x293).inner,
show_battle_points_box = lu16.init(0x294).inner,
hide_battle_points_box = lu16.init(0x295).inner,
update_battle_points_box = lu16.init(0x296).inner,
take_b_points = lu16.init(0x299).inner,
check_b_points = lu16.init(0x29a).inner,
cmd_29c = lu16.init(0x29c).inner,
choice_multi = lu16.init(0x29d).inner,
h_m_effect = lu16.init(0x29e).inner,
camera_bump_effect = lu16.init(0x29f).inner,
double_battle = lu16.init(0x2a0).inner,
apply_movement2 = lu16.init(0x2a1).inner,
cmd_2a2 = lu16.init(0x2a2).inner,
store_act_hero_friend_code = lu16.init(0x2a3).inner,
store_act_other_friend_code = lu16.init(0x2a4).inner,
choose_trade_pokemon = lu16.init(0x2a5).inner,
chs_prize_casino = lu16.init(0x2a6).inner,
check_plate = lu16.init(0x2a7).inner,
take_coins_casino = lu16.init(0x2a8).inner,
check_coins_casino2 = lu16.init(0x2a9).inner,
compare_phrase_box_input = lu16.init(0x2aa).inner,
store_seal_num = lu16.init(0x2ab).inner,
activate_mystery_gift = lu16.init(0x2ac).inner,
check_follow_battle = lu16.init(0x2ad).inner,
cmd_2af = lu16.init(0x2af).inner,
cmd_2b0 = lu16.init(0x2b0).inner,
cmd_2b1 = lu16.init(0x2b1).inner,
cmd_2b2 = lu16.init(0x2b2).inner,
setvar_seal_random = lu16.init(0x2b3).inner,
darkrai_function = lu16.init(0x2b5).inner,
cmd_2b6 = lu16.init(0x2b6).inner,
store_poke_num_party = lu16.init(0x2b7).inner,
store_poke_nickname = lu16.init(0x2b8).inner,
close_multi_union = lu16.init(0x2b9).inner,
check_battle_union = lu16.init(0x2ba).inner,
cmd_2_b_b = lu16.init(0x2bb).inner,
check_wild_battle2 = lu16.init(0x2bc).inner,
wild_battle2 = lu16.init(0x2bd).inner,
store_trainer_card_star = lu16.init(0x2be).inner,
bike_ride = lu16.init(0x2bf).inner,
cmd_2c0 = lu16.init(0x2c0).inner,
show_save_box = lu16.init(0x2c1).inner,
hide_save_box = lu16.init(0x2c2).inner,
cmd_2c3 = lu16.init(0x2c3).inner,
show_b_tower_some = lu16.init(0x2c4).inner,
delete_saves_b_factory = lu16.init(0x2c5).inner,
spin_trade_union = lu16.init(0x2c6).inner,
check_version_game = lu16.init(0x2c7).inner,
show_b_arcade_recors = lu16.init(0x2c8).inner,
eterna_gym_anm = lu16.init(0x2c9).inner,
floral_clock_animation = lu16.init(0x2ca).inner,
check_poke_party2 = lu16.init(0x2cb).inner,
check_poke_castle = lu16.init(0x2cc).inner,
act_team_galactic_events = lu16.init(0x2cd).inner,
choose_wire_poke_b_castle = lu16.init(0x2cf).inner,
cmd_2d0 = lu16.init(0x2d0).inner,
cmd_2d1 = lu16.init(0x2d1).inner,
cmd_2d2 = lu16.init(0x2d2).inner,
cmd_2d3 = lu16.init(0x2d3).inner,
cmd_2d4 = lu16.init(0x2d4).inner,
cmd_2d5 = lu16.init(0x2d5).inner,
cmd_2d6 = lu16.init(0x2d6).inner,
cmd_2d7 = lu16.init(0x2d7).inner,
cmd_2d8 = lu16.init(0x2d8).inner,
cmd_2d9 = lu16.init(0x2d9).inner,
cmd_2da = lu16.init(0x2da).inner,
cmd_2db = lu16.init(0x2db).inner,
cmd_2dc = lu16.init(0x2dc).inner,
cmd_2dd = lu16.init(0x2dd).inner,
cmd_2de = lu16.init(0x2de).inner,
cmd_2df = lu16.init(0x2df).inner,
cmd_2e0 = lu16.init(0x2e0).inner,
cmd_2e1 = lu16.init(0x2e1).inner,
cmd_2e2 = lu16.init(0x2e2).inner,
cmd_2e3 = lu16.init(0x2e3).inner,
cmd_2e4 = lu16.init(0x2e4).inner,
cmd_2e5 = lu16.init(0x2e5).inner,
cmd_2e6 = lu16.init(0x2e6).inner,
cmd_2e7 = lu16.init(0x2e7).inner,
cmd_2e8 = lu16.init(0x2e8).inner,
cmd_2e9 = lu16.init(0x2e9).inner,
cmd_2ea = lu16.init(0x2ea).inner,
cmd_2eb = lu16.init(0x2eb).inner,
cmd_2ec = lu16.init(0x2ec).inner,
cmd_2ed = lu16.init(0x2ed).inner,
cmd_2ee = lu16.init(0x2ee).inner,
cmd_2f0 = lu16.init(0x2f0).inner,
cmd_2f2 = lu16.init(0x2f2).inner,
cmd_2f3 = lu16.init(0x2f3).inner,
cmd_2f4 = lu16.init(0x2f4).inner,
cmd_2f5 = lu16.init(0x2f5).inner,
cmd_2f6 = lu16.init(0x2f6).inner,
cmd_2f7 = lu16.init(0x2f7).inner,
cmd_2f8 = lu16.init(0x2f8).inner,
cmd_2f9 = lu16.init(0x2f9).inner,
cmd_2fa = lu16.init(0x2fa).inner,
cmd_2fb = lu16.init(0x2fb).inner,
cmd_2fc = lu16.init(0x2fc).inner,
cmd_2fd = lu16.init(0x2fd).inner,
cmd_2fe = lu16.init(0x2fe).inner,
cmd_2ff = lu16.init(0x2ff).inner,
cmd_300 = lu16.init(0x300).inner,
cmd_302 = lu16.init(0x302).inner,
cmd_303 = lu16.init(0x303).inner,
cmd_304 = lu16.init(0x304).inner,
cmd_305 = lu16.init(0x305).inner,
cmd_306 = lu16.init(0x306).inner,
cmd_307 = lu16.init(0x307).inner,
cmd_308 = lu16.init(0x308).inner,
cmd_309 = lu16.init(0x309).inner,
cmd_30a = lu16.init(0x30a).inner,
cmd_30b = lu16.init(0x30b).inner,
cmd_30c = lu16.init(0x30c).inner,
cmd_30d = lu16.init(0x30d).inner,
cmd_30e = lu16.init(0x30e).inner,
cmd_30f = lu16.init(0x30f).inner,
cmd_310 = lu16.init(0x310).inner,
cmd_311 = lu16.init(0x311).inner,
cmd_312 = lu16.init(0x312).inner,
cmd_313 = lu16.init(0x313).inner,
cmd_314 = lu16.init(0x314).inner,
cmd_315 = lu16.init(0x315).inner,
cmd_316 = lu16.init(0x316).inner,
cmd_317 = lu16.init(0x317).inner,
wild_battle3 = lu16.init(0x318).inner,
cmd_319 = lu16.init(0x319).inner,
cmd_31a = lu16.init(0x31a).inner,
cmd_31b = lu16.init(0x31b).inner,
cmd_31c = lu16.init(0x31c).inner,
cmd_31d = lu16.init(0x31d).inner,
cmd_31e = lu16.init(0x31e).inner,
cmd_31f = lu16.init(0x31f).inner,
cmd_320 = lu16.init(0x320).inner,
cmd_321 = lu16.init(0x321).inner,
cmd_322 = lu16.init(0x322).inner,
cmd_323 = lu16.init(0x323).inner,
cmd_324 = lu16.init(0x324).inner,
cmd_325 = lu16.init(0x325).inner,
cmd_326 = lu16.init(0x326).inner,
cmd_327 = lu16.init(0x327).inner,
portal_effect = lu16.init(0x328).inner,
cmd_329 = lu16.init(0x329).inner,
cmd_32a = lu16.init(0x32a).inner,
cmd_32b = lu16.init(0x32b).inner,
cmd_32c = lu16.init(0x32c).inner,
cmd_32d = lu16.init(0x32d).inner,
cmd_32e = lu16.init(0x32e).inner,
cmd_32f = lu16.init(0x32f).inner,
cmd_330 = lu16.init(0x330).inner,
cmd_331 = lu16.init(0x331).inner,
cmd_332 = lu16.init(0x332).inner,
cmd_333 = lu16.init(0x333).inner,
cmd_334 = lu16.init(0x334).inner,
cmd_335 = lu16.init(0x335).inner,
cmd_336 = lu16.init(0x336).inner,
cmd_337 = lu16.init(0x337).inner,
cmd_338 = lu16.init(0x338).inner,
cmd_339 = lu16.init(0x339).inner,
cmd_33a = lu16.init(0x33a).inner,
cmd_33c = lu16.init(0x33c).inner,
cmd_33d = lu16.init(0x33d).inner,
cmd_33e = lu16.init(0x33e).inner,
cmd_33f = lu16.init(0x33f).inner,
cmd_340 = lu16.init(0x340).inner,
cmd_341 = lu16.init(0x341).inner,
cmd_342 = lu16.init(0x342).inner,
cmd_343 = lu16.init(0x343).inner,
cmd_344 = lu16.init(0x344).inner,
cmd_345 = lu16.init(0x345).inner,
cmd_346 = lu16.init(0x346).inner,
display_floor = lu16.init(0x347).inner,
};
pub const Return2 = packed struct {
a: lu16,
b: lu16,
};
pub const Cmd_a = packed struct {
a: u8,
b: u8,
};
pub const If = packed struct {
@"var": lu16,
nr: lu16,
};
pub const If2 = packed struct {
@"var": lu16,
nr: lu16,
};
pub const CallStandard = packed struct {
a: lu16,
};
pub const Jump = packed struct {
adr: li32,
};
pub const Call = packed struct {
adr: li32,
};
pub const CompareLastResultJump = packed struct {
cond: u8,
adr: li32,
};
pub const CompareLastResultCall = packed struct {
cond: u8,
adr: li32,
};
pub const SetFlag = packed struct {
a: lu16,
};
pub const ClearFlag = packed struct {
a: lu16,
};
pub const CheckFlag = packed struct {
a: lu16,
};
pub const Cmd_21 = packed struct {
a: lu16,
b: lu16,
};
pub const Cmd_22 = packed struct {
a: lu16,
};
pub const SetTrainerId = packed struct {
a: lu16,
};
pub const Cmd_24 = packed struct {
a: lu16,
};
pub const ClearTrainerId = packed struct {
a: lu16,
};
pub const ScriptCmd_AddValue = packed struct {
a: lu16,
b: lu16,
};
pub const ScriptCmd_SubValue = packed struct {
a: lu16,
b: lu16,
};
pub const SetVar = packed struct {
destination: lu16,
value: lu16,
};
pub const CopyVar = packed struct {
a: lu16,
b: lu16,
};
pub const Message2 = packed struct {
nr: u8,
};
pub const Message = packed struct {
nr: u8,
};
pub const Message3 = packed struct {
nr: lu16,
};
pub const Message4 = packed struct {
nr: lu16,
};
pub const Message5 = packed struct {
nr: u8,
};
pub const CallMessageBox = packed struct {
a: u8,
b: u8,
c: lu16,
d: lu16,
};
pub const ColorMsgBox = packed struct {
a: u8,
b: lu16,
};
pub const TypeMessageBox = packed struct {
a: u8,
};
pub const CallTextMsgBox = packed struct {
a: u8,
b: lu16,
};
pub const StoreMenuStatus = packed struct {
a: lu16,
};
pub const YesNoBox = packed struct {
nr: lu16,
};
pub const Multi = packed struct {
a: u8,
b: u8,
c: u8,
d: u8,
e: lu16,
};
pub const Multi2 = packed struct {
a: u8,
b: u8,
c: u8,
d: u8,
e: lu16,
};
pub const Cmd_42 = packed struct {
a: u8,
b: u8,
};
pub const Multi3 = packed struct {
a: u8,
b: u8,
c: u8,
d: u8,
e: lu16,
};
pub const Multi4 = packed struct {
a: u8,
b: u8,
c: u8,
d: u8,
e: lu16,
};
pub const TxtMsgScrpMulti = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const PlayFanfare = packed struct {
nr: lu16,
};
pub const MultiRow = packed struct {
a: u8,
};
pub const PlayFanfare2 = packed struct {
nr: lu16,
};
pub const WaitFanfare = packed struct {
a: lu16,
};
pub const PlayCry = packed struct {
a: lu16,
b: lu16,
};
pub const Soundfr = packed struct {
a: lu16,
};
pub const PlaySound = packed struct {
a: lu16,
};
pub const Stop = packed struct {
a: lu16,
};
pub const Cmd_53 = packed struct {
a: lu16,
};
pub const SwitchMusic = packed struct {
a: lu16,
b: lu16,
};
pub const StoreSayingLearned = packed struct {
a: lu16,
};
pub const PlaySound2 = packed struct {
a: lu16,
};
pub const Cmd_58 = packed struct {
a: u8,
};
pub const CheckSayingLearned = packed struct {
a: lu16,
};
pub const SwithMusic2 = packed struct {
a: lu16,
};
pub const ApplyMovement = packed struct {
a: lu16,
adr: lu32,
};
pub const Lock = packed struct {
a: lu16,
};
pub const Release = packed struct {
a: lu16,
};
pub const AddPeople = packed struct {
a: lu16,
};
pub const RemovePeople = packed struct {
a: lu16,
};
pub const LockCam = packed struct {
a: lu16,
b: lu16,
};
pub const CheckSpritePosition = packed struct {
a: lu16,
b: lu16,
};
pub const CheckPersonPosition = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const ContinueFollow = packed struct {
a: lu16,
b: u8,
};
pub const FollowHero = packed struct {
a: lu16,
b: lu16,
};
pub const TakeMoney = packed struct {
a: lu32,
};
pub const CheckMoney = packed struct {
a: lu16,
b: lu32,
};
pub const ShowMoney = packed struct {
a: lu16,
b: lu16,
};
pub const ShowCoins = packed struct {
a: lu16,
b: lu16,
};
pub const CheckCoins = packed struct {
a: lu16,
};
pub const GiveCoins = packed struct {
a: lu16,
};
pub const TakeCoins = packed struct {
a: lu16,
};
pub const TakeItem = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const GiveItem = packed struct {
itemid: lu16,
quantity: lu16,
@"return": lu16,
};
pub const CheckStoreItem = packed struct {
itemid: lu16,
b: lu16,
c: lu16,
};
pub const CheckItem = packed struct {
itemid: lu16,
quantity: lu16,
@"return": lu16,
};
pub const StoreItemTaken = packed struct {
a: lu16,
b: lu16,
};
pub const StoreItemType = packed struct {
a: lu16,
b: lu16,
};
pub const SendItemType1 = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const Cmd_84 = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const CheckUndergroundPcStatus = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const Cmd_86 = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const SendItemType2 = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const Cmd_88 = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const Cmd_89 = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const Cmd_8a = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const Cmd_8b = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const Cmd_8c = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const Cmd_8d = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const Cmd_8e = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const SendItemType3 = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const CheckPokemonParty = packed struct {
a: lu16,
b: lu16,
};
pub const StorePokemonParty = packed struct {
a: lu16,
b: lu16,
};
pub const SetPokemonPartyStored = packed struct {
a: lu16,
b: lu16,
};
pub const GivePokemon = packed struct {
species: lu16,
level: lu16,
item: lu16,
res: lu16,
};
pub const GiveEgg = packed struct {
a: lu16,
b: lu16,
};
pub const CheckMove = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const CheckPlaceStored = packed struct {
a: lu16,
b: lu16,
};
pub const Cmd_9b = packed struct {
a: lu16,
b: lu16,
};
pub const Cmd_a4 = packed struct {
a: lu16,
};
pub const DressPokemon = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const DisplayDressedPokemon = packed struct {
a: lu16,
b: lu16,
};
pub const DisplayContestPokemon = packed struct {
a: lu16,
b: lu16,
};
pub const OpenPcFunction = packed struct {
a: u8,
};
pub const StoreWfcStatus = packed struct {
a: lu16,
b: lu16,
};
pub const StartWfc = packed struct {
a: lu16,
};
pub const BattleId = packed struct {
a: lu16,
};
pub const SetVarBattle = packed struct {
a: lu16,
b: lu16,
};
pub const CheckBattleType = packed struct {
a: lu16,
};
pub const SetVarBattle2 = packed struct {
a: lu16,
b: lu16,
};
pub const ChoosePokeNick = packed struct {
a: lu16,
b: lu16,
};
pub const FadeScreen = packed struct {
a: lu16,
b: lu16,
c: lu16,
d: lu16,
};
pub const Warp = packed struct {
a: lu16,
b: lu16,
c: lu16,
d: lu16,
e: lu16,
};
pub const RockClimbAnimation = packed struct {
a: lu16,
};
pub const SurfAnimation = packed struct {
a: lu16,
};
pub const WaterfallAnimation = packed struct {
a: lu16,
};
pub const PrepHmEffect = packed struct {
a: lu16,
};
pub const CheckBike = packed struct {
a: lu16,
};
pub const RideBike = packed struct {
a: u8,
};
pub const RideBike2 = packed struct {
a: u8,
};
pub const GivePokeHiroAnm = packed struct {
a: lu16,
};
pub const SetVarHero = packed struct {
a: u8,
};
pub const SetVariableRival = packed struct {
a: u8,
};
pub const SetVarAlter = packed struct {
a: u8,
};
pub const SetVarPoke = packed struct {
a: u8,
b: lu16,
};
pub const SetVarItem = packed struct {
a: u8,
b: lu16,
};
pub const SetVarItemNum = packed struct {
a: u8,
b: lu16,
};
pub const SetVarAtkItem = packed struct {
a: u8,
b: lu16,
};
pub const SetVarAtk = packed struct {
a: u8,
b: lu16,
};
pub const SetVariableNumber = packed struct {
a: u8,
b: lu16,
};
pub const SetVarPokeNick = packed struct {
a: u8,
b: lu16,
};
pub const SetVarObj = packed struct {
a: u8,
b: lu16,
};
pub const SetVarTrainer = packed struct {
a: u8,
b: lu16,
};
pub const SetVarWiFiSprite = packed struct {
a: u8,
};
pub const SetVarPokeStored = packed struct {
a: u8,
b: lu16,
c: lu16,
d: u8,
};
pub const SetVarStrHero = packed struct {
a: u8,
};
pub const SetVarStrRival = packed struct {
a: u8,
};
pub const StoreStarter = packed struct {
a: lu16,
};
pub const Cmd_df = packed struct {
a: u8,
b: lu16,
};
pub const SetVarItemStored = packed struct {
a: u8,
b: lu16,
};
pub const SetVarItemStored2 = packed struct {
a: u8,
b: lu16,
};
pub const SetVarSwarmPoke = packed struct {
a: u8,
b: lu16,
};
pub const CheckSwarmPoke = packed struct {
a: lu16,
b: lu16,
};
pub const StartBattleAnalysis = packed struct {
a: lu16,
};
pub const TrainerBattle = packed struct {
a: lu16,
b: lu16,
};
pub const EndtrainerBattle = packed struct {
a: lu16,
b: lu16,
};
pub const TrainerBattleStored = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const TrainerBattleStored2 = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const CheckTrainerStatus = packed struct {
a: lu16,
};
pub const StoreLeagueTrainer = packed struct {
a: lu16,
};
pub const CheckTrainerLost = packed struct {
a: lu16,
};
pub const CheckTrainerStatus2 = packed struct {
a: lu16,
};
pub const StorePokePartyDefeated = packed struct {
a: lu16,
};
pub const ChsFriend = packed struct {
a: lu16,
b: lu16,
c: lu16,
d: lu16,
};
pub const WireBattleWait = packed struct {
a: lu16,
b: lu16,
c: lu16,
d: lu16,
};
pub const StartOvation = packed struct {
a: lu16,
};
pub const StopOvation = packed struct {
a: lu16,
};
pub const Cmd_fa = packed struct {
a: lu16,
b: lu16,
c: lu16,
d: lu16,
};
pub const Cmd_fb = packed struct {
a: lu16,
};
pub const Cmd_fc = packed struct {
a: lu16,
b: lu16,
};
pub const SetvarOtherEntry = packed struct {
a: lu16,
b: lu16,
};
pub const Cmd_fe = packed struct {
a: lu16,
b: lu16,
};
pub const SetvatHiroEntry = packed struct {
a: lu16,
b: lu16,
};
pub const SetvarTypeContest = packed struct {
a: lu16,
};
pub const SetvarRankContest = packed struct {
a: lu16,
};
pub const Cmd_104 = packed struct {
a: lu16,
};
pub const Cmd_105 = packed struct {
a: lu16,
};
pub const Cmd_106 = packed struct {
a: lu16,
};
pub const Cmd_107 = packed struct {
a: lu16,
};
pub const StorePeopleIdContest = packed struct {
a: lu16,
};
pub const Cmd_109 = packed struct {
a: lu16,
};
pub const SetvatHiroEntry2 = packed struct {
a: lu16,
b: lu16,
};
pub const ActPeopleContest = packed struct {
a: lu16,
b: lu16,
};
pub const Cmd_10c = packed struct {
a: lu16,
};
pub const Cmd_10d = packed struct {
a: lu16,
};
pub const Cmd_10e = packed struct {
a: lu16,
};
pub const Cmd_10f = packed struct {
a: lu16,
};
pub const Cmd_110 = packed struct {
a: lu16,
b: lu16,
c: lu16,
d: lu16,
};
pub const FlashContest = packed struct {
a: lu16,
};
pub const Cmd_115 = packed struct {
a: lu16,
};
pub const StorePokerus = packed struct {
a: lu16,
};
pub const WarpMapElevator = packed struct {
a: lu16,
b: lu16,
c: lu16,
d: lu16,
e: lu16,
};
pub const CheckFloor = packed struct {
a: lu16,
};
pub const StartLift = packed struct {
a: u8,
b: u8,
c: lu16,
d: lu16,
};
pub const StoreSinPokemonSeen = packed struct {
a: lu16,
};
pub const Cmd_11f = packed struct {
a: lu16,
};
pub const StoreTotPokemonSeen = packed struct {
a: lu16,
};
pub const StoreNatPokemonSeen = packed struct {
a: lu16,
};
pub const SetVarTextPokedex = packed struct {
a: u8,
b: lu16,
};
pub const WildBattle = packed struct {
species: lu16,
level: lu16,
};
pub const StarterBattle = packed struct {
a: lu16,
b: lu16,
};
pub const CheckIfHoneySlathered = packed struct {
a: lu16,
};
pub const StoreSaveData = packed struct {
a: lu16,
};
pub const CheckSaveData = packed struct {
a: lu16,
};
pub const CheckDress = packed struct {
a: lu16,
b: lu16,
};
pub const CheckContestWin = packed struct {
a: lu16,
b: lu16,
};
pub const StorePhotoName = packed struct {
a: lu16,
};
pub const CheckPtchAppl = packed struct {
a: lu16,
};
pub const ActPktchAppl = packed struct {
a: lu16,
};
pub const StorePoketchApp = packed struct {
a: lu16,
b: lu16,
};
pub const FriendBT = packed struct {
nr: lu16,
};
pub const Cmd_138 = packed struct {
a: lu16,
};
pub const OpenUnionFunction2 = packed struct {
a: lu16,
};
pub const SetUnionFunctionId = packed struct {
a: lu16,
};
pub const SetVarUnionMessage = packed struct {
a: lu16,
b: lu16,
};
pub const StoreYourDecisionUnion = packed struct {
a: lu16,
};
pub const StoreOtherDecisionUnion = packed struct {
a: lu16,
};
pub const CheckOtherDecisionUnion = packed struct {
a: lu16,
b: lu16,
};
pub const StoreYourDecisionUnion2 = packed struct {
a: lu16,
};
pub const StoreOtherDecisionUnion2 = packed struct {
a: lu16,
};
pub const CheckOtherDecisionUnion2 = packed struct {
a: lu16,
b: lu16,
};
pub const Pokemart = packed struct {
a: lu16,
};
pub const Pokemart1 = packed struct {
a: lu16,
};
pub const Pokemart2 = packed struct {
a: lu16,
};
pub const Pokemart3 = packed struct {
a: lu16,
};
pub const ActBike = packed struct {
a: lu16,
};
pub const CheckGender = packed struct {
a: lu16,
};
pub const UndergroundId = packed struct {
a: lu16,
};
pub const StoreWiFiSprite = packed struct {
a: lu16,
b: lu16,
};
pub const ActWiFiSprite = packed struct {
a: lu16,
};
pub const Cmd_157 = packed struct {
a: lu16,
};
pub const CheckBadge = packed struct {
a: lu16,
b: lu16,
};
pub const EnableBadge = packed struct {
a: lu16,
};
pub const DisableBadge = packed struct {
a: lu16,
};
pub const CheckFollow = packed struct {
a: lu16,
};
pub const Cmd_166 = packed struct {
a: lu16,
};
pub const PrepareDoorAnimation = packed struct {
a: lu16,
b: lu16,
c: lu16,
d: lu16,
e: u8,
};
pub const WaitAction = packed struct {
a: u8,
};
pub const WaitClose = packed struct {
a: u8,
};
pub const OpenDoor = packed struct {
a: u8,
};
pub const CloseDoor = packed struct {
a: u8,
};
pub const StorePDCareNum = packed struct {
a: lu16,
};
pub const SunishoreGymFunction = packed struct {
a: u8,
};
pub const SunishoreGymFunction2 = packed struct {
a: u8,
};
pub const CheckPartyNumber = packed struct {
a: lu16,
};
pub const OpenBerryPouch = packed struct {
a: u8,
};
pub const Cmd_179 = packed struct {
a: lu16,
};
pub const Cmd_17a = packed struct {
a: lu16,
b: lu16,
};
pub const Cmd_17b = packed struct {
a: u8,
b: lu16,
c: lu16,
};
pub const SetNaturePokemon = packed struct {
a: u8,
b: lu16,
};
pub const Cmd_17d = packed struct {
a: lu16,
};
pub const Cmd_17e = packed struct {
a: lu16,
};
pub const Cmd_17f = packed struct {
a: lu16,
};
pub const Cmd_180 = packed struct {
a: lu16,
};
pub const Cmd_181 = packed struct {
a: lu16,
};
pub const CheckDeoxis = packed struct {
a: lu16,
};
pub const Cmd_183 = packed struct {
a: lu16,
};
pub const Cmd_184 = packed struct {
a: lu16,
};
pub const ChangeOwPosition = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const SetOwPosition = packed struct {
a: lu16,
b: lu16,
c: lu16,
d: lu16,
e: lu16,
};
pub const ChangeOwMovement = packed struct {
a: lu16,
b: lu16,
};
pub const ReleaseOw = packed struct {
a: lu16,
b: lu16,
};
pub const SetTilePassable = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const SetTileLocked = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const SetOwsFollow = packed struct {
a: lu16,
b: lu16,
};
pub const Cmd_18f = packed struct {
a: lu16,
};
pub const SetSaveData = packed struct {
a: lu16,
};
pub const StorePokeMenu2 = packed struct {
a: lu16,
};
pub const ChsPokeContest = packed struct {
a: lu16,
b: lu16,
c: lu16,
d: lu16,
};
pub const StorePokeContest = packed struct {
a: lu16,
b: lu16,
};
pub const ShowPokeInfo = packed struct {
a: lu16,
};
pub const StorePokeMove = packed struct {
a: lu16,
};
pub const CheckPokeEgg = packed struct {
a: lu16,
b: lu16,
};
pub const ComparePokeNick = packed struct {
a: lu16,
b: lu16,
};
pub const CheckPartyNumberUnion = packed struct {
a: lu16,
};
pub const CheckPokePartyHealth = packed struct {
a: lu16,
b: lu16,
};
pub const CheckPokePartyNumDCare = packed struct {
a: lu16,
};
pub const CheckEggUnion = packed struct {
a: lu16,
};
pub const UndergroundFunction = packed struct {
a: lu16,
b: lu16,
};
pub const UndergroundFunction2 = packed struct {
a: lu16,
};
pub const TakeMoneyDCare = packed struct {
a: lu16,
};
pub const TakePokemonDCare = packed struct {
a: lu16,
b: lu16,
};
pub const SetVarPokeAndMoneyDCare = packed struct {
a: lu16,
b: lu16,
};
pub const CheckMoneyDCare = packed struct {
a: lu16,
b: lu16,
};
pub const SetVarPokeAndLevelDCare = packed struct {
a: lu16,
b: lu16,
};
pub const SetVarPokeChosenDCare = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const GivePokeDCare = packed struct {
a: lu16,
};
pub const AddPeople2 = packed struct {
a: lu16,
};
pub const RemovePeople2 = packed struct {
a: lu16,
};
pub const CheckMail = packed struct {
a: lu16,
};
pub const ShowRecordList = packed struct {
a: lu16,
};
pub const CheckTime = packed struct {
a: lu16,
};
pub const CheckIdPlayer = packed struct {
a: lu16,
b: lu16,
};
pub const RandomTextStored = packed struct {
a: lu16,
b: lu16,
};
pub const StoreHappyPoke = packed struct {
a: lu16,
b: lu16,
};
pub const StoreHappyStatus = packed struct {
a: lu16,
b: lu16,
};
pub const SetVarDataDayCare = packed struct {
a: lu16,
b: lu16,
c: lu16,
d: lu16,
};
pub const CheckFacePosition = packed struct {
a: lu16,
};
pub const StorePokeDCareLove = packed struct {
a: lu16,
};
pub const CheckStatusSolaceonEvent = packed struct {
a: lu16,
};
pub const CheckPokeParty = packed struct {
a: lu16,
b: lu16,
};
pub const CopyPokemonHeight = packed struct {
a: lu16,
b: lu16,
};
pub const SetVariablePokemonHeight = packed struct {
a: lu16,
};
pub const ComparePokemonHeight = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const CheckPokemonHeight = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const StorePokeDelete = packed struct {
a: lu16,
};
pub const StoreMoveDelete = packed struct {
a: lu16,
};
pub const CheckMoveNumDelete = packed struct {
a: lu16,
b: lu16,
};
pub const StoreDeleteMove = packed struct {
a: lu16,
b: lu16,
};
pub const CheckDeleteMove = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const SetvarMoveDelete = packed struct {
a: u8,
b: lu16,
c: lu16,
};
pub const DeActivateLeader = packed struct {
a: lu16,
b: lu16,
c: lu16,
d: lu16,
e: lu16,
};
pub const HmFunctions = packed struct {
a: enum(u8) {
@"1" = 1,
@"2" = 2,
},
b: packed union {
@"1": void,
@"2": packed struct {
b: lu16,
},
},
};
pub const FlashDuration = packed struct {
a: u8,
};
pub const DefogDuration = packed struct {
a: u8,
};
pub const GiveAccessories = packed struct {
a: lu16,
b: lu16,
};
pub const CheckAccessories = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const Cmd_1d4 = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const GiveAccessories2 = packed struct {
a: lu16,
};
pub const CheckAccessories2 = packed struct {
a: lu16,
b: lu16,
};
pub const BerryPoffin = packed struct {
a: lu16,
};
pub const SetVarBTowerChs = packed struct {
a: lu16,
};
pub const BattleRoomResult = packed struct {
a: lu16,
b: lu16,
};
pub const StoreBTowerData = packed struct {
a: lu16,
b: lu16,
};
pub const CallBTowerFunctions = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const RandomTeamBTower = packed struct {
a: lu16,
b: lu16,
c: lu16,
d: lu16,
};
pub const StorePrizeNumBTower = packed struct {
a: lu16,
};
pub const StorePeopleIdBTower = packed struct {
a: lu16,
};
pub const CallBTowerWireFunction = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const StorePChosenWireBTower = packed struct {
a: lu16,
b: lu16,
};
pub const StoreRankDataWireBTower = packed struct {
a: lu16,
b: lu16,
};
pub const Cmd_1e4 = packed struct {
a: lu16,
};
pub const RandomEvent = packed struct {
a: lu16,
};
pub const CheckSinnohPokedex = packed struct {
a: lu16,
};
pub const CheckNationalPokedex = packed struct {
a: lu16,
};
pub const StoreTrophyPokemon = packed struct {
a: lu16,
};
pub const Cmd_1ef = packed struct {
a: lu16,
};
pub const Cmd_1f0 = packed struct {
a: lu16,
};
pub const CheckActFossil = packed struct {
a: lu16,
};
pub const CheckItemChosen = packed struct {
a: lu16,
b: lu16,
};
pub const CompareItemPokeFossil = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const CheckPokemonLevel = packed struct {
a: lu16,
b: lu16,
};
pub const CheckIsPokemonPoisoned = packed struct {
a: lu16,
b: lu16,
};
pub const StoreFurniture = packed struct {
a: lu16,
};
pub const CopyFurniture = packed struct {
a: lu16,
b: lu16,
};
pub const SetBCastleFunctionId = packed struct {
a: u8,
};
pub const BCastleFunctReturn = packed struct {
a: u8,
b: lu16,
c: lu16,
d: u8,
};
pub const Cmd_200 = packed struct {
a: lu16,
};
pub const CheckEffectHm = packed struct {
a: lu16,
};
pub const GreatMarshFunction = packed struct {
a: u8,
};
pub const BattlePokeColosseum = packed struct {
a: lu16,
b: lu16,
c: lu16,
d: lu16,
e: lu16,
};
pub const StorePokeColosseumLost = packed struct {
a: lu16,
};
pub const PokemonPicture = packed struct {
a: lu16,
b: lu16,
};
pub const Cmd_20a = packed struct {
a: lu16,
};
pub const SetvarMtCoronet = packed struct {
a: u8,
b: lu16,
};
pub const CheckQuicTrineCoordinates = packed struct {
a: lu16,
b: lu16,
};
pub const SetvarQuickTrainCoordinates = packed struct {
a: lu16,
b: lu16,
};
pub const MoveTrainAnm = packed struct {
a: u8,
};
pub const StorePokeNature = packed struct {
a: lu16,
b: lu16,
};
pub const CheckPokeNature = packed struct {
a: lu16,
b: lu16,
};
pub const RandomHallowes = packed struct {
a: lu16,
};
pub const Cmd_216 = packed struct {
a: lu16,
};
pub const Cmd_217 = packed struct {
a: lu16,
b: lu16,
};
pub const ChsRSPoke = packed struct {
a: lu16,
};
pub const SetSPoke = packed struct {
a: lu16,
};
pub const CheckSPoke = packed struct {
a: lu16,
};
pub const ActSwarmPoke = packed struct {
a: u8,
};
pub const Cmd_21d = packed struct {
a: enum(u16) {
@"0" = lu16.init(0).inner,
@"1" = lu16.init(1).inner,
@"2" = lu16.init(2).inner,
@"3" = lu16.init(3).inner,
@"4" = lu16.init(4).inner,
@"5" = lu16.init(5).inner,
},
b: packed union {
@"0": packed struct {
b: lu16,
c: lu16,
},
@"1": packed struct {
b: lu16,
c: lu16,
},
@"2": packed struct {
b: lu16,
c: lu16,
},
@"3": packed struct {
b: lu16,
c: lu16,
},
@"4": packed struct {
b: lu16,
},
@"5": packed struct {
b: lu16,
},
},
};
pub const CheckMoveRemember = packed struct {
a: lu16,
b: lu16,
};
pub const StorePokeRemember = packed struct {
a: lu16,
};
pub const StoreRememberMove = packed struct {
a: lu16,
};
pub const TeachMove = packed struct {
a: lu16,
b: lu16,
};
pub const CheckTeachMove = packed struct {
a: lu16,
};
pub const SetTradeId = packed struct {
a: u8,
};
pub const CheckPokemonTrade = packed struct {
a: lu16,
};
pub const TradeChosenPokemon = packed struct {
a: lu16,
};
pub const CheckNatPokedexStatus = packed struct {
a: u8,
b: lu16,
};
pub const CheckRibbonNumber = packed struct {
a: lu16,
};
pub const CheckRibbon = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const GiveRibbon = packed struct {
a: lu16,
b: lu16,
};
pub const SetvarRibbon = packed struct {
a: u8,
b: lu16,
};
pub const CheckHappyRibbon = packed struct {
a: lu16,
b: lu16,
};
pub const CheckPokemart = packed struct {
a: lu16,
};
pub const CheckFurniture = packed struct {
a: enum(u16) {
@"0" = lu16.init(0).inner,
@"1" = lu16.init(1).inner,
@"2" = lu16.init(2).inner,
@"3" = lu16.init(3).inner,
@"4" = lu16.init(4).inner,
@"5" = lu16.init(5).inner,
@"6" = lu16.init(6).inner,
},
b: packed union {
@"0": packed struct {
b: lu16,
},
@"1": packed struct {
b: lu16,
c: lu16,
d: lu16,
},
@"2": void,
@"3": packed struct {
b: lu16,
c: lu16,
d: lu16,
},
@"4": packed struct {
b: lu16,
c: lu16,
},
@"5": packed struct {
b: lu16,
c: lu16,
d: lu16,
},
@"6": packed struct {
b: lu16,
},
},
};
pub const Cmd_236 = packed struct {
a: lu16,
};
pub const CheckPhraseBoxInput = packed struct {
a: lu16,
b: lu16,
c: lu16,
d: lu16,
};
pub const CheckStatusPhraseBox = packed struct {
a: lu16,
b: lu16,
};
pub const DecideRules = packed struct {
a: lu16,
};
pub const CheckFootStep = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const HealPokemonAnimation = packed struct {
a: lu16,
};
pub const StoreElevatorDirection = packed struct {
a: lu16,
b: lu16,
};
pub const ShipAnimation = packed struct {
a: u8,
b: u8,
c: lu16,
d: lu16,
e: lu16,
};
pub const Cmd_23e = packed struct {
a: enum(u16) {
@"1" = lu16.init(1).inner,
@"2" = lu16.init(2).inner,
@"3" = lu16.init(3).inner,
@"5" = lu16.init(5).inner,
@"6" = lu16.init(6).inner,
},
b: packed union {
@"1": packed struct {
b: lu16,
},
@"2": packed struct {
b: lu16,
},
@"3": packed struct {
b: lu16,
},
@"5": packed struct {
b: lu16,
c: lu16,
},
@"6": packed struct {
b: lu16,
c: lu16,
},
},
};
pub const StorePhraseBox1W = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const StorePhraseBox2W = packed struct {
a: lu16,
b: lu16,
c: lu16,
d: lu16,
};
pub const SetvarPhraseBox1W = packed struct {
a: lu16,
b: lu16,
};
pub const StoreMtCoronet = packed struct {
a: lu16,
};
pub const CheckFirstPokeParty = packed struct {
a: lu16,
};
pub const CheckPokeType = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const CheckPhraseBoxInput2 = packed struct {
a: lu16,
b: lu16,
c: lu16,
d: lu16,
e: lu16,
};
pub const StoreUndTime = packed struct {
a: lu16,
};
pub const PreparePcAnimation = packed struct {
a: u8,
};
pub const OpenPcAnimation = packed struct {
a: u8,
};
pub const ClosePcAnimation = packed struct {
a: u8,
};
pub const CheckLottoNumber = packed struct {
a: lu16,
};
pub const CompareLottoNumber = packed struct {
a: lu16,
b: lu16,
c: lu16,
d: lu16,
};
pub const SetvarIdPokeBoxes = packed struct {
a: u8,
b: lu16,
};
pub const CheckBoxesNumber = packed struct {
a: lu16,
};
pub const StopGreatMarsh = packed struct {
a: lu16,
};
pub const CheckPokeCatchingShow = packed struct {
a: lu16,
};
pub const CheckCatchingShowRecords = packed struct {
a: lu16,
b: lu16,
};
pub const CheckElevLgAnm = packed struct {
a: lu16,
};
pub const CheckElevPosition = packed struct {
a: lu16,
};
pub const MainEvent = packed struct {
a: lu16,
};
pub const CheckAccessories3 = packed struct {
a: u8,
b: lu16,
};
pub const ActDeoxisFormChange = packed struct {
a: lu16,
b: lu16,
};
pub const ChangeFormDeoxis = packed struct {
a: lu16,
};
pub const CheckCoombeEvent = packed struct {
a: lu16,
};
pub const Pokecasino = packed struct {
a: lu16,
};
pub const CheckTime2 = packed struct {
a: lu16,
};
pub const RegigigasAnm = packed struct {
a: lu16,
b: lu16,
c: lu16,
d: lu16,
e: lu16,
};
pub const CresseliaAnm = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const CheckRegi = packed struct {
a: lu16,
};
pub const CheckMassage = packed struct {
a: lu16,
};
pub const UnownMessageBox = packed struct {
a: lu16,
};
pub const CheckPCatchingShow = packed struct {
a: lu16,
};
pub const ShayminAnm = packed struct {
a: lu16,
b: u8,
};
pub const ThankNameInsert = packed struct {
a: lu16,
};
pub const SetvarShaymin = packed struct {
a: u8,
};
pub const SetvarAccessories2 = packed struct {
a: u8,
b: lu16,
};
pub const Cmd_274 = packed struct {
a: lu16,
b: lu32,
};
pub const CheckRecordCasino = packed struct {
a: lu16,
};
pub const CheckCoinsCasino = packed struct {
a: lu16,
b: lu16,
};
pub const SrtRandomNum = packed struct {
a: lu16,
};
pub const CheckPokeLevel2 = packed struct {
a: lu16,
b: lu16,
};
pub const Cmd_279 = packed struct {
a: lu16,
b: lu16,
};
pub const SetvarAmityPokemon = packed struct {
a: lu16,
b: lu16,
};
pub const Cmd_27d = packed struct {
a: lu16,
b: lu16,
};
pub const CheckFirstTimeVShop = packed struct {
a: lu16,
};
pub const Cmd_27f = packed struct {
a: lu16,
};
pub const SetvarIdNumber = packed struct {
a: u8,
b: lu16,
c: u8,
d: u8,
};
pub const Cmd_281 = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const SetvarUnk = packed struct {
a: lu16,
};
pub const Cmd_283 = packed struct {
a: lu16,
b: lu16,
};
pub const CheckRuinManiac = packed struct {
a: lu16,
};
pub const CheckTurnBack = packed struct {
a: lu16,
b: lu16,
};
pub const CheckUgPeopleNum = packed struct {
a: lu16,
};
pub const CheckUgFossilNum = packed struct {
a: lu16,
};
pub const CheckUgTrapsNum = packed struct {
a: lu16,
};
pub const CheckPoffinItem = packed struct {
a: lu16,
b: lu16,
c: lu16,
d: lu16,
e: lu16,
f: lu16,
g: lu16,
};
pub const CheckPoffinCaseStatus = packed struct {
a: lu16,
};
pub const UnkFunct2 = packed struct {
a: u8,
b: lu16,
};
pub const PokemonPartyPicture = packed struct {
a: lu16,
};
pub const SetSoundLearning = packed struct {
a: lu16,
};
pub const CheckFirstTimeChampion = packed struct {
a: lu16,
};
pub const ChoosePokeDCare = packed struct {
a: lu16,
};
pub const StorePokeDCare = packed struct {
a: lu16,
b: lu16,
};
pub const Cmd_292 = packed struct {
a: u8,
b: lu16,
};
pub const CheckMasterRank = packed struct {
a: lu16,
};
pub const ShowBattlePointsBox = packed struct {
a: u8,
b: u8,
};
pub const TakeBPoints = packed struct {
a: lu16,
};
pub const CheckBPoints = packed struct {
a: lu16,
b: lu16,
};
pub const Cmd_29c = packed struct {
a: lu16,
b: lu16,
};
pub const ChoiceMulti = packed struct {
a: lu16,
b: lu16,
};
pub const HMEffect = packed struct {
a: lu16,
b: lu16,
};
pub const CameraBumpEffect = packed struct {
a: lu16,
};
pub const DoubleBattle = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const ApplyMovement2 = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const Cmd_2a2 = packed struct {
a: lu16,
};
pub const StoreActHeroFriendCode = packed struct {
a: lu16,
};
pub const StoreActOtherFriendCode = packed struct {
a: lu16,
};
pub const ChsPrizeCasino = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const CheckPlate = packed struct {
a: lu16,
b: lu16,
};
pub const TakeCoinsCasino = packed struct {
a: lu16,
};
pub const CheckCoinsCasino2 = packed struct {
a: lu16,
b: lu16,
};
pub const ComparePhraseBoxInput = packed struct {
a: lu16,
b: lu16,
c: lu16,
d: lu16,
e: lu16,
};
pub const StoreSealNum = packed struct {
a: lu16,
};
pub const CheckFollowBattle = packed struct {
a: lu16,
b: lu16,
};
pub const Cmd_2af = packed struct {
a: lu16,
};
pub const SetvarSealRandom = packed struct {
a: u8,
b: lu16,
};
pub const DarkraiFunction = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const Cmd_2b6 = packed struct {
a: lu16,
b: u8,
};
pub const StorePokeNumParty = packed struct {
a: lu16,
};
pub const StorePokeNickname = packed struct {
a: lu16,
};
pub const CheckBattleUnion = packed struct {
a: lu16,
};
pub const CheckWildBattle2 = packed struct {
a: lu16,
};
pub const StoreTrainerCardStar = packed struct {
a: lu16,
};
pub const Cmd_2c0 = packed struct {
a: lu16,
};
pub const Cmd_2c3 = packed struct {
a: u8,
};
pub const ShowBTowerSome = packed struct {
a: u8,
};
pub const DeleteSavesBFactory = packed struct {
a: lu16,
b: lu16,
};
pub const CheckVersionGame = packed struct {
a: lu16,
};
pub const ShowBArcadeRecors = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const CheckPokeParty2 = packed struct {
a: lu16,
b: lu16,
};
pub const CheckPokeCastle = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const ActTeamGalacticEvents = packed struct {
a: u8,
b: lu16,
};
pub const ChooseWirePokeBCastle = packed struct {
a: lu16,
b: lu16,
};
pub const Cmd_2d0 = packed struct {
a: lu16,
b: lu16,
};
pub const Cmd_2d1 = packed struct {
a: lu16,
};
pub const Cmd_2d2 = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const Cmd_2d3 = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const Cmd_2d4 = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const Cmd_2d5 = packed struct {
a: lu16,
};
pub const Cmd_2d7 = packed struct {
a: lu16,
};
pub const Cmd_2d8 = packed struct {
a: u8,
};
pub const Cmd_2d9 = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const Cmd_2da = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const Cmd_2db = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const Cmd_2dc = packed struct {
a: lu16,
};
pub const Cmd_2dd = packed struct {
a: lu16,
b: lu16,
};
pub const Cmd_2de = packed struct {
a: lu16,
b: lu16,
c: lu16,
d: lu16,
e: lu16,
};
pub const Cmd_2df = packed struct {
a: lu16,
};
pub const Cmd_2e0 = packed struct {
a: lu16,
b: lu16,
};
pub const Cmd_2e1 = packed struct {
a: lu16,
b: lu16,
};
pub const Cmd_2e4 = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const Cmd_2e5 = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const Cmd_2e6 = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const Cmd_2e7 = packed struct {
a: lu16,
b: lu16,
};
pub const Cmd_2e8 = packed struct {
a: lu16,
};
pub const Cmd_2e9 = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const Cmd_2ea = packed struct {
a: lu16,
b: lu16,
};
pub const Cmd_2eb = packed struct {
a: lu16,
};
pub const Cmd_2ec = packed struct {
a: u8,
b: u8,
c: lu16,
d: lu16,
};
pub const Cmd_2ee = packed struct {
a: lu16,
b: lu16,
c: lu16,
d: lu16,
};
pub const Cmd_2f3 = packed struct {
a: u8,
b: lu16,
};
pub const Cmd_2f4 = packed struct {
a: lu16,
b: lu16,
c: lu16,
d: lu16,
};
pub const Cmd_2f5 = packed struct {
a: u8,
b: lu32,
c: u8,
d: u8,
};
pub const Cmd_2f6 = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const Cmd_2f7 = packed struct {
a: lu16,
};
pub const Cmd_2f9 = packed struct {
a: lu16,
};
pub const Cmd_2fa = packed struct {
a: lu16,
};
pub const Cmd_2fc = packed struct {
a: lu16,
};
pub const Cmd_2fd = packed struct {
a: u8,
b: lu16,
};
pub const Cmd_2fe = packed struct {
a: lu16,
b: lu16,
};
pub const Cmd_2ff = packed struct {
a: lu16,
b: lu16,
};
pub const Cmd_302 = packed struct {
a: lu16,
b: lu16,
c: lu16,
d: lu16,
e: lu16,
};
pub const Cmd_303 = packed struct {
a: lu16,
b: lu16,
};
pub const Cmd_304 = packed struct {
a: lu16,
b: lu16,
c: lu16,
d: lu16,
};
pub const Cmd_305 = packed struct {
a: lu16,
b: lu16,
};
pub const Cmd_306 = packed struct {
a: lu16,
b: lu16,
};
pub const Cmd_307 = packed struct {
a: lu16,
};
pub const Cmd_308 = packed struct {
a: lu16,
b: lu16,
};
pub const Cmd_30a = packed struct {
a: lu16,
};
pub const Cmd_30d = packed struct {
a: lu16,
};
pub const Cmd_30e = packed struct {
a: lu16,
};
pub const Cmd_30f = packed struct {
a: lu16,
b: lu16,
};
pub const Cmd_311 = packed struct {
a: lu16,
};
pub const Cmd_312 = packed struct {
a: lu16,
};
pub const Cmd_313 = packed struct {
a: lu16,
};
pub const Cmd_314 = packed struct {
a: lu16,
};
pub const Cmd_315 = packed struct {
a: lu16,
};
pub const Cmd_317 = packed struct {
a: lu16,
b: lu16,
c: lu16,
};
pub const Cmd_319 = packed struct {
a: lu16,
b: lu16,
};
pub const Cmd_31a = packed struct {
a: lu16,
};
pub const Cmd_31b = packed struct {
a: lu16,
};
pub const Cmd_31c = packed struct {
a: lu16,
b: lu16,
};
pub const Cmd_31d = packed struct {
a: lu16,
};
pub const Cmd_31e = packed struct {
a: lu16,
b: lu16,
};
pub const Cmd_321 = packed struct {
a: lu16,
};
pub const Cmd_323 = packed struct {
a: lu16,
};
pub const Cmd_324 = packed struct {
a: u8,
b: u8,
c: u8,
d: u8,
e: lu16,
f: lu16,
};
pub const Cmd_325 = packed struct {
a: lu16,
};
pub const Cmd_326 = packed struct {
a: lu16,
};
pub const Cmd_327 = packed struct {
a: lu16,
};
pub const PortalEffect = packed struct {
a: lu16,
};
pub const Cmd_329 = packed struct {
a: lu16,
b: lu16,
c: lu16,
d: lu16,
};
pub const Cmd_32a = packed struct {
a: lu16,
};
pub const Cmd_32b = packed struct {
a: lu16,
};
pub const Cmd_32c = packed struct {
a: lu16,
b: lu16,
c: lu16,
d: lu16,
};
pub const Cmd_32f = packed struct {
a: lu16,
b: lu16,
};
pub const Cmd_333 = packed struct {
a: lu16,
};
pub const Cmd_334 = packed struct {
a: lu16,
b: lu16,
};
pub const Cmd_335 = packed struct {
a: lu16,
b: lu32,
};
pub const Cmd_336 = packed struct {
a: lu16,
};
pub const Cmd_337 = packed struct {
a: lu16,
b: lu16,
};
pub const Cmd_33a = packed struct {
a: u8,
};
pub const Cmd_33c = packed struct {
a: u8,
b: lu16,
};
pub const Cmd_33d = packed struct {
a: u8,
b: lu16,
};
pub const Cmd_33e = packed struct {
a: u8,
b: lu16,
};
pub const Cmd_33f = packed struct {
a: u8,
b: lu16,
};
pub const Cmd_340 = packed struct {
a: u8,
b: lu16,
};
pub const Cmd_341 = packed struct {
a: lu16,
b: lu16,
};
pub const Cmd_342 = packed struct {
a: u8,
};
pub const Cmd_343 = packed struct {
a: u8,
b: lu16,
};
pub const Cmd_344 = packed struct {
a: u8,
b: lu16,
};
pub const Cmd_345 = packed struct {
a: u8,
b: lu16,
};
pub const Cmd_346 = packed struct {
a: u8,
};
pub const DisplayFloor = packed struct {
a: u8,
b: u8,
};
}; | src/core/gen4/script.zig |
pub const raw = @cImport({
@cInclude("tinyfx.h");
});
const std = @import("std");
pub const Debug = struct {
pub const print = raw.tfx_debug_print;
pub const blit_rgba = raw.tfx_debug_blit_rgba;
pub const blit_pal = raw.tfx_debug_blit_pal;
pub const set_palette = raw.tfx_debug_set_palette;
};
pub const UniformType = enum {
Int,
Vec4,
Mat4,
};
pub const Program = struct {
handle: raw.tfx_program,
pub inline fn create(src: []const u8, attribs: [*][]const u8, attrib_count: usize) anyerror!Program {
// alternative...
// pub inline fn create(src: []const u8, attribs: [*c][*c]const u8) anyerror!Program {
// var attribs: [*c][*c]const u8 = &[_:null]?[*:0]const u8 {
// "a_position",
// null
// };
// var handle = raw.tfx_program_len_new(src.ptr, @intCast(c_int, src.len), src.ptr, @intCast(c_int, src.len), attribs, -1)
var handle = raw.tfx_program_len_new(src.ptr, @intCast(c_int, src.len), src.ptr, @intCast(c_int, src.len), @ptrCast([*c][*c]const u8, attribs), @intCast(c_int, attrib_count));
if (handle == 0) {
return error.ShaderCompileFailure;
}
return Program{ .handle = handle };
}
};
pub const Uniform = struct {
handle: raw.tfx_uniform,
pub inline fn create(name: [:0]const u8, utype: UniformType, count: i32) Uniform {
const real_type = switch (utype) {
.Int => @intToEnum(raw.tfx_uniform_type, raw.TFX_UNIFORM_INT),
.Vec4 => @intToEnum(raw.tfx_uniform_type, raw.TFX_UNIFORM_VEC4),
.Mat4 => @intToEnum(raw.tfx_uniform_type, raw.TFX_UNIFORM_MAT4),
};
var handle = raw.tfx_uniform_new(name, real_type, @intCast(c_int, count));
return .{ .handle = handle };
}
};
pub const ComponentType = enum {
Float,
};
pub const VertexFormat = struct {
format: raw.tfx_vertex_format,
pub inline fn start() VertexFormat {
return VertexFormat{ .format = raw.tfx_vertex_format_start() };
}
pub inline fn add(self: *VertexFormat, slot: u8, count: usize, normalized: bool, component: ComponentType) void {
var real_type = switch (component) {
.Float => @intToEnum(raw.tfx_component_type, raw.TFX_TYPE_FLOAT),
};
raw.tfx_vertex_format_add(&self.format, slot, count, normalized, real_type);
}
pub inline fn end(self: *VertexFormat) void {
raw.tfx_vertex_format_end(&self.format);
}
};
pub const Buffer = raw.tfx_buffer;
pub fn TransientBuffer(t: var) type {
return struct {
ptr: [*]align(1) t,
handle: raw.tfx_transient_buffer,
pub fn create(fmt: *VertexFormat, count: u16) TransientBuffer(t) {
var tb = raw.tfx_transient_buffer_new(&fmt.format, count);
return TransientBuffer(t){
.handle = tb,
.ptr = @ptrCast([*]align(1) t, tb.data),
};
}
};
}
// var tb = tfx.TransientBuffer(f32).create(&fmt, 3);
// tb.ptr[0] = -1.0;
// tb.ptr[3] = -1.0;
// tb.ptr[4] = -1.0;
// tb.ptr[7] = -1.0;
// tb.ptr[2] = depth;
// tb.ptr[5] = depth;
// tb.ptr[8] = depth;
// tb.ptr[1] = 3.0;
// tb.ptr[6] = 3.0;
pub const ResetFlags = struct {
pub const None = raw.TFX_RESET_NONE;
pub const DebugOverlay = raw.TFX_RESET_DEBUG_OVERLAY;
pub const DebugOverlayStats = raw.TFX_RESET_DEBUG_OVERLAY_STATS;
pub const ReportGPUTimings = raw.TFX_RESET_REPORT_GPU_TIMINGS;
};
pub const State = struct {
pub const Default = raw.TFX_STATE_DEFAULT;
pub const RGBWrite = raw.TFX_STATE_RGB_WRITE;
pub const DepthWrite = raw.TFX_STATE_DEPTH_WRITE;
};
pub const TextureFlags = struct {
pub const FilterPoint = raw.TFX_TEXTURE_FILTER_POINT;
pub const FilterLinear = raw.TFX_TEXTURE_FILTER_LINEAR;
pub const CPUWritable = raw.TFX_TEXTURE_CPU_WRITABLE;
pub const GenMips = raw.TFX_TEXTURE_GEN_MIPS;
pub const ReserveMips = raw.TFX_TEXTURE_RESERVE_MIPS;
pub const Cube = raw.TFX_TEXTURE_CUBE;
pub const MSAASample = raw.TFX_TEXTURE_MSAA_SAMPLE;
pub const MSAAX2 = raw.TFX_TEXTURE_MSAA_X2;
pub const MSAAX4 = raw.TFX_TEXTURE_MSAA_X4;
pub const External = raw.TFX_TEXTURE_EXTERNAL;
};
pub const TextureFormat = struct {
pub const RGB565 = @intToEnum(raw.tfx_format, raw.TFX_FORMAT_RGB565);
pub const RGBA8 = @intToEnum(raw.tfx_format, raw.TFX_FORMAT_RGBA8);
pub const SRGB8 = @intToEnum(raw.tfx_format, raw.TFX_FORMAT_SRGB8);
pub const SRGB8_A8 = @intToEnum(raw.tfx_format, raw.TFX_FORMAT_SRGB8_A8);
pub const RGB10A2 = @intToEnum(raw.tfx_format, raw.TFX_FORMAT_RGB10A2);
pub const RG11B10F = @intToEnum(raw.tfx_format, raw.TFX_FORMAT_RG11B10F);
pub const RGB16F = @intToEnum(raw.tfx_format, raw.TFX_FORMAT_RGB16F);
pub const RGBA16F = @intToEnum(raw.tfx_format, raw.TFX_FORMAT_RGBA16F);
pub const RGB565_D16 = @intToEnum(raw.tfx_format, raw.TFX_FORMAT_RGB565_D16);
pub const RGBA8_D16 = @intToEnum(raw.tfx_format, raw.TFX_FORMAT_RGBA8_D16);
pub const RGBA8_D24 = @intToEnum(raw.tfx_format, raw.TFX_FORMAT_RGBA8_D24);
pub const R16F = @intToEnum(raw.tfx_format, raw.TFX_FORMAT_R16F);
pub const R32UI = @intToEnum(raw.tfx_format, raw.TFX_FORMAT_R32UI);
pub const R32F = @intToEnum(raw.tfx_format, raw.TFX_FORMAT_R32F);
pub const RG16F = @intToEnum(raw.tfx_format, raw.TFX_FORMAT_RG16F);
pub const RG32F = @intToEnum(raw.tfx_format, raw.TFX_FORMAT_RG32F);
pub const D16 = @intToEnum(raw.tfx_format, raw.TFX_FORMAT_D16);
pub const D24 = @intToEnum(raw.tfx_format, raw.TFX_FORMAT_D24);
pub const D32 = @intToEnum(raw.tfx_format, raw.TFX_FORMAT_D32);
pub const D32F = @intToEnum(raw.tfx_format, raw.TFX_FORMAT_D32F);
};
pub const PlatformData = struct {
pub inline fn create(gl_version: c_int, gl_get_proc_address: var) raw.tfx_platform_data {
var pd = std.mem.zeroes(raw.tfx_platform_data);
pd.context_version = gl_version;
pd.gl_get_proc_address = gl_get_proc_address;
return pd;
}
};
pub const ViewFlags = struct {
pub const None = raw.TFX_VIEW_NONE;
pub const Invalidate = raw.TFX_VIEW_INVALIDATE;
pub const Flush = raw.TFX_VIEW_FLUSH;
pub const SortSequential = raw.TFX_VIEW_SORT_SEQUENTIAL;
pub const Default = raw.TFX_VIEW_DEFAULT;
};
pub const View = struct {
id: u8,
pub inline fn setName(self: *const View, name: [:0]const u8) void {
raw.tfx_view_set_name(self.id, name);
}
pub inline fn setFlags(self: *const View, flags: c_int) void {
raw.tfx_view_set_flags(self.id, @intToEnum(raw.tfx_view_flags, flags));
}
pub inline fn setClearColor(self: *const View, color: u32) void {
raw.tfx_view_set_clear_color(self.id, color);
}
pub inline fn setClearDepth(self: *const View, depth: f32) void {
raw.tfx_view_set_clear_depth(self.id, depth);
}
pub inline fn setCanvas(self: *const View, canvas: *raw.tfx_canvas, layer: i32) void {
raw.tfx_view_set_canvas(self.id, canvas, @intCast(c_int, layer));
}
pub inline fn setViewports(self: *const View, count: usize, viewports: [*][*]u16) void {
raw.tfx_view_set_viewports(self.id, @intCast(c_int, count), @ptrCast([*]?[*]u16, viewports));
}
};
pub inline fn setPlatformData(pd: raw.tfx_platform_data) void {
raw.tfx_set_platform_data(pd);
}
pub inline fn reset(w: u32, h: u32, flags: c_int) void {
raw.tfx_reset(@intCast(u16, w), @intCast(u16, h), @intToEnum(raw.tfx_reset_flags, flags));
}
pub const shutdown = raw.tfx_shutdown;
pub const setBuffer = raw.tfx_set_buffer;
pub inline fn setTransientBuffer(tb: var) void {
raw.tfx_set_transient_buffer(tb.handle);
}
pub inline fn setTexture(uniform: *Uniform, tex: *raw.tfx_texture, slot: u8) void {
raw.tfx_set_texture(&uniform.handle, tex, slot);
}
pub const setState = raw.tfx_set_state;
pub const setCallback = raw.tfx_set_callback;
pub inline fn setUniform(uniform: *Uniform, data: [*]f32, count: i32) void {
raw.tfx_set_uniform(&uniform.handle, data, @intCast(c_int, count));
}
pub inline fn submit(view: View, program: Program, retain: bool) void {
return raw.tfx_submit(view.id, program.handle, retain);
}
pub inline fn touch(view: View) void {
return raw.tfx_touch(view.id);
}
pub inline fn getView(viewid: u8) View {
return .{ .id = viewid };
}
pub inline fn frame() raw.tfx_stats {
return raw.tfx_frame();
} | tfx.zig |
const std = @import("std");
const mem = std.mem;
const math = std.math;
const ArrayList = std.ArrayList;
pub const MAX_PAGES = 64 * 1024;
pub const PAGE_SIZE = 64 * 1024;
pub const Memory = struct {
alloc: *mem.Allocator,
min: u32,
max: ?u32 = null,
data: ArrayList([PAGE_SIZE]u8),
pub fn init(alloc: *mem.Allocator, min: u32, max: ?u32) Memory {
return Memory{
.alloc = alloc,
.data = ArrayList([PAGE_SIZE]u8).init(alloc),
.min = min,
.max = max,
};
}
// TODO: is usize correct here?
pub fn size(self: *Memory) usize {
return self.data.items.len;
}
pub fn grow(self: *Memory, num_pages: u32) !usize {
if (self.data.items.len + num_pages > math.min(self.max orelse MAX_PAGES, MAX_PAGES)) return error.OutOfBoundsMemoryAccess;
const old_size = self.data.items.len;
_ = try self.data.resize(self.data.items.len + num_pages);
mem.set(u8, self.asSlice()[PAGE_SIZE * old_size .. PAGE_SIZE * (old_size + num_pages)], 0);
return old_size;
}
pub fn copy(self: *Memory, address: u32, data: []const u8) !void {
if (address + data.len > PAGE_SIZE * self.data.items.len) return error.OutOfBoundsMemoryAccess;
mem.copy(u8, self.asSlice()[address .. address + data.len], data);
}
// as per copy but don't actually mutate
pub fn check(self: *Memory, address: u32, data: []const u8) !void {
if (address + data.len > PAGE_SIZE * self.data.items.len) return error.OutOfBoundsMemoryAccess;
}
pub fn read(self: *Memory, comptime T: type, offset: u32, address: u32) !T {
const effective_address = @as(u33, offset) + @as(u33, address);
if (effective_address + @sizeOf(T) - 1 >= PAGE_SIZE * self.data.items.len) return error.OutOfBoundsMemoryAccess;
const page = effective_address / PAGE_SIZE;
const page_offset = effective_address % PAGE_SIZE;
switch (T) {
u8,
u16,
u32,
u64,
i8,
i16,
i32,
i64,
=> return mem.readInt(T, @ptrCast(*const [@sizeOf(T)]u8, &self.data.items[page][page_offset]), .Little),
f32 => {
const x = mem.readInt(u32, @ptrCast(*const [@sizeOf(T)]u8, &self.data.items[page][page_offset]), .Little);
return @bitCast(f32, x);
},
f64 => {
const x = mem.readInt(u64, @ptrCast(*const [@sizeOf(T)]u8, &self.data.items[page][page_offset]), .Little);
return @bitCast(f64, x);
},
else => @compileError("Memory.read unsupported type (not int/float): " ++ @typeName(T)),
}
}
pub fn write(self: *Memory, comptime T: type, offset: u32, address: u32, value: T) !void {
const effective_address = @as(u33, offset) + @as(u33, address);
if (effective_address + @sizeOf(T) - 1 >= PAGE_SIZE * self.data.items.len) return error.OutOfBoundsMemoryAccess;
const page = effective_address / PAGE_SIZE;
const page_offset = effective_address % PAGE_SIZE;
switch (T) {
u8,
u16,
u32,
u64,
i8,
i16,
i32,
i64,
=> std.mem.writeInt(T, @ptrCast(*[@sizeOf(T)]u8, &self.data.items[page][page_offset]), value, .Little),
f32 => {
const x = @bitCast(u32, value);
std.mem.writeInt(u32, @ptrCast(*[@sizeOf(u32)]u8, &self.data.items[page][page_offset]), x, .Little);
},
f64 => {
const x = @bitCast(u64, value);
std.mem.writeInt(u64, @ptrCast(*[@sizeOf(u64)]u8, &self.data.items[page][page_offset]), x, .Little);
},
else => @compileError("Memory.read unsupported type (not int/float): " ++ @typeName(T)),
}
}
pub fn asSlice(self: *Memory) []u8 {
var slice: []u8 = undefined;
slice.ptr = if (self.data.items.len > 0) @ptrCast([*]u8, &self.data.items[0][0]) else undefined;
slice.len = PAGE_SIZE * self.data.items.len;
return slice;
}
};
const testing = std.testing;
test "Memory test" {
const ArrayListStore = @import("store.zig").ArrayListStore;
const ArenaAllocator = std.heap.ArenaAllocator;
var arena = ArenaAllocator.init(testing.allocator);
defer _ = arena.deinit();
var store = ArrayListStore.init(&arena.allocator);
const mem_handle = try store.addMemory(0, null);
var mem0 = try store.memory(mem_handle);
try testing.expectEqual(@as(usize, 0), mem0.asSlice().len);
_ = try mem0.grow(1);
try testing.expectEqual(@as(usize, 1 * PAGE_SIZE), mem0.asSlice().len);
try testing.expectEqual(@as(usize, 1), mem0.size());
try testing.expectEqual(@as(u8, 0x00), try mem0.read(u8, 0, 0));
try testing.expectEqual(@as(u32, 0x00000000), try mem0.read(u32, 0, 0));
try mem0.write(u8, 0, 0, 15);
try testing.expectEqual(@as(u8, 15), try mem0.read(u8, 0, 0));
try testing.expectEqual(@as(u32, 0x0000000F), try mem0.read(u32, 0, 0));
try mem0.write(u8, 0, 0xFFFF, 42);
try testing.expectEqual(@as(u8, 42), try mem0.read(u8, 0, 0xFFFF));
try testing.expectError(error.OutOfBoundsMemoryAccess, mem0.read(u16, 0, 0xFFFF));
try testing.expectError(error.OutOfBoundsMemoryAccess, mem0.read(u8, 0, 0xFFFF + 1));
_ = try mem0.grow(1);
try testing.expectEqual(@as(usize, 2 * PAGE_SIZE), mem0.asSlice().len);
try testing.expectEqual(@as(usize, 2), mem0.size());
try testing.expectEqual(@as(u8, 0x00), try mem0.read(u8, 0, 0xFFFF + 1));
// Write across page boundary
try mem0.write(u16, 0, 0xFFFF, 0xDEAD);
try testing.expectEqual(@as(u8, 0xAD), try mem0.read(u8, 0, 0xFFFF));
try testing.expectEqual(@as(u8, 0xDE), try mem0.read(u8, 0, 0xFFFF + 1));
try testing.expectEqual(@as(u16, 0xDEAD), try mem0.read(u16, 0, 0xFFFF));
const slice = mem0.asSlice();
try testing.expectEqual(@as(u8, 0xAD), slice[0xFFFF]);
try testing.expectEqual(@as(u8, 0xDE), slice[0xFFFF + 1]);
try testing.expectEqual(@as(u8, 0x00), try mem0.read(u8, 0, 0x1FFFF));
try testing.expectError(error.OutOfBoundsMemoryAccess, mem0.read(u8, 0, 0x1FFFF + 1));
mem0.max = 2;
try testing.expectError(error.OutOfBoundsMemoryAccess, mem0.grow(1));
mem0.max = null;
_ = try mem0.grow(1);
try testing.expectEqual(@as(usize, 3), mem0.size());
try testing.expectEqual(@as(usize, 3 * PAGE_SIZE), mem0.asSlice().len);
} | src/memory.zig |
const RESOURCE_STATES = @import("d3d12.zig").RESOURCE_STATES;
const windows = @import("windows.zig");
const d3d = @import("d3dcommon.zig");
const d3d11 = @import("d3d11.zig");
const IUnknown = windows.IUnknown;
const UINT = windows.UINT;
const WINAPI = windows.WINAPI;
const GUID = windows.GUID;
const HRESULT = windows.HRESULT;
pub const RESOURCE_FLAGS = extern struct {
BindFlags: UINT,
MiscFlags: UINT,
CPUAccessFlags: UINT,
StructureByteStride: UINT,
};
pub const IDevice = extern struct {
const Self = @This();
v: *const extern struct {
unknown: IUnknown.VTable(Self),
on12dev: VTable(Self),
},
usingnamespace IUnknown.Methods(Self);
usingnamespace Methods(Self);
pub fn Methods(comptime T: type) type {
return extern struct {
pub inline fn CreateWrappedResource(
self: *T,
resource12: *IUnknown,
flags11: *const RESOURCE_FLAGS,
in_state: RESOURCE_STATES,
out_state: RESOURCE_STATES,
guid: *const GUID,
resource11: ?*?*anyopaque,
) HRESULT {
return self.v.on12dev.CreateWrappedResource(
self,
resource12,
flags11,
in_state,
out_state,
guid,
resource11,
);
}
pub inline fn ReleaseWrappedResources(
self: *T,
resources: [*]const *d3d11.IResource,
num_resources: UINT,
) void {
self.v.on12dev.ReleaseWrappedResources(self, resources, num_resources);
}
pub inline fn AcquireWrappedResources(
self: *T,
resources: [*]const *d3d11.IResource,
num_resources: UINT,
) void {
self.v.on12dev.AcquireWrappedResources(self, resources, num_resources);
}
};
}
pub fn VTable(comptime T: type) type {
return extern struct {
CreateWrappedResource: fn (
*T,
*IUnknown,
*const RESOURCE_FLAGS,
RESOURCE_STATES,
RESOURCE_STATES,
*const GUID,
?*?*anyopaque,
) callconv(WINAPI) HRESULT,
ReleaseWrappedResources: fn (*T, [*]const *d3d11.IResource, UINT) callconv(WINAPI) void,
AcquireWrappedResources: fn (*T, [*]const *d3d11.IResource, UINT) callconv(WINAPI) void,
};
}
};
pub const IDevice1 = extern struct {
const Self = @This();
v: *const extern struct {
unknown: IUnknown.VTable(Self),
on12dev: IDevice.VTable(Self),
on12dev1: VTable(Self),
},
usingnamespace IUnknown.Methods(Self);
usingnamespace IDevice.Methods(Self);
usingnamespace Methods(Self);
pub fn Methods(comptime T: type) type {
_ = T;
return extern struct {};
}
pub fn VTable(comptime T: type) type {
_ = T;
return extern struct {
GetD3D12Device: *anyopaque,
};
}
};
pub const IDevice2 = extern struct {
const Self = @This();
v: *const extern struct {
unknown: IUnknown.VTable(Self),
on12dev: IDevice.VTable(Self),
on12dev1: IDevice1.VTable(Self),
on12dev2: VTable(Self),
},
usingnamespace IUnknown.Methods(Self);
usingnamespace IDevice.Methods(Self);
usingnamespace IDevice1.Methods(Self);
usingnamespace Methods(Self);
pub fn Methods(comptime T: type) type {
_ = T;
return extern struct {};
}
pub fn VTable(comptime T: type) type {
_ = T;
return extern struct {
UnwrapUnderlyingResource: *anyopaque,
ReturnUnderlyingResource: *anyopaque,
};
}
};
pub const IID_IDevice2 = GUID{
.Data1 = 0xdc90f331,
.Data2 = 0x4740,
.Data3 = 0x43fa,
.Data4 = .{ 0x86, 0x6e, 0x67, 0xf1, 0x2c, 0xb5, 0x82, 0x23 },
};
pub extern "d3d11" fn D3D11On12CreateDevice(
device12: *IUnknown,
flags11: d3d11.CREATE_DEVICE_FLAG,
feature_levels: ?[*]const d3d.FEATURE_LEVEL,
num_feature_levels: UINT,
cmd_queues: [*]const *IUnknown,
num_cmd_queues: UINT,
node_mask: UINT,
device11: ?*?*d3d11.IDevice,
device_ctx11: ?*?*d3d11.IDeviceContext,
?*d3d.FEATURE_LEVEL,
) callconv(WINAPI) HRESULT; | modules/platform/vendored/zwin32/src/d3d11on12.zig |
const std = @import("std");
const stdx = @import("stdx.zig");
const t = stdx.testing;
const log = stdx.log.scoped(.closure);
pub fn Closure(comptime Capture: type, comptime Fn: type) type {
stdx.meta.assertFunctionType(Fn);
// The compiler crashes when a created @Type is not used. Declaring a dummy var somehow makes the compiler aware of it.
var dummy: stdx.meta.FnParamsTuple(Fn) = undefined;
_ = dummy;
return struct {
const Self = @This();
capture: *Capture,
user_fn: stdx.meta.FnWithPrefixParam(Fn, Capture),
pub fn init(alloc: std.mem.Allocator, capture: Capture, user_fn: stdx.meta.FnWithPrefixParam(Fn, Capture)) Self {
if (@sizeOf(Capture) == 0) {
return .{
.capture = undefined,
.user_fn = user_fn,
};
} else {
const dupe = alloc.create(Capture) catch unreachable;
dupe.* = capture;
return .{
.capture = dupe,
.user_fn = user_fn,
};
}
}
pub fn iface(self: Self) ClosureIface(Fn) {
return ClosureIface(Fn).init(self);
}
pub fn call(self: *Self, args: stdx.meta.FnParamsTuple(Fn)) stdx.meta.FnReturn(Fn) {
if (@sizeOf(Capture) == 0) {
// *void
return @call(.{}, self.user_fn, .{{}} ++ args);
} else {
return @call(.{}, self.user_fn, .{self.capture.*} ++ args);
}
}
pub fn deinit(self: Self, alloc: std.mem.Allocator) void {
if (@sizeOf(Capture) > 0) {
alloc.destroy(self.capture);
}
}
};
}
test "Closure" {
// No params.
const S = struct {
fn foo(ctx: u32) void {
_ = ctx;
}
};
var c = Closure(u32, fn () void).init(t.alloc, 20, S.foo);
defer c.deinit(t.alloc);
c.call(.{});
}
pub fn ClosureIface(comptime Fn: type) type {
stdx.meta.assertFunctionType(Fn);
// The compiler crashes when a created @Type is not used. Declaring a dummy var somehow makes the compiler aware of it.
var dummy: stdx.meta.FnParamsTuple(Fn) = undefined;
_ = dummy;
return struct {
const Self = @This();
capture_ptr: *anyopaque,
call_fn: fn (user_fn: *const anyopaque, capture: *anyopaque, stdx.meta.FnParamsTuple(Fn)) stdx.meta.FnReturn(Fn),
deinit_fn: fn (std.mem.Allocator, *anyopaque) void,
// Also useful for equality comparison.
user_fn: *const anyopaque,
pub fn init(closure: anytype) Self {
const CapturePtr = @TypeOf(closure.capture);
const UserFn = @TypeOf(closure.user_fn);
const gen = struct {
fn call(user_fn_ptr: *const anyopaque, ptr: *anyopaque, args: stdx.meta.FnParamsTuple(Fn)) stdx.meta.FnReturn(Fn) {
const user_fn = @ptrCast(UserFn, user_fn_ptr);
if (@sizeOf(CapturePtr) == 0) {
// *void
return @call(.{}, user_fn, .{{}} ++ args);
} else {
const capture = stdx.mem.ptrCastAlign(CapturePtr, ptr);
return @call(.{}, user_fn, .{capture.*} ++ args);
}
}
fn deinit(alloc: std.mem.Allocator, ptr: *anyopaque) void {
if (@sizeOf(CapturePtr) > 0) {
// not *void
const capture = stdx.mem.ptrCastAlign(CapturePtr, ptr);
alloc.destroy(capture);
}
}
};
return .{
// Check for *void.
.capture_ptr = if (@sizeOf(CapturePtr) == 0) undefined else @ptrCast(*anyopaque, closure.capture),
.user_fn = closure.user_fn,
.call_fn = gen.call,
.deinit_fn = gen.deinit,
};
}
pub fn call(self: Self, args: stdx.meta.FnParamsTuple(Fn)) stdx.meta.FnReturn(Fn) {
return self.call_fn(self.user_fn, self.capture_ptr, args);
}
pub fn deinit(self: Self, alloc: std.mem.Allocator) void {
self.deinit_fn(alloc, self.capture_ptr);
}
};
}
test "ClosureIface" {
// No params.
const S = struct {
fn foo(ctx: u32) void {
_ = ctx;
}
};
var c = Closure(u32, fn () void).init(t.alloc, 20, S.foo).iface();
defer c.deinit(t.alloc);
c.call(.{});
}
pub fn UserClosureFn(comptime Capture: type, comptime Param: type) type {
return if (Param == void) fn (Capture) void else fn (Capture, Param) void;
}
/// Prefer Closure, keeping this in case using the FnParamsTuple method breaks.
pub fn ClosureSimple(comptime Capture: type, comptime Param: type) type {
return struct {
const Self = @This();
capture: *Capture,
user_fn: UserClosureFn(Capture, Param),
pub fn init(alloc: std.mem.Allocator, capture: Capture, user_fn: UserClosureFn(Capture, Param)) Self {
if (@sizeOf(Capture) == 0) {
return .{
.capture = undefined,
.user_fn = user_fn,
};
} else {
const dupe = alloc.create(Capture) catch unreachable;
dupe.* = capture;
return .{
.capture = dupe,
.user_fn = user_fn,
};
}
}
pub fn iface(self: Self) ClosureSimpleIface(Param) {
return ClosureSimpleIface(Param).init(self);
}
pub fn call(self: *Self, arg: Param) void {
if (@sizeOf(Capture) == 0) {
if (Param == void) {
self.user_fn({});
} else {
self.user_fn({}, arg);
}
} else {
if (Param == void) {
self.user_fn(self.capture.*);
} else {
self.user_fn(self.capture.*, arg);
}
}
}
pub fn deinit(self: Self, alloc: std.mem.Allocator) void {
if (@sizeOf(Capture) > 0) {
alloc.destroy(self.capture);
}
}
};
}
/// Prefer ClosureIface, keeping this in case using the FnParamsTuple method breaks.
pub fn ClosureSimpleIface(comptime Param: type) type {
return struct {
const Self = @This();
capture_ptr: *anyopaque,
call_fn: fn (*const anyopaque, *anyopaque, Param) void,
deinit_fn: fn (std.mem.Allocator, *anyopaque) void,
// Also useful for equality comparison.
user_fn: *const anyopaque,
pub fn init(closure: anytype) Self {
const CapturePtr = @TypeOf(closure.capture);
const UserFn = @TypeOf(closure.user_fn);
const gen = struct {
fn call(user_fn_ptr: *const anyopaque, ptr: *anyopaque, arg: Param) void {
const user_fn = @ptrCast(UserFn, user_fn_ptr);
if (@sizeOf(CapturePtr) == 0) {
// *void
if (Param == void) {
user_fn({});
} else {
user_fn({}, arg);
}
} else {
const capture = stdx.mem.ptrCastAlign(CapturePtr, ptr);
if (Param == void) {
user_fn(capture.*);
} else {
user_fn(capture.*, arg);
}
}
}
fn deinit(alloc: std.mem.Allocator, ptr: *anyopaque) void {
if (@sizeOf(CapturePtr) > 0) {
// not *void
const capture = stdx.mem.ptrCastAlign(CapturePtr, ptr);
alloc.destroy(capture);
}
}
};
return .{
// Check for *void.
.capture_ptr = if (@sizeOf(CapturePtr) == 0) undefined else @ptrCast(*anyopaque, closure.capture),
.user_fn = closure.user_fn,
.call_fn = gen.call,
.deinit_fn = gen.deinit,
};
}
pub fn call(self: Self, arg: Param) void {
self.call_fn(self.user_fn, self.capture_ptr, arg);
}
pub fn deinit(self: Self, alloc: std.mem.Allocator) void {
self.deinit_fn(alloc, self.capture_ptr);
}
};
} | stdx/closure.zig |
const std = @import("std");
const mem = std.mem;
const ascii = std.ascii;
const fs = std.fs;
const files = @import("files.zig");
const template = @import("template.zig");
const print = std.debug.print;
const assert = std.debug.assert;
const expect = std.testing.expect;
const Allocator = *std.mem.Allocator;
const File = fs.File;
const FileNotFound = File.OpenError.FileNotFound;
pub const APPNAME = "zed";
pub const FILENAME = "config.txt";
pub const ENTER = 0x0d;
pub const NEW_LINE = 0x0a;
// Errors
const GADD = "fs.getAppDataDir() error";
const OOM = "Out of memory error";
var data: []u8 = "";
var current_filename: []const u8 = undefined;
pub const Modifier = enum(u8) { control = 'C', none = ' ', };
pub const KeyCode = struct {
data: [4]u8, len: usize
};
pub const KeyCombination = struct {
modifier: Modifier,
code: KeyCode,
};
pub const Action = struct {
name: []const u8,
key: KeyCombination,
};
pub const KeyMapping = struct {
key: Key,
code: KeyCode,
};
pub const chunk = mem.page_size;
pub const templ = template.CONFIG;
pub var width: u16 = 80;
pub var height: u16 = 25;
pub inline fn ctrlKey(key: u8) u8 {
return key & 0x1f;
}
inline fn code1(char: u8) KeyCode {
return KeyCode{ .data = [4]u8{ char, 0, 0, 0, }, .len = 1};
}
test "code1" {
try expect(code1('q').data[0] == 'q');
try expect(code1('a').len == 1);
}
inline fn code2(c1: u8, c2: u8) KeyCode {
return KeyCode{ .data = [4]u8{ c1, c2, 0, 0, }, .len = 2};
}
inline fn code3(c1: u8, c2: u8, c3: u8) KeyCode {
return KeyCode{ .data = [4]u8{ c1, c2, c3, 0, }, .len = 3};
}
inline fn code4(c1: u8, c2: u8, c3: u8, c4: u8) KeyCode {
return KeyCode{ .data = [4]u8{ c1, c2, c3, c4, }, .len = 4};
}
pub var actions = [_]Action{
Action{ .name = "quit", .key = KeyCombination{ .modifier = Modifier.control, .code = code1('q')}},
Action{ .name = "save", .key = KeyCombination{ .modifier = Modifier.control, .code = code1('s')}},
Action{ .name = "newLine", .key = KeyCombination{ .modifier = Modifier.none, .code = code1(ENTER)}},
Action{ .name = "toggleConfig", .key = KeyCombination{ .modifier = Modifier.none, .code = code3(0x1b, 0x4f, 0x50)}},
};
test "actions" {
try expect(mem.eql(u8, actionOf(Builtin.quit).name, "quit"));
try expect(modifierOf(Builtin.quit) == Modifier.control);
try expect(charOf(Builtin.quit, 'x') == ctrlKey('q'));
}
pub const Builtin = enum(usize) {
quit = 0, save = 1, new_line = 2, toggle_config = 3,
};
pub var codes = [_]KeyMapping{
KeyMapping{ .key=Key.esc, .code=KeyCode{.data=[4]u8{0x1b, 0x00, 0x00, 0x00}, .len=1}},
KeyMapping{ .key=Key.f1, .code=KeyCode{.data=[4]u8{0x1b, 0x5b, 0x5b, 0x40}, .len=4}},
KeyMapping{ .key=Key.f2, .code=KeyCode{.data=[4]u8{0x1b, 0x5b, 0x5b, 0x42}, .len=4}},
KeyMapping{ .key=Key.f3, .code=KeyCode{.data=[4]u8{0x1b, 0x5b, 0x5b, 0x43}, .len=4}},
KeyMapping{ .key=Key.f4, .code=KeyCode{.data=[4]u8{0x1b, 0x5b, 0x5b, 0x44}, .len=4}},
KeyMapping{ .key=Key.f5, .code=KeyCode{.data=[4]u8{0x1b, 0x5b, 0x5b, 0x45}, .len=4}},
KeyMapping{ .key=Key.f6, .code=KeyCode{.data=[4]u8{0x1b, 0x5b, 0x5b, 0x46}, .len=4}},
KeyMapping{ .key=Key.f7, .code=KeyCode{.data=[4]u8{0x1b, 0x5b, 0x5b, 0x47}, .len=4}},
KeyMapping{ .key=Key.f8, .code=KeyCode{.data=[4]u8{0x1b, 0x5b, 0x5b, 0x48}, .len=4}},
KeyMapping{ .key=Key.f9, .code=KeyCode{.data=[4]u8{0x1b, 0x5b, 0x5b, 0x49}, .len=4}},
KeyMapping{ .key=Key.f10, .code=KeyCode{.data=[4]u8{0x1b, 0x5b, 0x5b, 0x50}, .len=4}},
KeyMapping{ .key=Key.f11, .code=KeyCode{.data=[4]u8{0x1b, 0x5b, 0x5b, 0x51}, .len=4}},
KeyMapping{ .key=Key.f12, .code=KeyCode{.data=[4]u8{0x1b, 0x5b, 0x5b, 0x52}, .len=4}},
KeyMapping{ .key=Key.enter, .code=KeyCode{.data=[4]u8{0x1b, 0x5b, 0x5b, 0x53}, .len=4}},
KeyMapping{ .key=Key.delete, .code=KeyCode{.data=[4]u8{0x1b, 0x5b, 0x5b, 0x54}, .len=4}},
KeyMapping{ .key=Key.backspace, .code=KeyCode{.data=[4]u8{0x1b, 0x5b, 0x5b, 0x55}, .len=4}},
};
pub const Key = enum(usize) {
esc=0, f1=1, f2=2, f3=3, f4=4, f5=5, f6=6, f7=7, f8=8, f9=9, f10=10, f11=11, f12=12, enter=13, delete=14, backspace=15,
};
pub fn findKey(str: []const u8) ?Key {
inline for (std.meta.fields(Key)) |entry| {
if (ascii.eqlIgnoreCase(entry.name, str)) return @field(Key, entry.name);
}
return null;
}
test "findKey" {
try expect(findKey("") == null);
try expect(findKey("F13") == null);
try expect(findKey("F1") == Key.f1);
}
pub inline fn mappingOf(k: Key) *KeyMapping {
return &codes[@enumToInt(k)];
}
pub inline fn KeyCodeOf(kc: KeyMapping) *KeyCode {
return &mappingOf(kc).code;
}
pub inline fn actionOf(bi: Builtin) *Action {
return &actions[@enumToInt(bi)];
}
pub inline fn keysOf(bi: Builtin) *KeyCombination {
return &actionOf(bi).key;
}
pub inline fn keyOf(bi: Builtin) *KeyCode {
return &keysOf(bi).code;
}
pub inline fn codeOf(bi: Builtin) *[4]u8 {
return &keysOf(bi).key.code;
}
pub inline fn lenOf(bi: Builtin) [4]u8 {
return keysOf(bi).key.len;
}
/// return char code includung modifier encoding
pub inline fn charOf(bi: Builtin, default: u8) u8 {
const keys = keysOf(bi);
if (keys.modifier == Modifier.control and keys.code.len == 1) return ctrlKey(keys.code.data[0]);
if (keys.modifier == Modifier.none and keys.code.len == 1) return keys.code.data[0];
return default;
}
pub inline fn modifierOf(bi: Builtin) Modifier {
return keysOf(bi).modifier;
}
pub fn findAction(name: []const u8) ?*Action {
for (actions) |action, i| {
if (mem.eql(u8, name, action.name)) return &actions[i];
}
return null;
}
test "actions" {
try expect(findAction("") == null);
try expect(mem.eql(u8, findAction("quit").?.name, "quit"));
try expect(mem.eql(u8, findAction("save").?.name, "save"));
try expect(mem.eql(u8, findAction("newLine").?.name, "newLine"));
try expect(mem.eql(u8, findAction("toggleConfig").?.name, "toggleConfig"));
}
pub const Section = enum(u8) {
vars = 0, key_binding = 1, key_codes = 2, actions = 3, builtin = 4,
};
pub fn findSection(str: []const u8) ?Section {
inline for (std.meta.fields(Section)) |entry| {
if (eqlSection(entry.name, str)) return @field(Section, entry.name);
}
return null;
}
test "findSection" {
try expect(findSection("") == null);
try expect(findSection("KEY BIDDING") == null);
try expect(findSection("KEY BINDING") == Section.key_binding);
try expect(findSection("KEY-BINDING") == Section.key_binding);
try expect(findSection("KEY CODES") == Section.key_codes);
try expect(findSection("ACTIONS") == Section.actions);
try expect(findSection("BUILTIN") == Section.builtin);
}
fn parseKeyBinding(str: []const u8) void {
if (str.len == 0) return;
const colon_index = mem.indexOf(u8, str, ":");
if (colon_index != null) {
var key_str = str[0..colon_index.?];
const dash_index = mem.indexOf(u8, key_str, "-");
const action_str = trim(str[colon_index.?+1..]);
var action = if(action_str.len > 0 and action_str[0] == '@') findAction(action_str[1..]) else null;
if (dash_index != null) {
const d_i = dash_index.?;
var mod = key_str[0..d_i];
if (mod.len == 1) {
const mc = mod[0];
if (mc == 'C') {
if (action != null) action.?.key.modifier = Modifier.control;
}
}
if (key_str.len > d_i) {
var key_name = key_str[d_i+1..];
if (key_name.len == 1 and action != null) {
action.?.key.code = code1(key_name[0]);
}
}
} else {
if (key_str.len == 1) {
if (action != null) {
action.?.key.modifier = Modifier.none;
action.?.key.code = code1(key_str[0]);
}
}
if (key_str.len > 1 and action != null) {
const k = findKey(key_str);
if (k != null) {
var ac = &action.?.key.code;
const mc = mappingOf(k.?).code;
ac.len = mc.len;
if (ac.len > 0) ac.data[0] = mc.data[0];
if (ac.len > 1) ac.data[1] = mc.data[1];
if (ac.len > 2) ac.data[2] = mc.data[2];
if (ac.len > 3) ac.data[3] = mc.data[3];
} else {
@panic("key not defined!");
}
}
}
}
}
test "parseKeyBinding" {
parseKeyBinding("");
try expect(modifierOf(Builtin.quit) == Modifier.control);
try expect(charOf(Builtin.quit, 'x') == ctrlKey('q'));
parseKeyBinding("C-x: @quit");
try expect(modifierOf(Builtin.quit) == Modifier.control);
try expect(charOf(Builtin.quit, 'q') == ctrlKey('x'));
parseKeyBinding("c: @quit");
try expect(modifierOf(Builtin.quit) == Modifier.none);
try expect(charOf(Builtin.quit, 'q') == 'c');
mappingOf(Key.f1).code.data[3] = 0x33;
parseKeyBinding("F1: @toggleConfig");
try expect(actionOf(Builtin.toggle_config).key.code.data[3] == 0x33);
}
fn parseCodes(str: []const u8, code: []u8) usize {
if (str.len == 0) return 0;
var size: usize = 0;
if (str.len > 1) { _ = std.fmt.hexToBytes(code[0..1], str[0..2]) catch @panic("no hex"); size += 1; }
if (str.len > 4) { _ = std.fmt.hexToBytes(code[1..2], str[3..5]) catch @panic("no hex"); size += 1; }
if (str.len > 7) { _ = std.fmt.hexToBytes(code[2..3], str[6..8]) catch @panic("no hex"); size += 1; }
if (str.len > 10) { _ = std.fmt.hexToBytes(code[3..4], str[9..11]) catch @panic("no hex"); size += 1; }
return size;
}
test "parseCodes" {
var code = [_]u8{0} ** 4;
try expect(parseCodes("", code[0..]) == 0); try expect(code[0] == 0);
try expect(parseCodes("01", code[0..]) == 1); try expect(code[0] == 0x01);
try expect(parseCodes("0f", code[0..]) == 1); try expect(code[0] == 0x0f);
try expect(parseCodes("10", code[0..]) == 1); try expect(code[0] == 0x10);
try expect(parseCodes("ff", code[0..]) == 1); try expect(code[0] == 0xff);
try expect(parseCodes("01 02", code[0..]) == 2); try expect(code[1] == 0x02);
try expect(parseCodes("0f 1f 2f", code[0..]) == 3); try expect(code[2] == 0x2f);
try expect(parseCodes("10 20 30 40", code[0..]) == 4); try expect(code[3] == 0x40);
try expect(parseCodes("ff fe fd fc", code[0..]) == 4); try expect(code[3] == 0xfc);
}
fn parseKeyCodes(str: []const u8) void {
if (str.len == 0) return;
const colon_index = mem.indexOf(u8, str, ":");
if (colon_index != null) {
var key_str = str[0..colon_index.?];
var key = if(key_str.len > 0) findKey(key_str) else null;
const code_str = trim(str[colon_index.?+1..]);
var code = [_]u8{0} ** 4;
const len = parseCodes(code_str, code[0..]);
if (len > 0 and key != null) {
var m = mappingOf(key.?);
m.code.len = len;
m.code.data[0] = code[0];
m.code.data[1] = code[1];
m.code.data[2] = code[2];
m.code.data[3] = code[3];
}
}
}
test "parseKeyCodes" {
parseKeyCodes("");
try expect(mappingOf(Key.f1) == &codes[@enumToInt(Key.f1)]);
parseKeyCodes("F1: 1b 5b 5b 42");
try expect(mappingOf(Key.f1).code.len == 4);
try expect(mappingOf(Key.f1).code.data[3] == 0x42);
}
/// Compares strings `a` and `b` case insensitively (ignore underscore of section_enum) and returns whether they are equal.
pub fn eqlSection(section_enum: []const u8, conf_title: []const u8) bool {
if (section_enum.len != conf_title.len) return false;
for (section_enum) |s_e, i| {
if (s_e != '_' and ascii.toLower(s_e) != ascii.toLower(conf_title[i])) return false;
}
return true;
}
test "eqlIgnoreCase" {
try std.testing.expect(eqlSection("a_b", "A B"));
try std.testing.expect(eqlSection("a_b", "A B"));
try std.testing.expect(!eqlSection("a_b", "A C"));
try std.testing.expect(eqlSection("HEy Ho!", "heY ho!"));
try std.testing.expect(!eqlSection("hElLo!", "hello! "));
try std.testing.expect(!eqlSection("hElLo!", "helro!"));
}
test "literalToArray" {
var result = [_]u8{0} ** 4;
const literal = "abc";
var r = literalToArray(literal, &result);
try expect(r.len == 3);
try expect(mem.eql(u8, literal, r));
}
pub fn literalToArray(comptime source: []const u8, dest: []u8) []u8 {
mem.copy(u8, dest, source);
return dest[0..source.len];
}
pub fn trim(str: []const u8) []const u8 {
return mem.trim(u8, str, " \r\n\t");
}
test "nextNewLine" {
var text = [_]u8{0} ** 255;
try expect(mem.eql(u8, nextLine(literalToArray("", &text), 0), ""));
try expect(mem.eql(u8, nextLine(literalToArray("a", &text), 0), "a"));
try expect(mem.eql(u8, nextLine(literalToArray("a\n", &text), 0), "a"));
try expect(mem.eql(u8, nextLine(literalToArray("\n", &text), 0), ""));
try expect(mem.eql(u8, nextLine(literalToArray("\na", &text), 0), "a"));
try expect(mem.eql(u8, nextLine(literalToArray("\n\na", &text), 0), ""));
try expect(mem.eql(u8, nextLine(literalToArray("###\n\n*", &text), 3), ""));
try expect(mem.eql(u8, nextLine(literalToArray("###\n\n* V", &text), 4), "* V"));
try expect(mem.eql(u8, nextLine(literalToArray("ab\n", &text), 0), "ab"));
try expect(mem.eql(u8, nextLine(literalToArray("ab\n", &text), 2), ""));
try expect(mem.eql(u8, nextLine(literalToArray("ab\nc", &text), 2), "c"));
try expect(mem.eql(u8, nextLine(literalToArray("ab\ncd", &text), 2), "cd"));
}
pub fn nextLine(text: []u8, index: usize) []u8 {
if (text.len == 0 or index >= text.len) return "";
var i = index;
if (text[i] == NEW_LINE) {
i += 1;
if (i >= text.len) return "";
}
var start = i;
while (i < text.len) : (i+=1) {
if(text[i] == NEW_LINE) {
return text[start..i];
}
}
return text[start..text.len];
}
pub fn parse(conf: []u8) void {
var i: usize = 0;
var line: []u8 = nextLine(conf, i);
var section: ?Section = null;
while(i < conf.len) {
if (line.len > 0) {
if (line[0] != '#') {
if (section == Section.key_codes) {
parseKeyCodes(line);
}
if (section == Section.key_binding) {
parseKeyBinding(line);
}
if (line[0] == '*') section = findSection(trim(line[1..]));
}
}
i += line.len + 1;
line = nextLine(conf, i);
}
}
test "parse" {
try expect(modifierOf(Builtin.save) == Modifier.control);
try expect(charOf(Builtin.save, 's') == ctrlKey('s'));
var conf = [_]u8{0} ** 255;
parse(literalToArray("", &conf));
parse(literalToArray("* KEY BINDING", &conf));
try expect(charOf(Builtin.save, 's') == ctrlKey('s'));
parse(literalToArray("* KEY BINDING\nC-w: @save", &conf));
try expect(charOf(Builtin.save, 's') == ctrlKey('w'));
parse(literalToArray("* KEY BINDING\nC-r: @save", &conf));
try expect(charOf(Builtin.save, 's') == ctrlKey('r'));
parse(literalToArray("* KEY CODES\nF1: 01 02 03 04", &conf));
try expect(mappingOf(Key.f1).code.data[0] == 0x01);
try expect(mappingOf(Key.f1).code.data[1] == 0x02);
try expect(mappingOf(Key.f1).code.data[2] == 0x03);
try expect(mappingOf(Key.f1).code.data[3] == 0x04);
parse(literalToArray("###\n\n* KEY CODES\nF1: 1b 5b 5b 41\n* KEY BINDING\nF1: @toggleConfig", &conf));
try expect(actionOf(Builtin.toggle_config).key.code.data[3] == 0x41);
try expect(mappingOf(Key.f1).code.data[3] == 0x41);
} | libs/config.zig |
const std = @import("../std.zig");
const math = std.math;
const expect = std.testing.expect;
/// Returns the logarithm of x for the provided base.
pub fn log(comptime T: type, base: T, x: T) T {
if (base == 2) {
return math.log2(x);
} else if (base == 10) {
return math.log10(x);
} else if ((@typeInfo(T) == .Float or @typeInfo(T) == .ComptimeFloat) and base == math.e) {
return math.ln(x);
}
const float_base = math.lossyCast(f64, base);
switch (@typeInfo(T)) {
.ComptimeFloat => {
return @as(comptime_float, math.ln(@as(f64, x)) / math.ln(float_base));
},
.ComptimeInt => {
return @as(comptime_int, math.floor(math.ln(@as(f64, x)) / math.ln(float_base)));
},
.Int => {
// TODO implement integer log without using float math
return @floatToInt(T, math.floor(math.ln(@intToFloat(f64, x)) / math.ln(float_base)));
},
.Float => {
switch (T) {
f32 => return @floatCast(f32, math.ln(@as(f64, x)) / math.ln(float_base)),
f64 => return math.ln(x) / math.ln(float_base),
else => @compileError("log not implemented for " ++ @typeName(T)),
}
},
else => {
@compileError("log expects integer or float, found '" ++ @typeName(T) ++ "'");
},
}
}
test "math.log integer" {
expect(log(u8, 2, 0x1) == 0);
expect(log(u8, 2, 0x2) == 1);
expect(log(i16, 2, 0x72) == 6);
expect(log(u32, 2, 0xFFFFFF) == 23);
expect(log(u64, 2, 0x7FF0123456789ABC) == 62);
}
test "math.log float" {
const epsilon = 0.000001;
expect(math.approxEqAbs(f32, log(f32, 6, 0.23947), -0.797723, epsilon));
expect(math.approxEqAbs(f32, log(f32, 89, 0.23947), -0.318432, epsilon));
expect(math.approxEqAbs(f64, log(f64, 123897, 12389216414), 1.981724596, epsilon));
}
test "math.log float_special" {
expect(log(f32, 2, 0.2301974) == math.log2(@as(f32, 0.2301974)));
expect(log(f32, 10, 0.2301974) == math.log10(@as(f32, 0.2301974)));
expect(log(f64, 2, 213.23019799993) == math.log2(@as(f64, 213.23019799993)));
expect(log(f64, 10, 213.23019799993) == math.log10(@as(f64, 213.23019799993)));
} | lib/std/math/log.zig |
const std = @import("std");
/// Makes all vector and matrix types generic against Real
fn specializeOn(comptime Real: type) type {
return struct {
/// Helper for the swizzle operator.
/// Returns the type fitting the number of swizzle elements
fn SwizzleTypeByElements(comptime i: usize) type {
return switch (i) {
1 => Real,
2 => Vec2,
3 => Vec3,
4 => Vec4,
else => @compileError("Swizzle can take up to 4 elements!"),
};
}
/// Returns a type mixin for a vector type implementing all component-wise operations.
/// Reduces the amount of duplicated code by a lot
fn VectorMixin(comptime Self: type) type {
return struct {
/// adds all components from `a` with the components of `b`.
pub fn add(a: Self, b: Self) Self {
var result: Self = undefined;
inline for (@typeInfo(Self).Struct.fields) |fld| {
@field(result, fld.name) = @field(a, fld.name) + @field(b, fld.name);
}
return result;
}
pub fn hash(self: Self) u32 {
return std.hash.Adler32.hash(&std.mem.toBytes(self));
}
pub fn hash64(self: Self) u64 {
return std.hash.Wyhash.hash(34837813, &std.mem.toBytes(self));
}
/// subtracts all components from `a` with the components of `b`.
pub fn sub(a: Self, b: Self) Self {
var result: Self = undefined;
inline for (@typeInfo(Self).Struct.fields) |fld| {
@field(result, fld.name) = @field(a, fld.name) - @field(b, fld.name);
}
return result;
}
/// multiplies all components from `a` with the components of `b`.
pub fn mul(a: Self, b: Self) Self {
var result: Self = undefined;
inline for (@typeInfo(Self).Struct.fields) |fld| {
@field(result, fld.name) = @field(a, fld.name) * @field(b, fld.name);
}
return result;
}
/// divides all components from `a` by the components of `b`.
pub fn div(a: Self, b: Self) Self {
var result: Self = undefined;
inline for (@typeInfo(Self).Struct.fields) |fld| {
@field(result, fld.name) = @field(a, fld.name) / @field(b, fld.name);
}
return result;
}
/// multiplies all components by a scalar value.
pub fn scale(a: Self, b: Real) Self {
var result: Self = undefined;
inline for (@typeInfo(Self).Struct.fields) |fld| {
@field(result, fld.name) = @field(a, fld.name) * b;
}
return result;
}
pub fn scaleDiv(a: Self, b: Real) Self {
var result: Self = undefined;
inline for (@typeInfo(Self).Struct.fields) |fld| {
@field(result, fld.name) = @field(a, fld.name) / b;
}
return result;
}
/// returns the dot product of two vectors.
/// This is the sum of products of all components.
pub fn dot(a: Self, b: Self) Real {
var result: Real = 0;
inline for (@typeInfo(Self).Struct.fields) |fld| {
result += @field(a, fld.name) * @field(b, fld.name);
}
return result;
}
pub fn distanceTo(a: Self, b: Self) Real {
return (a.sub(b).abs()).length();
}
/// returns the magnitude of the vector.
pub fn length(a: Self) Real {
return std.math.sqrt(a.length2());
}
/// returns the squared magnitude of the vector.
pub fn length2(a: Self) Real {
return Self.dot(a, a);
}
/// returns either a normalized vector (`length() = 1`) or `zero` if the vector
/// has length 0.
pub fn normalize(vec: Self) Self {
var len = vec.length();
return if (len != 0.0)
vec.scale(1.0 / vec.length())
else
Self.zero;
}
/// applies component-wise absolute values
pub fn abs(a: Self) Self {
var result: Self = undefined;
inline for (@typeInfo(Self).Struct.fields) |fld| {
@field(result, fld.name) = std.math.absFloat(@field(a, fld.name));
}
return result;
}
/// Returns a vector `mix`% between the two vectors.
/// 0 is a, 1 is b, 0.5 is between the two.
pub fn lerp(a: Self, b: Self, mix: f32) Self {
var result: Self = undefined;
inline for (@typeInfo(Self).Struct.fields) |fld| {
@field(result, fld.name) = @field(a, fld.name) + (@field(b, fld.name) - @field(a, fld.name)) * mix;
}
return result;
}
/// swizzle vector fields into a new vector type.
/// swizzle("xxx") will return a Vec3 with three times the x component.
/// swizzle will return a vector or scalar type with the same number of components as the
/// `components` string.
/// `components` may be any sequence of `x`, `y`, `z`, `w`, `0` and `1`.
/// The letters will be replaced by the corresponding component, the digits will be replaced
/// by the corresponding literal value.
///
/// Examples:
/// - `vec4(1,2,3,4).swizzle("wzyx") == vec4(4, 3, 2, 1)`
/// - `vec4(1,2,3,4).swizzle("xyx") == vec3(1,2,1)`
/// - `vec2(1,2).swizzle("xyxy") == vec4(1,2,1,2)`
/// - `vec2(3,4).swizzle("xy01") == vec4(3, 4, 0, 1)`
///
pub fn swizzle(self: Self, comptime components: []const u8) SwizzleTypeByElements(components.len) {
const T = SwizzleTypeByElements(components.len);
var result: T = undefined;
if (components.len > 1) {
const fieldorder = "xyzw";
_ = fieldorder;
inline for (components) |c, i| {
_ = c;
const slice = components[i .. i + 1];
const temp = if (comptime std.mem.eql(u8, slice, "0"))
0
else if (comptime std.mem.eql(u8, slice, "1"))
1
else
@field(self, components[i .. i + 1]);
@field(result, switch (i) {
0 => "x",
1 => "y",
2 => "z",
3 => "w",
else => @compileError("this should not happen"),
}) = temp;
}
} else if (components.len == 1) {
result = @field(self, components);
} else {
@compileError("components must at least contain a single field!");
}
return result;
}
/// returns a new vector where each component is the minimum of the components of the input vectors.
pub fn componentMin(a: Self, b: Self) Self {
var result: Self = undefined;
inline for (@typeInfo(Self).Struct.fields) |fld| {
@field(result, fld.name) = std.math.min(@field(a, fld.name), @field(b, fld.name));
}
return result;
}
/// returns a new vector where each component is the maximum of the components of the input vectors.
pub fn componentMax(a: Self, b: Self) Self {
var result: Self = undefined;
inline for (@typeInfo(Self).Struct.fields) |fld| {
@field(result, fld.name) = std.math.max(@field(a, fld.name), @field(b, fld.name));
}
return result;
}
};
}
pub const Rect = extern struct {
position: Vec2 = .{},
size: Vec2 = .{},
pub inline fn left(self: Rect) Real {
return self.position.x;
}
pub inline fn top(self: Rect) Real {
return self.position.y;
}
pub inline fn right(self: Rect) Real {
return self.position.x + self.size.x;
}
pub inline fn bottom(self: Rect) Real {
return self.position.y + self.size.y;
}
pub inline fn newVec(pos: Vec2, size: Vec2) Rect {
return new(pos.x, pos.y, size.x, size.y);
}
pub fn new(x: Real, y: Real, width: Real, height: Real) Rect {
return .{ .position = .{ .x = x, .y = y }, .size = .{ .x = width, .y = height } };
}
pub fn containsPoint(self: Rect, point: Vec2) bool {
return point.x >= self.position.x and point.y >= self.position.y and
point.x <= self.position.x + self.size.x and point.y <= self.position.y + self.size.y;
}
pub fn containsRect(self: Rect, other: Rect) bool {
return ((((self.position.x <= other.position.x) and ((other.position.x + other.size.x) <= (self.position.x + self.size.x))) and (self.position.y <= other.position.y)) and ((other.position.y + other.size.y) <= (self.position.y + self.size.y)));
}
pub fn intersectsRect(self: Rect, other: Rect) bool {
return other.position.x < self.position.x + self.size.x and
self.position.x < other.position.x + other.size.x and
other.position.y < self.position.y + self.size.y and
self.position.y < other.position.y + other.size.y;
}
pub fn moved(self: Rect, position: Vec2) Rect {
return rect(self.position.x + position.x, self.position.y + position.y, self.size.x, self.size.y);
}
pub fn inset(self: Rect, amount: Real) Rect {
return rect(self.position.x + amount, self.position.y + amount, self.size.x - (amount * 2), self.size.y - (amount * 2));
}
/// Returns how much the two rectangles intersect on each axis, if they do.
pub fn intersection(self: Rect, other: Rect) ?Vec2 {
if (self.intersectsRect(other)) {
var val: Vec2 = .{};
val.x = std.math.min(self.right(), other.right()) - std.math.max(self.left(), other.left());
val.y = std.math.min(self.bottom(), other.bottom()) - std.math.max(self.top(), other.top());
return val;
} else {
return null;
}
}
/// negative expansion moves the left/top bounds, positive moves the bottom/right bounds.
pub fn expand(self: Rect, expansion: Vec2) Rect {
var copy = self;
if (expansion.x < 0) {
copy.position.x += expansion.x;
copy.size.x -= expansion.x;
} else {
copy.position.x += expansion.x;
}
if (expansion.y < 0) {
copy.position.y += expansion.y;
copy.size.y -= expansion.y;
} else {
copy.position.y += expansion.y;
}
return copy;
}
};
/// 2-dimensional vector type.
pub const Vec2 = extern struct {
x: Real = 0,
y: Real = 0,
pub const zero = Vec2.new(0, 0);
pub const one = Vec2.new(1, 1);
pub const unitX = Vec2.new(1, 0);
pub const unitY = Vec2.new(0, 1);
usingnamespace VectorMixin(Vec2);
pub fn new(x: Real, y: Real) Vec2 {
return Vec2{
.x = x,
.y = y,
};
}
pub fn format(value: Vec2, comptime fmt: []const u8, options: std.fmt.FormatOptions, stream: anytype) !void {
_ = options;
_ = fmt;
try stream.print("vec2({d:.2}, {d:.2})", .{ value.x, value.y });
}
fn getField(vec: Vec2, comptime index: comptime_int) Real {
switch (index) {
0 => return vec.x,
1 => return vec.y,
else => @compileError("index out of bounds!"),
}
}
/// multiplies the vector with a matrix.
pub fn transform(vec: Vec2, mat: Mat2) Vec2 {
var result = zero;
inline for ([_]comptime_int{ 0, 1 }) |i| {
result.x += vec.getField(i) * mat.fields[0][i];
result.y += vec.getField(i) * mat.fields[1][i];
}
return result;
}
/// multiplies the vector with a matrix4.
pub fn transform4(vec: Vec2, mat: Mat4) Vec2 {
return Vec2.new(
// (position.X * matrix.M11) + (position.Y * matrix.M21) + matrix.M41
(vec.x * mat.fields[0][0]) + (vec.y * mat.fields[1][0]) + mat.fields[3][0],
// (position.X * matrix.M12) + (position.Y * matrix.M22) + matrix.M42
(vec.x * mat.fields[0][1]) + (vec.y * mat.fields[1][1]) + mat.fields[3][1],
);
}
/// Assumes you are rotating around the 0,0 origin.
pub fn rotate(vec: Vec2, radians: f32) Vec2 {
return vec.transform4(Mat4.createZRotation(radians));
}
};
/// 3-dimensional vector type.
pub const Vec3 = extern struct {
x: Real = 0,
y: Real = 0,
z: Real = 0,
pub const zero = Vec3.new(0, 0, 0);
pub const one = Vec3.new(1, 1, 1);
pub const unitX = Vec3.new(1, 0, 0);
pub const unitY = Vec3.new(0, 1, 0);
pub const unitZ = Vec3.new(0, 0, 1);
usingnamespace VectorMixin(Vec3);
pub fn new(x: Real, y: Real, z: Real) Vec3 {
return Vec3{
.x = x,
.y = y,
.z = z,
};
}
pub fn format(value: Vec3, comptime fmt: []const u8, options: std.fmt.FormatOptions, stream: anytype) !void {
_ = options;
_ = fmt;
try stream.print("vec3({d:.2}, {d:.2}, {d:.2})", .{ value.x, value.y, value.z });
}
/// calculates the cross product. result will be perpendicular to a and b.
pub fn cross(a: Vec3, b: Vec3) Vec3 {
return Vec3{
.x = a.y * b.z - a.z * b.y,
.y = a.z * b.x - a.x * b.z,
.z = a.x * b.y - a.y * b.x,
};
}
/// converts the vector from an homogeneous position (w=1).
pub fn toAffinePosition(a: Vec3) Vec4 {
return Vec4{
.x = a.x,
.y = a.y,
.z = a.z,
.w = 1.0,
};
}
/// converts the vector from an homogeneous direction (w=0).
pub fn toAffineDirection(a: Vec3) Vec4 {
return Vec4{
.x = a.x,
.y = a.y,
.z = a.z,
.w = 0.0,
};
}
pub fn fromAffinePosition(a: Vec4) Vec3 {
return Vec3{
.x = a.x / a.w,
.y = a.y / a.w,
.z = a.z / a.w,
};
}
pub fn fromAffineDirection(a: Vec4) Vec3 {
return Vec3{
.x = a.x,
.y = a.y,
.z = a.z,
};
}
/// multiplies the vector with a matrix.
pub fn transform(vec: Vec3, mat: Mat3) Vec3 {
var result = zero;
inline for ([_]comptime_int{ 0, 1, 2 }) |i| {
result.x += vec.getField(i) * mat.fields[0][i];
result.y += vec.getField(i) * mat.fields[1][i];
result.z += vec.getField(i) * mat.fields[2][i];
}
return result;
}
/// transforms a homogeneous position.
pub fn transformPosition(vec: Vec3, mat: Mat4) Vec3 {
return fromAffinePosition(vec.toAffinePosition().transform(mat));
}
/// transforms a homogeneous direction.
pub fn transformDirection(vec: Vec3, mat: Mat4) Vec3 {
return fromAffineDirection(vec.toAffineDirection().transform(mat));
}
fn getField(vec: Vec3, comptime index: comptime_int) Real {
switch (index) {
0 => return vec.x,
1 => return vec.y,
2 => return vec.z,
else => @compileError("index out of bounds!"),
}
}
};
/// 4-dimensional vector type.
pub const Vec4 = extern struct {
x: Real = 0,
y: Real = 0,
z: Real = 0,
w: Real = 0,
pub const zero = Vec4.new(0, 0, 0, 0);
pub const one = Vec4.new(1, 1, 1, 1);
pub const unitX = Vec4.new(1, 0, 0, 0);
pub const unitY = Vec4.new(0, 1, 0, 0);
pub const unitZ = Vec4.new(0, 0, 1, 0);
pub const unitW = Vec4.new(0, 0, 0, 1);
pub const white = Vec4.new(1, 1, 1, 1);
pub const black = Vec4.new(0, 0, 0, 1);
pub const transparent = Vec4.new(0, 0, 0, 0);
usingnamespace VectorMixin(Vec4);
pub fn new(x: Real, y: Real, z: Real, w: Real) Vec4 {
return Vec4{
.x = x,
.y = y,
.z = z,
.w = w,
};
}
pub fn format(value: Vec4, comptime fmt: []const u8, options: std.fmt.FormatOptions, stream: anytype) !void {
_ = options;
_ = fmt;
try stream.print("vec4({d:.2}, {d:.2}, {d:.2}, {d:.2})", .{ value.x, value.y, value.z, value.w });
}
/// multiplies the vector with a matrix.
pub fn transform(vec: Vec4, mat: Mat4) Vec4 {
var result = zero;
inline for ([_]comptime_int{ 0, 1, 2, 3 }) |i| {
result.x += vec.getField(i) * mat.fields[i][0];
result.y += vec.getField(i) * mat.fields[i][1];
result.z += vec.getField(i) * mat.fields[i][2];
result.w += vec.getField(i) * mat.fields[i][3];
}
return result;
}
fn getField(vec: Vec4, comptime index: comptime_int) Real {
switch (index) {
0 => return vec.x,
1 => return vec.y,
2 => return vec.z,
3 => return vec.w,
else => @compileError("index out of bounds!"),
}
}
pub fn colorFaded(vec: Vec4, newTransparency: Real) Vec4 {
return .{ .x = vec.x, .y = vec.y, .z = vec.z, .w = newTransparency };
}
/// val = 0 means unchanged, val = 1 means full white, val = -1 means full black
/// Values are clamped between 0 and 1 to maintain valid normalized color, and alpha is unchanged.
pub fn brighten(self: @This(), val: f32) @This() {
return .{ .x = std.math.clamp(self.x * (1.0 + val), 0.0, 1.0), .y = std.math.clamp(self.y * (1.0 + val), 0.0, 1.0), .z = std.math.clamp(self.z * (1.0 + val), 0.0, 1.0), .w = self.w };
}
};
/// 2 by 2 matrix type.
pub const Mat2 = extern struct {
fields: [2][2]Real, // [row][col]
/// identitiy matrix
pub const identity = Mat2{
.fields = [2]Real{
[2]Real{ 1, 0 },
[2]Real{ 0, 1 },
},
};
};
/// 3 by 3 matrix type.
pub const Mat3 = extern struct {
fields: [3][3]Real, // [row][col]
/// identitiy matrix
pub const identity = Mat3{
.fields = [3]Real{
[3]Real{ 1, 0, 0 },
[3]Real{ 0, 1, 0 },
[3]Real{ 0, 0, 1 },
},
};
};
/// 4 by 4 matrix type.
pub const Mat4 = extern struct {
fields: [4][4]Real, // [row][col]
/// zero matrix.
pub const zero = Mat4{
.fields = [4][4]Real{
[4]Real{ 0, 0, 0, 0 },
[4]Real{ 0, 0, 0, 0 },
[4]Real{ 0, 0, 0, 0 },
[4]Real{ 0, 0, 0, 0 },
},
};
/// identitiy matrix
pub const identity = Mat4{
.fields = [4][4]Real{
[4]Real{ 1, 0, 0, 0 },
[4]Real{ 0, 1, 0, 0 },
[4]Real{ 0, 0, 1, 0 },
[4]Real{ 0, 0, 0, 1 },
},
};
pub fn format(value: Mat4, comptime fmt: []const u8, options: std.fmt.FormatOptions, stream: anytype) !void {
_ = options;
_ = fmt;
try stream.writeAll("mat4{");
inline for ([_]comptime_int{ 0, 1, 2, 3 }) |i| {
const row = value.fields[i];
try stream.print(" ({d:.2} {d:.2} {d:.2} {d:.2})", .{ row[0], row[1], row[2], row[3] });
}
try stream.writeAll(" }");
}
/// performs matrix multiplication of a*b
pub fn mul(a: Mat4, b: Mat4) Mat4 {
var result: Mat4 = undefined;
inline for ([_]comptime_int{ 0, 1, 2, 3 }) |row| {
inline for ([_]comptime_int{ 0, 1, 2, 3 }) |col| {
var sum: Real = 0.0;
inline for ([_]comptime_int{ 0, 1, 2, 3 }) |i| {
sum += a.fields[row][i] * b.fields[i][col];
}
result.fields[row][col] = sum;
}
}
return result;
}
/// transposes the matrix.
/// this will swap columns with rows.
pub fn transpose(a: Mat4) Mat4 {
var result: Mat4 = undefined;
inline for ([_]comptime_int{ 0, 1, 2, 3 }) |row| {
inline for ([_]comptime_int{ 0, 1, 2, 3 }) |col| {
result.fields[row][col] = a.fields[col][row];
}
}
return result;
}
// taken from GLM implementation
/// Creates a look-at matrix.
/// The matrix will create a transformation that can be used
/// as a camera transform.
/// the camera is located at `eye` and will look into `direction`.
/// `up` is the direction from the screen center to the upper screen border.
pub fn createLook(eye: Vec3, direction: Vec3, up: Vec3) Mat4 {
const f = direction.normalize();
const s = Vec3.cross(up, f).normalize();
const u = Vec3.cross(f, s);
var result = Mat4.identity;
result.fields[0][0] = s.x;
result.fields[1][0] = s.y;
result.fields[2][0] = s.z;
result.fields[0][1] = u.x;
result.fields[1][1] = u.y;
result.fields[2][1] = u.z;
result.fields[0][2] = f.x;
result.fields[1][2] = f.y;
result.fields[2][2] = f.z;
result.fields[3][0] = -Vec3.dot(s, eye);
result.fields[3][1] = -Vec3.dot(u, eye);
result.fields[3][2] = -Vec3.dot(f, eye);
return result;
}
/// Creates a look-at matrix.
/// The matrix will create a transformation that can be used
/// as a camera transform.
/// the camera is located at `eye` and will look at `center`.
/// `up` is the direction from the screen center to the upper screen border.
pub fn createLookAt(eye: Vec3, center: Vec3, up: Vec3) Mat4 {
return createLook(eye, Vec3.sub(center, eye), up);
}
// taken from GLM implementation
/// creates a perspective transformation matrix.
/// `fov` is the field of view in radians,
/// `aspect` is the screen aspect ratio (width / height)
/// `near` is the distance of the near clip plane, whereas `far` is the distance to the far clip plane.
pub fn createPerspective(fov: Real, aspect: Real, near: Real, far: Real) Mat4 {
std.debug.assert(std.math.fabs(aspect - 0.001) > 0);
const tanHalfFovy = std.math.tan(fov / 2);
var result = Mat4.zero;
result.fields[0][0] = 1.0 / (aspect * tanHalfFovy);
result.fields[1][1] = 1.0 / (tanHalfFovy);
result.fields[2][2] = far / (far - near);
result.fields[2][3] = 1;
result.fields[3][2] = -(far * near) / (far - near);
return result;
}
/// creates a rotation matrix around a certain axis.
pub fn createAngleAxis(axis: Vec3, angle: Real) Mat4 {
var cos = std.math.cos(angle);
var sin = std.math.sin(angle);
var x = axis.x;
var y = axis.y;
var z = axis.z;
return Mat4{
.fields = [4][4]Real{
[4]Real{ cos + x * x * (1 - cos), x * y * (1 - cos) - z * sin, x * z * (1 - cos) + y * sin, 0 },
[4]Real{ y * x * (1 - cos) + z * sin, cos + y * y * (1 - cos), y * z * (1 - cos) - x * sin, 0 },
[4]Real{ z * x * (1 * cos) - y * sin, z * y * (1 - cos) + x * sin, cos + z * z * (1 - cos), 0 },
[4]Real{ 0, 0, 0, 1 },
},
};
}
pub fn createZRotation(radians: f32) Mat4 {
var result = Mat4.identity;
var val1 = @cos(radians);
var val2 = @sin(radians);
result.fields[0][0] = val1;
result.fields[0][1] = val2;
result.fields[1][0] = -val2;
result.fields[1][1] = val1;
return result;
}
/// creates matrix that will scale a homogeneous matrix.
pub fn createUniformScale(scale: Real) Mat4 {
return createScale(scale, scale, scale);
}
/// Creates a non-uniform scaling matrix
pub fn createScale(x: Real, y: Real, z: Real) Mat4 {
return Mat4{
.fields = [4][4]Real{
[4]Real{ x, 0, 0, 0 },
[4]Real{ 0, y, 0, 0 },
[4]Real{ 0, 0, z, 0 },
[4]Real{ 0, 0, 0, 1 },
},
};
}
/// creates matrix that will translate a homogeneous matrix.
pub fn createTranslationXYZ(x: Real, y: Real, z: Real) Mat4 {
return Mat4{
.fields = [4][4]Real{
[4]Real{ 1, 0, 0, 0 },
[4]Real{ 0, 1, 0, 0 },
[4]Real{ 0, 0, 1, 0 },
[4]Real{ x, y, z, 1 },
},
};
}
/// creates matrix that will scale a homogeneous matrix.
pub fn createTranslation(v: Vec3) Mat4 {
return Mat4{
.fields = [4][4]Real{
[4]Real{ 1, 0, 0, 0 },
[4]Real{ 0, 1, 0, 0 },
[4]Real{ 0, 0, 1, 0 },
[4]Real{ v.x, v.y, v.z, 1 },
},
};
}
/// creates an orthogonal projection matrix.
/// `left`, `right`, `bottom` and `top` are the borders of the screen whereas `near` and `far` define the
/// distance of the near and far clipping planes.
pub fn createOrthogonal(left: Real, right: Real, bottom: Real, top: Real, near: Real, far: Real) Mat4 {
var result = Mat4.identity;
result.fields[0][0] = 2 / (right - left);
result.fields[1][1] = 2 / (top - bottom);
result.fields[2][2] = 1 / (far - near);
result.fields[3][0] = -(right + left) / (right - left);
result.fields[3][1] = -(top + bottom) / (top - bottom);
result.fields[3][2] = -near / (far - near);
return result;
}
pub fn inlined(self: Mat4) [16]f32 {
return @bitCast([16]f32, self.fields);
}
/// Batch matrix multiplication. Will multiply all matrices from "first" to "last".
pub fn batchMul(items: []const Mat4) Mat4 {
if (items.len == 0)
return Mat4.identity;
if (items.len == 1)
return items[0];
var value = items[0];
var i: usize = 1;
while (i < items.len) : (i += 1) {
value = value.mul(items[i]);
}
return value;
}
pub fn invert(src: Mat4) ?Mat4 {
// https://github.com/stackgl/gl-mat4/blob/master/invert.js
const a = @bitCast([16]f32, src.fields);
const a00 = a[0];
const a01 = a[1];
const a02 = a[2];
const a03 = a[3];
const a10 = a[4];
const a11 = a[5];
const a12 = a[6];
const a13 = a[7];
const a20 = a[8];
const a21 = a[9];
const a22 = a[10];
const a23 = a[11];
const a30 = a[12];
const a31 = a[13];
const a32 = a[14];
const a33 = a[15];
const b00 = a00 * a11 - a01 * a10;
const b01 = a00 * a12 - a02 * a10;
const b02 = a00 * a13 - a03 * a10;
const b03 = a01 * a12 - a02 * a11;
const b04 = a01 * a13 - a03 * a11;
const b05 = a02 * a13 - a03 * a12;
const b06 = a20 * a31 - a21 * a30;
const b07 = a20 * a32 - a22 * a30;
const b08 = a20 * a33 - a23 * a30;
const b09 = a21 * a32 - a22 * a31;
const b10 = a21 * a33 - a23 * a31;
const b11 = a22 * a33 - a23 * a32;
// Calculate the determinant
var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
if (std.math.approxEqAbs(f32, det, 0, 1e-8)) {
return null;
}
det = 1.0 / det;
const out = [16]f32{
(a11 * b11 - a12 * b10 + a13 * b09) * det, // 0
(a02 * b10 - a01 * b11 - a03 * b09) * det, // 1
(a31 * b05 - a32 * b04 + a33 * b03) * det, // 2
(a22 * b04 - a21 * b05 - a23 * b03) * det, // 3
(a12 * b08 - a10 * b11 - a13 * b07) * det, // 4
(a00 * b11 - a02 * b08 + a03 * b07) * det, // 5
(a32 * b02 - a30 * b05 - a33 * b01) * det, // 6
(a20 * b05 - a22 * b02 + a23 * b01) * det, // 7
(a10 * b10 - a11 * b08 + a13 * b06) * det, // 8
(a01 * b08 - a00 * b10 - a03 * b06) * det, // 9
(a30 * b04 - a31 * b02 + a33 * b00) * det, // 10
(a21 * b02 - a20 * b04 - a23 * b00) * det, // 11
(a11 * b07 - a10 * b09 - a12 * b06) * det, // 12
(a00 * b09 - a01 * b07 + a02 * b06) * det, // 13
(a31 * b01 - a30 * b03 - a32 * b00) * det, // 14
(a20 * b03 - a21 * b01 + a22 * b00) * det, // 15
};
return Mat4{
.fields = @bitCast([4][4]f32, out),
};
}
};
/// constructs a new Vec2.
pub fn vec2(x: Real, y: Real) Vec2 {
return Vec2.new(x, y);
}
/// constructs a new Vec3.
pub fn vec3(x: Real, y: Real, z: Real) Vec3 {
return Vec3.new(x, y, z);
}
/// constructs a new Vec4.
pub fn vec4(x: Real, y: Real, z: Real, w: Real) Vec4 {
return Vec4.new(x, y, z, w);
}
/// constructs a new Rectangle.
pub fn rect(x: Real, y: Real, w: Real, h: Real) Rect {
return .{
.position = .{ .x = x, .y = y },
.size = .{ .x = w, .y = h },
};
}
};
}
/// Converts degrees to radian
pub fn toRadians(deg: anytype) @TypeOf(deg) {
return std.math.pi * deg / 180.0;
}
/// Converts radian to degree
pub fn toDegrees(rad: anytype) @TypeOf(rad) {
return 180.0 * rad / std.math.pi;
}
pub usingnamespace specializeOn(f32); | src/pkg/zlm.zig |
const std = @import("std");
const mem = std.mem;
const assert = std.debug.assert;
const ir = @import("ir.zig");
const Type = @import("type.zig").Type;
const Value = @import("value.zig").Value;
const TypedValue = @import("TypedValue.zig");
const link = @import("link.zig");
const Module = @import("Module.zig");
const ErrorMsg = Module.ErrorMsg;
const Target = std.Target;
const Allocator = mem.Allocator;
const trace = @import("tracy.zig").trace;
pub const Result = union(enum) {
/// The `code` parameter passed to `generateSymbol` has the value appended.
appended: void,
/// The value is available externally, `code` is unused.
externally_managed: []const u8,
fail: *Module.ErrorMsg,
};
pub fn generateSymbol(
bin_file: *link.ElfFile,
src: usize,
typed_value: TypedValue,
code: *std.ArrayList(u8),
) error{
OutOfMemory,
/// A Decl that this symbol depends on had a semantic analysis failure.
AnalysisFail,
}!Result {
const tracy = trace(@src());
defer tracy.end();
switch (typed_value.ty.zigTypeTag()) {
.Fn => {
const module_fn = typed_value.val.cast(Value.Payload.Function).?.func;
const fn_type = module_fn.owner_decl.typed_value.most_recent.typed_value.ty;
const param_types = try bin_file.allocator.alloc(Type, fn_type.fnParamLen());
defer bin_file.allocator.free(param_types);
fn_type.fnParamTypes(param_types);
// A parameter may be broken into multiple machine code parameters, so we don't
// know the size up front.
var mc_args = try std.ArrayList(Function.MCValue).initCapacity(bin_file.allocator, param_types.len);
defer mc_args.deinit();
var next_stack_offset: u64 = 0;
switch (fn_type.fnCallingConvention()) {
.Naked => assert(mc_args.items.len == 0),
.Unspecified, .C => {
// Prepare the function parameters
switch (bin_file.options.target.cpu.arch) {
.x86_64 => {
const integer_registers = [_]Reg(.x86_64){ .rdi, .rsi, .rdx, .rcx, .r8, .r9 };
var next_int_reg: usize = 0;
for (param_types) |param_type, src_i| {
switch (param_type.zigTypeTag()) {
.Bool, .Int => {
if (next_int_reg >= integer_registers.len) {
try mc_args.append(.{ .stack_offset = next_stack_offset });
next_stack_offset += param_type.abiSize(bin_file.options.target);
} else {
try mc_args.append(.{ .register = @enumToInt(integer_registers[next_int_reg]) });
next_int_reg += 1;
}
},
else => return Result{
.fail = try ErrorMsg.create(
bin_file.allocator,
src,
"TODO implement function parameters of type {}",
.{@tagName(param_type.zigTypeTag())},
),
},
}
}
},
else => return Result{
.fail = try ErrorMsg.create(
bin_file.allocator,
src,
"TODO implement function parameters for {}",
.{bin_file.options.target.cpu.arch},
),
},
}
},
else => return Result{
.fail = try ErrorMsg.create(
bin_file.allocator,
src,
"TODO implement {} calling convention",
.{fn_type.fnCallingConvention()},
),
},
}
var function = Function{
.target = &bin_file.options.target,
.bin_file = bin_file,
.mod_fn = module_fn,
.code = code,
.inst_table = std.AutoHashMap(*ir.Inst, Function.MCValue).init(bin_file.allocator),
.err_msg = null,
.args = mc_args.items,
};
defer function.inst_table.deinit();
function.gen() catch |err| switch (err) {
error.CodegenFail => return Result{ .fail = function.err_msg.? },
else => |e| return e,
};
if (function.err_msg) |em| {
return Result{ .fail = em };
} else {
return Result{ .appended = {} };
}
},
.Array => {
if (typed_value.val.cast(Value.Payload.Bytes)) |payload| {
if (typed_value.ty.arraySentinel()) |sentinel| {
try code.ensureCapacity(code.items.len + payload.data.len + 1);
code.appendSliceAssumeCapacity(payload.data);
const prev_len = code.items.len;
switch (try generateSymbol(bin_file, src, .{
.ty = typed_value.ty.elemType(),
.val = sentinel,
}, code)) {
.appended => return Result{ .appended = {} },
.externally_managed => |slice| {
code.appendSliceAssumeCapacity(slice);
return Result{ .appended = {} };
},
.fail => |em| return Result{ .fail = em },
}
} else {
return Result{ .externally_managed = payload.data };
}
}
return Result{
.fail = try ErrorMsg.create(
bin_file.allocator,
src,
"TODO implement generateSymbol for more kinds of arrays",
.{},
),
};
},
.Pointer => {
if (typed_value.val.cast(Value.Payload.DeclRef)) |payload| {
const decl = payload.decl;
if (decl.analysis != .complete) return error.AnalysisFail;
assert(decl.link.local_sym_index != 0);
// TODO handle the dependency of this symbol on the decl's vaddr.
// If the decl changes vaddr, then this symbol needs to get regenerated.
const vaddr = bin_file.local_symbols.items[decl.link.local_sym_index].st_value;
const endian = bin_file.options.target.cpu.arch.endian();
switch (bin_file.ptr_width) {
.p32 => {
try code.resize(4);
mem.writeInt(u32, code.items[0..4], @intCast(u32, vaddr), endian);
},
.p64 => {
try code.resize(8);
mem.writeInt(u64, code.items[0..8], vaddr, endian);
},
}
return Result{ .appended = {} };
}
return Result{
.fail = try ErrorMsg.create(
bin_file.allocator,
src,
"TODO implement generateSymbol for pointer {}",
.{typed_value.val},
),
};
},
.Int => {
const info = typed_value.ty.intInfo(bin_file.options.target);
if (info.bits == 8 and !info.signed) {
const x = typed_value.val.toUnsignedInt();
try code.append(@intCast(u8, x));
return Result{ .appended = {} };
}
return Result{
.fail = try ErrorMsg.create(
bin_file.allocator,
src,
"TODO implement generateSymbol for int type '{}'",
.{typed_value.ty},
),
};
},
else => |t| {
return Result{
.fail = try ErrorMsg.create(
bin_file.allocator,
src,
"TODO implement generateSymbol for type '{}'",
.{@tagName(t)},
),
};
},
}
}
const Function = struct {
bin_file: *link.ElfFile,
target: *const std.Target,
mod_fn: *const Module.Fn,
code: *std.ArrayList(u8),
inst_table: std.AutoHashMap(*ir.Inst, MCValue),
err_msg: ?*ErrorMsg,
args: []MCValue,
const MCValue = union(enum) {
none,
unreach,
/// A pointer-sized integer that fits in a register.
immediate: u64,
/// The constant was emitted into the code, at this offset.
embedded_in_code: usize,
/// The value is in a target-specific register. The value can
/// be @intToEnum casted to the respective Reg enum.
register: usize,
/// The value is in memory at a hard-coded address.
memory: u64,
/// The value is one of the stack variables.
stack_offset: u64,
};
fn gen(self: *Function) !void {
switch (self.target.cpu.arch) {
.arm => return self.genArch(.arm),
.armeb => return self.genArch(.armeb),
.aarch64 => return self.genArch(.aarch64),
.aarch64_be => return self.genArch(.aarch64_be),
.aarch64_32 => return self.genArch(.aarch64_32),
.arc => return self.genArch(.arc),
.avr => return self.genArch(.avr),
.bpfel => return self.genArch(.bpfel),
.bpfeb => return self.genArch(.bpfeb),
.hexagon => return self.genArch(.hexagon),
.mips => return self.genArch(.mips),
.mipsel => return self.genArch(.mipsel),
.mips64 => return self.genArch(.mips64),
.mips64el => return self.genArch(.mips64el),
.msp430 => return self.genArch(.msp430),
.powerpc => return self.genArch(.powerpc),
.powerpc64 => return self.genArch(.powerpc64),
.powerpc64le => return self.genArch(.powerpc64le),
.r600 => return self.genArch(.r600),
.amdgcn => return self.genArch(.amdgcn),
.riscv32 => return self.genArch(.riscv32),
.riscv64 => return self.genArch(.riscv64),
.sparc => return self.genArch(.sparc),
.sparcv9 => return self.genArch(.sparcv9),
.sparcel => return self.genArch(.sparcel),
.s390x => return self.genArch(.s390x),
.tce => return self.genArch(.tce),
.tcele => return self.genArch(.tcele),
.thumb => return self.genArch(.thumb),
.thumbeb => return self.genArch(.thumbeb),
.i386 => return self.genArch(.i386),
.x86_64 => return self.genArch(.x86_64),
.xcore => return self.genArch(.xcore),
.nvptx => return self.genArch(.nvptx),
.nvptx64 => return self.genArch(.nvptx64),
.le32 => return self.genArch(.le32),
.le64 => return self.genArch(.le64),
.amdil => return self.genArch(.amdil),
.amdil64 => return self.genArch(.amdil64),
.hsail => return self.genArch(.hsail),
.hsail64 => return self.genArch(.hsail64),
.spir => return self.genArch(.spir),
.spir64 => return self.genArch(.spir64),
.kalimba => return self.genArch(.kalimba),
.shave => return self.genArch(.shave),
.lanai => return self.genArch(.lanai),
.wasm32 => return self.genArch(.wasm32),
.wasm64 => return self.genArch(.wasm64),
.renderscript32 => return self.genArch(.renderscript32),
.renderscript64 => return self.genArch(.renderscript64),
.ve => return self.genArch(.ve),
}
}
fn genArch(self: *Function, comptime arch: std.Target.Cpu.Arch) !void {
for (self.mod_fn.analysis.success.instructions) |inst| {
const new_inst = try self.genFuncInst(inst, arch);
try self.inst_table.putNoClobber(inst, new_inst);
}
}
fn genFuncInst(self: *Function, inst: *ir.Inst, comptime arch: std.Target.Cpu.Arch) !MCValue {
switch (inst.tag) {
.add => return self.genAdd(inst.cast(ir.Inst.Add).?, arch),
.arg => return self.genArg(inst.cast(ir.Inst.Arg).?),
.block => return self.genBlock(inst.cast(ir.Inst.Block).?, arch),
.breakpoint => return self.genBreakpoint(inst.src, arch),
.call => return self.genCall(inst.cast(ir.Inst.Call).?, arch),
.unreach => return MCValue{ .unreach = {} },
.constant => unreachable, // excluded from function bodies
.assembly => return self.genAsm(inst.cast(ir.Inst.Assembly).?, arch),
.ptrtoint => return self.genPtrToInt(inst.cast(ir.Inst.PtrToInt).?),
.bitcast => return self.genBitCast(inst.cast(ir.Inst.BitCast).?),
.ret => return self.genRet(inst.cast(ir.Inst.Ret).?, arch),
.retvoid => return self.genRetVoid(inst.cast(ir.Inst.RetVoid).?, arch),
.cmp => return self.genCmp(inst.cast(ir.Inst.Cmp).?, arch),
.condbr => return self.genCondBr(inst.cast(ir.Inst.CondBr).?, arch),
.isnull => return self.genIsNull(inst.cast(ir.Inst.IsNull).?, arch),
.isnonnull => return self.genIsNonNull(inst.cast(ir.Inst.IsNonNull).?, arch),
}
}
fn genAdd(self: *Function, inst: *ir.Inst.Add, comptime arch: std.Target.Cpu.Arch) !MCValue {
const lhs = try self.resolveInst(inst.args.lhs);
const rhs = try self.resolveInst(inst.args.rhs);
switch (arch) {
.i386, .x86_64 => {
// const lhs_reg = try self.instAsReg(lhs);
// const rhs_reg = try self.instAsReg(rhs);
// const result = try self.allocateReg();
// try self.code.append(??);
// lhs_reg.release();
// rhs_reg.release();
return self.fail(inst.base.src, "TODO implement register allocation", .{});
},
else => return self.fail(inst.base.src, "TODO implement add for {}", .{self.target.cpu.arch}),
}
}
fn genArg(self: *Function, inst: *ir.Inst.Arg) !MCValue {
return self.args[inst.args.index];
}
fn genBreakpoint(self: *Function, src: usize, comptime arch: std.Target.Cpu.Arch) !MCValue {
switch (arch) {
.i386, .x86_64 => {
try self.code.append(0xcc); // int3
},
else => return self.fail(src, "TODO implement @breakpoint() for {}", .{self.target.cpu.arch}),
}
return .none;
}
fn genCall(self: *Function, inst: *ir.Inst.Call, comptime arch: std.Target.Cpu.Arch) !MCValue {
switch (arch) {
.x86_64, .i386 => {
if (inst.args.func.cast(ir.Inst.Constant)) |func_inst| {
if (inst.args.args.len != 0) {
return self.fail(inst.base.src, "TODO implement call with more than 0 parameters", .{});
}
if (func_inst.val.cast(Value.Payload.Function)) |func_val| {
const func = func_val.func;
const got = &self.bin_file.program_headers.items[self.bin_file.phdr_got_index.?];
const ptr_bits = self.target.cpu.arch.ptrBitWidth();
const ptr_bytes: u64 = @divExact(ptr_bits, 8);
const got_addr = @intCast(u32, got.p_vaddr + func.owner_decl.link.offset_table_index * ptr_bytes);
// ff 14 25 xx xx xx xx call [addr]
try self.code.resize(self.code.items.len + 7);
self.code.items[self.code.items.len - 7 ..][0..3].* = [3]u8{ 0xff, 0x14, 0x25 };
mem.writeIntLittle(u32, self.code.items[self.code.items.len - 4 ..][0..4], got_addr);
const return_type = func.owner_decl.typed_value.most_recent.typed_value.ty.fnReturnType();
switch (return_type.zigTypeTag()) {
.Void => return MCValue{ .none = {} },
.NoReturn => return MCValue{ .unreach = {} },
else => return self.fail(inst.base.src, "TODO implement fn call with non-void return value", .{}),
}
} else {
return self.fail(inst.base.src, "TODO implement calling weird function values", .{});
}
} else {
return self.fail(inst.base.src, "TODO implement calling runtime known function pointer", .{});
}
},
else => return self.fail(inst.base.src, "TODO implement call for {}", .{self.target.cpu.arch}),
}
}
fn ret(self: *Function, src: usize, comptime arch: std.Target.Cpu.Arch, mcv: MCValue) !MCValue {
if (mcv != .none) {
return self.fail(src, "TODO implement return with non-void operand", .{});
}
switch (arch) {
.i386, .x86_64 => {
try self.code.append(0xc3); // ret
},
else => return self.fail(src, "TODO implement return for {}", .{self.target.cpu.arch}),
}
return .unreach;
}
fn genRet(self: *Function, inst: *ir.Inst.Ret, comptime arch: std.Target.Cpu.Arch) !MCValue {
const operand = try self.resolveInst(inst.args.operand);
return self.ret(inst.base.src, arch, operand);
}
fn genRetVoid(self: *Function, inst: *ir.Inst.RetVoid, comptime arch: std.Target.Cpu.Arch) !MCValue {
return self.ret(inst.base.src, arch, .none);
}
fn genCmp(self: *Function, inst: *ir.Inst.Cmp, comptime arch: std.Target.Cpu.Arch) !MCValue {
switch (arch) {
else => return self.fail(inst.base.src, "TODO implement cmp for {}", .{self.target.cpu.arch}),
}
}
fn genCondBr(self: *Function, inst: *ir.Inst.CondBr, comptime arch: std.Target.Cpu.Arch) !MCValue {
switch (arch) {
else => return self.fail(inst.base.src, "TODO implement condbr for {}", .{self.target.cpu.arch}),
}
}
fn genIsNull(self: *Function, inst: *ir.Inst.IsNull, comptime arch: std.Target.Cpu.Arch) !MCValue {
switch (arch) {
else => return self.fail(inst.base.src, "TODO implement isnull for {}", .{self.target.cpu.arch}),
}
}
fn genIsNonNull(self: *Function, inst: *ir.Inst.IsNonNull, comptime arch: std.Target.Cpu.Arch) !MCValue {
// Here you can specialize this instruction if it makes sense to, otherwise the default
// will call genIsNull and invert the result.
switch (arch) {
else => return self.fail(inst.base.src, "TODO call genIsNull and invert the result ", .{}),
}
}
fn genRelativeFwdJump(self: *Function, src: usize, comptime arch: std.Target.Cpu.Arch, amount: u32) !void {
switch (arch) {
.i386, .x86_64 => {
// TODO x86 treats the operands as signed
if (amount <= std.math.maxInt(u8)) {
try self.code.resize(self.code.items.len + 2);
self.code.items[self.code.items.len - 2] = 0xeb;
self.code.items[self.code.items.len - 1] = @intCast(u8, amount);
} else {
try self.code.resize(self.code.items.len + 5);
self.code.items[self.code.items.len - 5] = 0xe9; // jmp rel32
const imm_ptr = self.code.items[self.code.items.len - 4 ..][0..4];
mem.writeIntLittle(u32, imm_ptr, amount);
}
},
else => return self.fail(src, "TODO implement relative forward jump for {}", .{self.target.cpu.arch}),
}
}
fn genBlock(self: *Function, inst: *ir.Inst.Block, comptime arch: std.Target.Cpu.Arch) !MCValue {
switch (arch) {
else => return self.fail(inst.base.src, "TODO implement codegen Block for {}", .{self.target.cpu.arch}),
}
}
fn genAsm(self: *Function, inst: *ir.Inst.Assembly, comptime arch: Target.Cpu.Arch) !MCValue {
if (arch != .x86_64 and arch != .i386) {
return self.fail(inst.base.src, "TODO implement inline asm support for more architectures", .{});
}
for (inst.args.inputs) |input, i| {
if (input.len < 3 or input[0] != '{' or input[input.len - 1] != '}') {
return self.fail(inst.base.src, "unrecognized asm input constraint: '{}'", .{input});
}
const reg_name = input[1 .. input.len - 1];
const reg = parseRegName(arch, reg_name) orelse
return self.fail(inst.base.src, "unrecognized register: '{}'", .{reg_name});
const arg = try self.resolveInst(inst.args.args[i]);
try self.genSetReg(inst.base.src, arch, reg, arg);
}
if (mem.eql(u8, inst.args.asm_source, "syscall")) {
try self.code.appendSlice(&[_]u8{ 0x0f, 0x05 });
} else {
return self.fail(inst.base.src, "TODO implement support for more x86 assembly instructions", .{});
}
if (inst.args.output) |output| {
if (output.len < 4 or output[0] != '=' or output[1] != '{' or output[output.len - 1] != '}') {
return self.fail(inst.base.src, "unrecognized asm output constraint: '{}'", .{output});
}
const reg_name = output[2 .. output.len - 1];
const reg = parseRegName(arch, reg_name) orelse
return self.fail(inst.base.src, "unrecognized register: '{}'", .{reg_name});
return MCValue{ .register = @enumToInt(reg) };
} else {
return MCValue.none;
}
}
/// Encodes a REX prefix as specified, and appends it to the instruction
/// stream. This only modifies the instruction stream if at least one bit
/// is set true, which has a few implications:
///
/// * The length of the instruction buffer will be modified *if* the
/// resulting REX is meaningful, but will remain the same if it is not.
/// * Deliberately inserting a "meaningless REX" requires explicit usage of
/// 0x40, and cannot be done via this function.
fn REX(self: *Function, arg: struct { B: bool = false, W: bool = false, X: bool = false, R: bool = false }) !void {
// From section 2.2.1.2 of the manual, REX is encoded as b0100WRXB.
var value: u8 = 0x40;
if (arg.B) {
value |= 0x1;
}
if (arg.X) {
value |= 0x2;
}
if (arg.R) {
value |= 0x4;
}
if (arg.W) {
value |= 0x8;
}
if (value != 0x40) {
try self.code.append(value);
}
}
fn genSetReg(self: *Function, src: usize, comptime arch: Target.Cpu.Arch, reg: Reg(arch), mcv: MCValue) error{ CodegenFail, OutOfMemory }!void {
switch (arch) {
.x86_64 => switch (mcv) {
.none, .unreach => unreachable,
.immediate => |x| {
if (reg.size() != 64) {
return self.fail(src, "TODO decide whether to implement non-64-bit loads", .{});
}
// 32-bit moves zero-extend to 64-bit, so xoring the 32-bit
// register is the fastest way to zero a register.
if (x == 0) {
// The encoding for `xor r32, r32` is `0x31 /r`.
// Section 3.1.1.1 of the Intel x64 Manual states that "/r indicates that the
// ModR/M byte of the instruction contains a register operand and an r/m operand."
//
// R/M bytes are composed of two bits for the mode, then three bits for the register,
// then three bits for the operand. Since we're zeroing a register, the two three-bit
// values will be identical, and the mode is three (the raw register value).
//
// If we're accessing e.g. r8d, we need to use a REX prefix before the actual operation. Since
// this is a 32-bit operation, the W flag is set to zero. X is also zero, as we're not using a SIB.
// Both R and B are set, as we're extending, in effect, the register bits *and* the operand.
try self.REX(.{ .R = reg.isExtended(), .B = reg.isExtended() });
const id = @as(u8, reg.id() & 0b111);
return self.code.appendSlice(&[_]u8{
0x31, 0xC0 | id << 3 | id,
});
}
if (x <= std.math.maxInt(u32)) {
// Next best case: if we set the lower four bytes, the upper four will be zeroed.
//
// The encoding for `mov IMM32 -> REG` is (0xB8 + R) IMM.
if (reg.isExtended()) {
// Just as with XORing, we need a REX prefix. This time though, we only
// need the B bit set, as we're extending the opcode's register field,
// and there is no Mod R/M byte.
//
// Thus, we need b01000001, or 0x41.
try self.code.resize(self.code.items.len + 6);
self.code.items[self.code.items.len - 6] = 0x41;
} else {
try self.code.resize(self.code.items.len + 5);
}
self.code.items[self.code.items.len - 5] = 0xB8 | @as(u8, reg.id() & 0b111);
const imm_ptr = self.code.items[self.code.items.len - 4 ..][0..4];
mem.writeIntLittle(u32, imm_ptr, @intCast(u32, x));
return;
}
// Worst case: we need to load the 64-bit register with the IMM. GNU's assemblers calls
// this `movabs`, though this is officially just a different variant of the plain `mov`
// instruction.
//
// This encoding is, in fact, the *same* as the one used for 32-bit loads. The only
// difference is that we set REX.W before the instruction, which extends the load to
// 64-bit and uses the full bit-width of the register.
//
// Since we always need a REX here, let's just check if we also need to set REX.B.
//
// In this case, the encoding of the REX byte is 0b0100100B
try self.REX(.{ .W = true, .B = reg.isExtended() });
try self.code.resize(self.code.items.len + 9);
self.code.items[self.code.items.len - 9] = 0xB8 | @as(u8, reg.id() & 0b111);
const imm_ptr = self.code.items[self.code.items.len - 8 ..][0..8];
mem.writeIntLittle(u64, imm_ptr, x);
},
.embedded_in_code => |code_offset| {
if (reg.size() != 64) {
return self.fail(src, "TODO decide whether to implement non-64-bit loads", .{});
}
// We need the offset from RIP in a signed i32 twos complement.
// The instruction is 7 bytes long and RIP points to the next instruction.
//
// 64-bit LEA is encoded as REX.W 8D /r. If the register is extended, the REX byte is modified,
// but the operation size is unchanged. Since we're using a disp32, we want mode 0 and lower three
// bits as five.
// REX 0x8D 0b00RRR101, where RRR is the lower three bits of the id.
try self.REX(.{ .W = true, .B = reg.isExtended() });
try self.code.resize(self.code.items.len + 6);
const rip = self.code.items.len;
const big_offset = @intCast(i64, code_offset) - @intCast(i64, rip);
const offset = @intCast(i32, big_offset);
self.code.items[self.code.items.len - 6] = 0x8D;
self.code.items[self.code.items.len - 5] = 0b101 | (@as(u8, reg.id() & 0b111) << 3);
const imm_ptr = self.code.items[self.code.items.len - 4 ..][0..4];
mem.writeIntLittle(i32, imm_ptr, offset);
},
.register => |r| {
if (reg.size() != 64) {
return self.fail(src, "TODO decide whether to implement non-64-bit loads", .{});
}
const src_reg = @intToEnum(Reg(arch), @intCast(u8, r));
// This is a variant of 8B /r. Since we're using 64-bit moves, we require a REX.
// This is thus three bytes: REX 0x8B R/M.
// If the destination is extended, the R field must be 1.
// If the *source* is extended, the B field must be 1.
// Since the register is being accessed directly, the R/M mode is three. The reg field (the middle
// three bits) contain the destination, and the R/M field (the lower three bits) contain the source.
try self.REX(.{ .W = true, .R = reg.isExtended(), .B = src_reg.isExtended() });
const R = 0xC0 | (@as(u8, reg.id() & 0b111) << 3) | @as(u8, src_reg.id() & 0b111);
try self.code.appendSlice(&[_]u8{ 0x8B, R });
},
.memory => |x| {
if (reg.size() != 64) {
return self.fail(src, "TODO decide whether to implement non-64-bit loads", .{});
}
if (x <= std.math.maxInt(u32)) {
// Moving from memory to a register is a variant of `8B /r`.
// Since we're using 64-bit moves, we require a REX.
// This variant also requires a SIB, as it would otherwise be RIP-relative.
// We want mode zero with the lower three bits set to four to indicate an SIB with no other displacement.
// The SIB must be 0x25, to indicate a disp32 with no scaled index.
// 0b00RRR100, where RRR is the lower three bits of the register ID.
// The instruction is thus eight bytes; REX 0x8B 0b00RRR100 0x25 followed by a four-byte disp32.
try self.REX(.{ .W = true, .B = reg.isExtended() });
try self.code.resize(self.code.items.len + 7);
const r = 0x04 | (@as(u8, reg.id() & 0b111) << 3);
self.code.items[self.code.items.len - 7] = 0x8B;
self.code.items[self.code.items.len - 6] = r;
self.code.items[self.code.items.len - 5] = 0x25;
const imm_ptr = self.code.items[self.code.items.len - 4 ..][0..4];
mem.writeIntLittle(u32, imm_ptr, @intCast(u32, x));
} else {
// If this is RAX, we can use a direct load; otherwise, we need to load the address, then indirectly load
// the value.
if (reg.id() == 0) {
// REX.W 0xA1 moffs64*
// moffs64* is a 64-bit offset "relative to segment base", which really just means the
// absolute address for all practical purposes.
try self.code.resize(self.code.items.len + 10);
// REX.W == 0x48
self.code.items[self.code.items.len - 10] = 0x48;
self.code.items[self.code.items.len - 9] = 0xA1;
const imm_ptr = self.code.items[self.code.items.len - 8 ..][0..8];
mem.writeIntLittle(u64, imm_ptr, x);
} else {
// This requires two instructions; a move imm as used above, followed by an indirect load using the register
// as the address and the register as the destination.
//
// This cannot be used if the lower three bits of the id are equal to four or five, as there
// is no way to possibly encode it. This means that RSP, RBP, R12, and R13 cannot be used with
// this instruction.
const id3 = @truncate(u3, reg.id());
std.debug.assert(id3 != 4 and id3 != 5);
// Rather than duplicate the logic used for the move, we just use a self-call with a new MCValue.
try self.genSetReg(src, arch, reg, MCValue{ .immediate = x });
// Now, the register contains the address of the value to load into it
// Currently, we're only allowing 64-bit registers, so we need the `REX.W 8B /r` variant.
// TODO: determine whether to allow other sized registers, and if so, handle them properly.
// This operation requires three bytes: REX 0x8B R/M
//
// For this operation, we want R/M mode *zero* (use register indirectly), and the two register
// values must match. Thus, it's 00ABCABC where ABC is the lower three bits of the register ID.
//
// Furthermore, if this is an extended register, both B and R must be set in the REX byte, as *both*
// register operands need to be marked as extended.
try self.REX(.{ .W = true, .B = reg.isExtended(), .R = reg.isExtended() });
const RM = (@as(u8, reg.id() & 0b111) << 3) | @truncate(u3, reg.id());
try self.code.appendSlice(&[_]u8{ 0x8B, RM });
}
}
},
.stack_offset => |off| {
return self.fail(src, "TODO implement genSetReg for stack variables", .{});
},
},
else => return self.fail(src, "TODO implement genSetReg for more architectures", .{}),
}
}
fn genPtrToInt(self: *Function, inst: *ir.Inst.PtrToInt) !MCValue {
// no-op
return self.resolveInst(inst.args.ptr);
}
fn genBitCast(self: *Function, inst: *ir.Inst.BitCast) !MCValue {
const operand = try self.resolveInst(inst.args.operand);
return operand;
}
fn resolveInst(self: *Function, inst: *ir.Inst) !MCValue {
if (self.inst_table.getValue(inst)) |mcv| {
return mcv;
}
if (inst.cast(ir.Inst.Constant)) |const_inst| {
const mcvalue = try self.genTypedValue(inst.src, .{ .ty = inst.ty, .val = const_inst.val });
try self.inst_table.putNoClobber(inst, mcvalue);
return mcvalue;
} else {
return self.inst_table.getValue(inst).?;
}
}
fn genTypedValue(self: *Function, src: usize, typed_value: TypedValue) !MCValue {
const ptr_bits = self.target.cpu.arch.ptrBitWidth();
const ptr_bytes: u64 = @divExact(ptr_bits, 8);
const allocator = self.code.allocator;
switch (typed_value.ty.zigTypeTag()) {
.Pointer => {
if (typed_value.val.cast(Value.Payload.DeclRef)) |payload| {
const got = &self.bin_file.program_headers.items[self.bin_file.phdr_got_index.?];
const decl = payload.decl;
const got_addr = got.p_vaddr + decl.link.offset_table_index * ptr_bytes;
return MCValue{ .memory = got_addr };
}
return self.fail(src, "TODO codegen more kinds of const pointers", .{});
},
.Int => {
const info = typed_value.ty.intInfo(self.target.*);
if (info.bits > ptr_bits or info.signed) {
return self.fail(src, "TODO const int bigger than ptr and signed int", .{});
}
return MCValue{ .immediate = typed_value.val.toUnsignedInt() };
},
.ComptimeInt => unreachable, // semantic analysis prevents this
.ComptimeFloat => unreachable, // semantic analysis prevents this
else => return self.fail(src, "TODO implement const of type '{}'", .{typed_value.ty}),
}
}
fn fail(self: *Function, src: usize, comptime format: []const u8, args: var) error{ CodegenFail, OutOfMemory } {
@setCold(true);
assert(self.err_msg == null);
self.err_msg = try ErrorMsg.create(self.code.allocator, src, format, args);
return error.CodegenFail;
}
};
const x86_64 = @import("codegen/x86_64.zig");
const x86 = @import("codegen/x86.zig");
fn Reg(comptime arch: Target.Cpu.Arch) type {
return switch (arch) {
.i386 => x86.Register,
.x86_64 => x86_64.Register,
else => @compileError("TODO add more register enums"),
};
}
fn parseRegName(comptime arch: Target.Cpu.Arch, name: []const u8) ?Reg(arch) {
return std.meta.stringToEnum(Reg(arch), name);
} | src-self-hosted/codegen.zig |
const std = @import("std");
const aoc = @import("aoc-lib.zig");
fn syntax(in: []const u8) ![2]usize {
var r = [2]usize{ 0, 0 };
var p2 = try std.BoundedArray(usize, 100).init(0);
var stack = try std.BoundedArray(u8, 100).init(0);
var i: usize = 0;
while (i < in.len) : (i += 1) {
var ch = in[i];
switch (ch) {
'(', '[', '{', '<' => {
var rch = ch + 2;
if (ch == '(') {
rch = ')';
}
try stack.append(rch);
},
'\n' => {
var s: usize = 0;
var e = stack.popOrNull();
while (e != null) : (e = stack.popOrNull()) {
s = s * 5 + score2(e.?);
}
try p2.append(s);
},
else => {
var exp = stack.pop();
if (exp != ch) {
r[0] += score1(ch);
while (in[i] != '\n') : (i += 1) {}
try stack.resize(0);
}
},
}
}
var scores = p2.slice();
std.sort.sort(usize, scores, {}, aoc.usizeLessThan);
r[1] = scores[scores.len / 2];
return r;
}
fn score1(ch: u8) usize {
switch (ch) {
')' => return 3,
']' => return 57,
'}' => return 1197,
'>' => return 25137,
else => unreachable,
}
}
fn score2(ch: u8) usize {
switch (ch) {
')' => return 1,
']' => return 2,
'}' => return 3,
'>' => return 4,
else => unreachable,
}
}
test "examples" {
var test1 = try syntax(aoc.test1file);
var real = try syntax(aoc.inputfile);
try aoc.assertEq(@as(usize, 26397), test1[0]);
try aoc.assertEq(@as(usize, 390993), real[0]);
try aoc.assertEq(@as(usize, 288957), test1[1]);
try aoc.assertEq(@as(usize, 2391385187), real[1]);
}
fn day10(inp: []const u8, bench: bool) anyerror!void {
var p = try syntax(inp);
if (!bench) {
try aoc.print("Part 1: {}\nPart 2: {}\n", .{ p[0], p[1] });
}
}
pub fn main() anyerror!void {
try aoc.benchme(aoc.input(), day10);
} | 2021/10/aoc.zig |
const std = @import("std");
const builtin = @import("builtin");
const debug = std.debug;
const os = std.os;
const io = std.io;
const print_zir = @import("print_zir.zig");
const Module = @import("Module.zig");
const Sema = @import("Sema.zig");
const Zir = @import("Zir.zig");
const Decl = Module.Decl;
pub const is_enabled = builtin.mode == .Debug;
/// To use these crash report diagnostics, publish these symbols in your main file.
/// You will also need to call initialize() on startup, preferably as the very first operation in your program.
pub const root_decls = struct {
pub const panic = if (is_enabled) compilerPanic else std.builtin.default_panic;
pub const enable_segfault_handler = false;
};
/// Install signal handlers to identify crashes and report diagnostics.
pub fn initialize() void {
if (is_enabled and debug.have_segfault_handling_support) {
attachSegfaultHandler();
}
}
fn En(comptime T: type) type {
return if (is_enabled) T else void;
}
fn en(val: anytype) En(@TypeOf(val)) {
return if (is_enabled) val else {};
}
pub const AnalyzeBody = struct {
parent: if (is_enabled) ?*AnalyzeBody else void,
sema: En(*Sema),
block: En(*Sema.Block),
body: En([]const Zir.Inst.Index),
body_index: En(usize),
pub fn push(self: *@This()) void {
if (!is_enabled) return;
const head = &zir_state;
debug.assert(self.parent == null);
self.parent = head.*;
head.* = self;
}
pub fn pop(self: *@This()) void {
if (!is_enabled) return;
const head = &zir_state;
const old = head.*.?;
debug.assert(old == self);
head.* = old.parent;
}
pub fn setBodyIndex(self: *@This(), index: usize) void {
if (!is_enabled) return;
self.body_index = index;
}
};
threadlocal var zir_state: ?*AnalyzeBody = if (is_enabled) null else @compileError("Cannot use zir_state if crash_report is disabled.");
pub fn prepAnalyzeBody(sema: *Sema, block: *Sema.Block, body: []const Zir.Inst.Index) AnalyzeBody {
if (is_enabled) {
return .{
.parent = null,
.sema = sema,
.block = block,
.body = body,
.body_index = 0,
};
} else {
if (@sizeOf(AnalyzeBody) != 0)
@compileError("AnalyzeBody must have zero size when crash reports are disabled");
return undefined;
}
}
fn dumpStatusReport() !void {
const anal = zir_state orelse return;
// Note: We have the panic mutex here, so we can safely use the global crash heap.
var fba = std.heap.FixedBufferAllocator.init(&crash_heap);
const allocator = &fba.allocator;
const stderr = io.getStdErr().writer();
const block: *Sema.Block = anal.block;
try stderr.writeAll("Analyzing ");
try writeFullyQualifiedDeclWithFile(block.src_decl, stderr);
try stderr.writeAll("\n");
print_zir.renderInstructionContext(
allocator,
anal.body,
anal.body_index,
block.namespace.file_scope,
block.src_decl.src_node,
6, // indent
stderr,
) catch |err| switch (err) {
error.OutOfMemory => try stderr.writeAll(" <out of memory dumping zir>\n"),
else => |e| return e,
};
try stderr.writeAll(" For full context, use the command\n zig ast-check -t ");
try writeFilePath(block.namespace.file_scope, stderr);
try stderr.writeAll("\n\n");
var parent = anal.parent;
while (parent) |curr| {
fba.reset();
try stderr.writeAll(" in ");
try writeFullyQualifiedDeclWithFile(curr.block.src_decl, stderr);
try stderr.writeAll("\n > ");
print_zir.renderSingleInstruction(
allocator,
curr.body[curr.body_index],
curr.block.namespace.file_scope,
curr.block.src_decl.src_node,
6, // indent
stderr,
) catch |err| switch (err) {
error.OutOfMemory => try stderr.writeAll(" <out of memory dumping zir>\n"),
else => |e| return e,
};
try stderr.writeAll("\n");
parent = curr.parent;
}
try stderr.writeAll("\n");
}
var crash_heap: [16 * 4096]u8 = undefined;
fn writeFilePath(file: *Module.File, stream: anytype) !void {
if (file.pkg.root_src_directory.path) |path| {
try stream.writeAll(path);
try stream.writeAll(std.fs.path.sep_str);
}
try stream.writeAll(file.sub_file_path);
}
fn writeFullyQualifiedDeclWithFile(decl: *Decl, stream: anytype) !void {
try writeFilePath(decl.getFileScope(), stream);
try stream.writeAll(": ");
try decl.renderFullyQualifiedDebugName(stream);
}
pub fn compilerPanic(msg: []const u8, error_return_trace: ?*std.builtin.StackTrace) noreturn {
PanicSwitch.preDispatch();
@setCold(true);
const ret_addr = @returnAddress();
const stack_ctx: StackContext = .{ .current = .{ .ret_addr = ret_addr } };
PanicSwitch.dispatch(error_return_trace, stack_ctx, msg);
}
/// Attaches a global SIGSEGV handler
pub fn attachSegfaultHandler() void {
if (!debug.have_segfault_handling_support) {
@compileError("segfault handler not supported for this target");
}
if (builtin.os.tag == .windows) {
_ = os.windows.kernel32.AddVectoredExceptionHandler(0, handleSegfaultWindows);
return;
}
var act = os.Sigaction{
.handler = .{ .sigaction = handleSegfaultLinux },
.mask = os.empty_sigset,
.flags = (os.SA.SIGINFO | os.SA.RESTART | os.SA.RESETHAND),
};
os.sigaction(os.SIG.SEGV, &act, null);
os.sigaction(os.SIG.ILL, &act, null);
os.sigaction(os.SIG.BUS, &act, null);
}
fn handleSegfaultLinux(sig: i32, info: *const os.siginfo_t, ctx_ptr: ?*const c_void) callconv(.C) noreturn {
// TODO: use alarm() here to prevent infinite loops
PanicSwitch.preDispatch();
const addr = switch (builtin.os.tag) {
.linux => @ptrToInt(info.fields.sigfault.addr),
.freebsd => @ptrToInt(info.addr),
.netbsd => @ptrToInt(info.info.reason.fault.addr),
.openbsd => @ptrToInt(info.data.fault.addr),
.solaris => @ptrToInt(info.reason.fault.addr),
else => @compileError("TODO implement handleSegfaultLinux for new linux OS"),
};
var err_buffer: [128]u8 = undefined;
const error_msg = switch (sig) {
os.SIG.SEGV => std.fmt.bufPrint(&err_buffer, "Segmentation fault at address 0x{x}", .{addr}) catch "Segmentation fault",
os.SIG.ILL => std.fmt.bufPrint(&err_buffer, "Illegal instruction at address 0x{x}", .{addr}) catch "Illegal instruction",
os.SIG.BUS => std.fmt.bufPrint(&err_buffer, "Bus error at address 0x{x}", .{addr}) catch "Bus error",
else => std.fmt.bufPrint(&err_buffer, "Unknown error (signal {}) at address 0x{x}", .{ sig, addr }) catch "Unknown error",
};
const stack_ctx: StackContext = switch (builtin.cpu.arch) {
.i386 => ctx: {
const ctx = @ptrCast(*const os.ucontext_t, @alignCast(@alignOf(os.ucontext_t), ctx_ptr));
const ip = @intCast(usize, ctx.mcontext.gregs[os.REG.EIP]);
const bp = @intCast(usize, ctx.mcontext.gregs[os.REG.EBP]);
break :ctx StackContext{ .exception = .{ .bp = bp, .ip = ip } };
},
.x86_64 => ctx: {
const ctx = @ptrCast(*const os.ucontext_t, @alignCast(@alignOf(os.ucontext_t), ctx_ptr));
const ip = switch (builtin.os.tag) {
.linux, .netbsd, .solaris => @intCast(usize, ctx.mcontext.gregs[os.REG.RIP]),
.freebsd => @intCast(usize, ctx.mcontext.rip),
.openbsd => @intCast(usize, ctx.sc_rip),
else => unreachable,
};
const bp = switch (builtin.os.tag) {
.linux, .netbsd, .solaris => @intCast(usize, ctx.mcontext.gregs[os.REG.RBP]),
.openbsd => @intCast(usize, ctx.sc_rbp),
.freebsd => @intCast(usize, ctx.mcontext.rbp),
else => unreachable,
};
break :ctx StackContext{ .exception = .{ .bp = bp, .ip = ip } };
},
.arm => ctx: {
const ctx = @ptrCast(*const os.ucontext_t, @alignCast(@alignOf(os.ucontext_t), ctx_ptr));
const ip = @intCast(usize, ctx.mcontext.arm_pc);
const bp = @intCast(usize, ctx.mcontext.arm_fp);
break :ctx StackContext{ .exception = .{ .bp = bp, .ip = ip } };
},
.aarch64 => ctx: {
const ctx = @ptrCast(*const os.ucontext_t, @alignCast(@alignOf(os.ucontext_t), ctx_ptr));
const ip = @intCast(usize, ctx.mcontext.pc);
// x29 is the ABI-designated frame pointer
const bp = @intCast(usize, ctx.mcontext.regs[29]);
break :ctx StackContext{ .exception = .{ .bp = bp, .ip = ip } };
},
else => .not_supported,
};
PanicSwitch.dispatch(null, stack_ctx, error_msg);
}
const WindowsSegfaultMessage = union(enum) {
literal: []const u8,
segfault: void,
illegal_instruction: void,
};
fn handleSegfaultWindows(info: *os.windows.EXCEPTION_POINTERS) callconv(os.windows.WINAPI) c_long {
switch (info.ExceptionRecord.ExceptionCode) {
os.windows.EXCEPTION_DATATYPE_MISALIGNMENT => handleSegfaultWindowsExtra(info, .{ .literal = "Unaligned Memory Access" }),
os.windows.EXCEPTION_ACCESS_VIOLATION => handleSegfaultWindowsExtra(info, .segfault),
os.windows.EXCEPTION_ILLEGAL_INSTRUCTION => handleSegfaultWindowsExtra(info, .illegal_instruction),
os.windows.EXCEPTION_STACK_OVERFLOW => handleSegfaultWindowsExtra(info, .{ .literal = "Stack Overflow" }),
else => return os.windows.EXCEPTION_CONTINUE_SEARCH,
}
}
fn handleSegfaultWindowsExtra(info: *os.windows.EXCEPTION_POINTERS, comptime msg: WindowsSegfaultMessage) noreturn {
PanicSwitch.preDispatch();
const stack_ctx = if (@hasDecl(os.windows, "CONTEXT")) ctx: {
const regs = info.ContextRecord.getRegs();
break :ctx StackContext{ .exception = .{ .bp = regs.bp, .ip = regs.ip } };
} else ctx: {
const addr = @ptrToInt(info.ExceptionRecord.ExceptionAddress);
break :ctx StackContext{ .current = .{ .ret_addr = addr } };
};
switch (msg) {
.literal => |err| PanicSwitch.dispatch(null, stack_ctx, err),
.segfault => {
const format_item = "Segmentation fault at address 0x{x}";
var buf: [format_item.len + 32]u8 = undefined; // 32 is arbitrary, but sufficiently large
const to_print = std.fmt.bufPrint(&buf, format_item, .{info.ExceptionRecord.ExceptionInformation[1]}) catch unreachable;
PanicSwitch.dispatch(null, stack_ctx, to_print);
},
.illegal_instruction => {
const ip: ?usize = switch (stack_ctx) {
.exception => |ex| ex.ip,
.current => |cur| cur.ret_addr,
.not_supported => null,
};
if (ip) |addr| {
const format_item = "Illegal instruction at address 0x{x}";
var buf: [format_item.len + 32]u8 = undefined; // 32 is arbitrary, but sufficiently large
const to_print = std.fmt.bufPrint(&buf, format_item, .{addr}) catch unreachable;
PanicSwitch.dispatch(null, stack_ctx, to_print);
} else {
PanicSwitch.dispatch(null, stack_ctx, "Illegal Instruction");
}
},
}
}
const StackContext = union(enum) {
current: struct {
ret_addr: ?usize,
},
exception: struct {
bp: usize,
ip: usize,
},
not_supported: void,
pub fn dumpStackTrace(ctx: @This()) void {
switch (ctx) {
.current => |ct| {
debug.dumpCurrentStackTrace(ct.ret_addr);
},
.exception => |ex| {
debug.dumpStackTraceFromBase(ex.bp, ex.ip);
},
.not_supported => {
const stderr = io.getStdErr().writer();
stderr.writeAll("Stack trace not supported on this platform.\n") catch {};
},
}
}
};
const PanicSwitch = struct {
const RecoverStage = enum {
initialize,
report_stack,
release_mutex,
release_ref_count,
abort,
silent_abort,
};
const RecoverVerbosity = enum {
message_and_stack,
message_only,
silent,
};
const PanicState = struct {
recover_stage: RecoverStage = .initialize,
recover_verbosity: RecoverVerbosity = .message_and_stack,
panic_ctx: StackContext = undefined,
panic_trace: ?*const std.builtin.StackTrace = null,
awaiting_dispatch: bool = false,
};
/// Counter for the number of threads currently panicking.
/// Updated atomically before taking the panic_mutex.
/// In recoverable cases, the program will not abort
/// until all panicking threads have dumped their traces.
var panicking: u8 = 0;
// Locked to avoid interleaving panic messages from multiple threads.
var panic_mutex = std.Thread.Mutex{};
/// Tracks the state of the current panic. If the code within the
/// panic triggers a secondary panic, this allows us to recover.
threadlocal var panic_state_raw: PanicState = .{};
/// The segfault handlers above need to do some work before they can dispatch
/// this switch. Calling preDispatch() first makes that work fault tolerant.
pub fn preDispatch() void {
// TODO: We want segfaults to trigger the panic recursively here,
// but if there is a segfault accessing this TLS slot it will cause an
// infinite loop. We should use `alarm()` to prevent the infinite
// loop and maybe also use a non-thread-local global to detect if
// it's happening and print a message.
var panic_state: *volatile PanicState = &panic_state_raw;
if (panic_state.awaiting_dispatch) {
dispatch(null, .{ .current = .{ .ret_addr = null } }, "Panic while preparing callstack");
}
panic_state.awaiting_dispatch = true;
}
/// This is the entry point to a panic-tolerant panic handler.
/// preDispatch() *MUST* be called exactly once before calling this.
/// A threadlocal "recover_stage" is updated throughout the process.
/// If a panic happens during the panic, the recover_stage will be
/// used to select a recover* function to call to resume the panic.
/// The recover_verbosity field is used to handle panics while reporting
/// panics within panics. If the panic handler triggers a panic, it will
/// attempt to log an additional stack trace for the secondary panic. If
/// that panics, it will fall back to just logging the panic message. If
/// it can't even do that witout panicing, it will recover without logging
/// anything about the internal panic. Depending on the state, "recover"
/// here may just mean "call abort".
pub fn dispatch(
trace: ?*const std.builtin.StackTrace,
stack_ctx: StackContext,
msg: []const u8,
) noreturn {
var panic_state: *volatile PanicState = &panic_state_raw;
debug.assert(panic_state.awaiting_dispatch);
panic_state.awaiting_dispatch = false;
nosuspend switch (panic_state.recover_stage) {
.initialize => goTo(initPanic, .{ panic_state, trace, stack_ctx, msg }),
.report_stack => goTo(recoverReportStack, .{ panic_state, trace, stack_ctx, msg }),
.release_mutex => goTo(recoverReleaseMutex, .{ panic_state, trace, stack_ctx, msg }),
.release_ref_count => goTo(recoverReleaseRefCount, .{ panic_state, trace, stack_ctx, msg }),
.abort => goTo(recoverAbort, .{ panic_state, trace, stack_ctx, msg }),
.silent_abort => goTo(abort, .{}),
};
}
noinline fn initPanic(
state: *volatile PanicState,
trace: ?*const std.builtin.StackTrace,
stack: StackContext,
msg: []const u8,
) noreturn {
// use a temporary so there's only one volatile store
const new_state = PanicState{
.recover_stage = .abort,
.panic_ctx = stack,
.panic_trace = trace,
};
state.* = new_state;
_ = @atomicRmw(u8, &panicking, .Add, 1, .SeqCst);
state.recover_stage = .release_ref_count;
_ = panic_mutex.acquire();
state.recover_stage = .release_mutex;
const stderr = io.getStdErr().writer();
if (builtin.single_threaded) {
stderr.print("panic: ", .{}) catch goTo(releaseMutex, .{state});
} else {
const current_thread_id = std.Thread.getCurrentId();
stderr.print("thread {} panic: ", .{current_thread_id}) catch goTo(releaseMutex, .{state});
}
stderr.print("{s}\n", .{msg}) catch goTo(releaseMutex, .{state});
state.recover_stage = .report_stack;
dumpStatusReport() catch |err| {
stderr.print("\nIntercepted error.{} while dumping current state. Continuing...\n", .{err}) catch {};
};
goTo(reportStack, .{state});
}
noinline fn recoverReportStack(
state: *volatile PanicState,
trace: ?*const std.builtin.StackTrace,
stack: StackContext,
msg: []const u8,
) noreturn {
recover(state, trace, stack, msg);
state.recover_stage = .release_mutex;
const stderr = io.getStdErr().writer();
stderr.writeAll("\nOriginal Error:\n") catch {};
goTo(reportStack, .{state});
}
noinline fn reportStack(state: *volatile PanicState) noreturn {
state.recover_stage = .release_mutex;
if (state.panic_trace) |t| {
debug.dumpStackTrace(t.*);
}
state.panic_ctx.dumpStackTrace();
goTo(releaseMutex, .{state});
}
noinline fn recoverReleaseMutex(
state: *volatile PanicState,
trace: ?*const std.builtin.StackTrace,
stack: StackContext,
msg: []const u8,
) noreturn {
recover(state, trace, stack, msg);
goTo(releaseMutex, .{state});
}
noinline fn releaseMutex(state: *volatile PanicState) noreturn {
state.recover_stage = .abort;
panic_mutex.releaseDirect();
goTo(releaseRefCount, .{state});
}
noinline fn recoverReleaseRefCount(
state: *volatile PanicState,
trace: ?*const std.builtin.StackTrace,
stack: StackContext,
msg: []const u8,
) noreturn {
recover(state, trace, stack, msg);
goTo(releaseRefCount, .{state});
}
noinline fn releaseRefCount(state: *volatile PanicState) noreturn {
state.recover_stage = .abort;
if (@atomicRmw(u8, &panicking, .Sub, 1, .SeqCst) != 1) {
// Another thread is panicking, wait for the last one to finish
// and call abort()
// Sleep forever without hammering the CPU
var event: std.Thread.StaticResetEvent = .{};
event.wait();
// This should be unreachable, recurse into recoverAbort.
@panic("event.wait() returned");
}
goTo(abort, .{});
}
noinline fn recoverAbort(
state: *volatile PanicState,
trace: ?*const std.builtin.StackTrace,
stack: StackContext,
msg: []const u8,
) noreturn {
recover(state, trace, stack, msg);
state.recover_stage = .silent_abort;
const stderr = io.getStdErr().writer();
stderr.writeAll("Aborting...\n") catch {};
goTo(abort, .{});
}
noinline fn abort() noreturn {
os.abort();
}
inline fn goTo(comptime func: anytype, args: anytype) noreturn {
// TODO: Tailcall is broken right now, but eventually this should be used
// to avoid blowing up the stack. It's ok for now though, there are no
// cycles in the state machine so the max stack usage is bounded.
//@call(.{.modifier = .always_tail}, func, args);
@call(.{}, func, args);
}
fn recover(
state: *volatile PanicState,
trace: ?*const std.builtin.StackTrace,
stack: StackContext,
msg: []const u8,
) void {
switch (state.recover_verbosity) {
.message_and_stack => {
// lower the verbosity, and restore it at the end if we don't panic.
state.recover_verbosity = .message_only;
const stderr = io.getStdErr().writer();
stderr.writeAll("\nPanicked during a panic: ") catch {};
stderr.writeAll(msg) catch {};
stderr.writeAll("\nInner panic stack:\n") catch {};
if (trace) |t| {
debug.dumpStackTrace(t.*);
}
stack.dumpStackTrace();
state.recover_verbosity = .message_and_stack;
},
.message_only => {
state.recover_verbosity = .silent;
const stderr = io.getStdErr().writer();
stderr.writeAll("\nPanicked while dumping inner panic stack: ") catch {};
stderr.writeAll(msg) catch {};
stderr.writeAll("\n") catch {};
// If we succeed, restore all the way to dumping the stack.
state.recover_verbosity = .message_and_stack;
},
.silent => {},
}
}
}; | src/crash_report.zig |
const std = @import("std");
const testing = std.testing;
const mem = std.mem;
const c = @import("c.zig").c;
const Error = @import("errors.zig").Error;
const getError = @import("errors.zig").getError;
const Image = @import("Image.zig");
const Monitor = @import("Monitor.zig");
const Window = @This();
handle: *c.GLFWwindow,
/// Resets all window hints to their default values.
///
/// This function resets all window hints to their default values.
///
/// Possible errors include glfw.Error.NotInitialized.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_hints, glfw.Window.hint, glfw.Window.hintString
pub inline fn defaultHints() Error!void {
c.glfwDefaultWindowHints();
try getError();
}
/// Sets the specified window hint to the desired value.
///
/// This function sets hints for the next call to glfw.Window.create. The hints, once set, retain
/// their values until changed by a call to this function or glfw.window.defaultHints, or until the
/// library is terminated.
///
/// Only integer value hints can be set with this function. String value hints are set with
/// glfw.Window.hintString.
///
/// This function does not check whether the specified hint values are valid. If you set hints to
/// invalid values this will instead be reported by the next call to glfw.createWindow.
///
/// Some hints are platform specific. These may be set on any platform but they will only affect
/// their specific platform. Other platforms will ignore them.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.InvalidEnum.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_hints, glfw.Window.hintString, glfw.Window.defaultHints
pub inline fn hint(hint_const: usize, value: isize) Error!void {
c.glfwWindowHint(@intCast(c_int, hint_const), @intCast(c_int, value));
try getError();
}
/// Sets the specified window hint to the desired value.
///
/// This function sets hints for the next call to glfw.Window.create. The hints, once set, retain
/// their values until changed by a call to this function or glfw.Window.defaultHints, or until the
/// library is terminated.
///
/// Only string type hints can be set with this function. Integer value hints are set with
/// glfw.Window.hint.
///
/// This function does not check whether the specified hint values are valid. If you set hints to
/// invalid values this will instead be reported by the next call to glfw.window.create.
///
/// Some hints are platform specific. These may be set on any platform but they will only affect
/// their specific platform. Other platforms will ignore them. Setting these hints requires no
/// platform specific headers or functions.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.InvalidEnum.
///
/// @pointer_lifetime The specified string is copied before this function returns.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_hints, glfw.Window.hint, glfw.Window.defaultHints
pub inline fn hintString(hint_const: usize, value: [:0]const u8) Error!void {
c.glfwWindowHintString(@intCast(c_int, hint_const), &value[0]);
try getError();
}
/// Creates a window and its associated context.
///
/// This function creates a window and its associated OpenGL or OpenGL ES context. Most of the
/// options controlling how the window and its context should be created are specified with window
/// hints using `glfw.Window.hint`.
///
/// Successful creation does not change which context is current. Before you can use the newly
/// created context, you need to make it current using `glfw.Window.makeContextCurrent`. For
/// information about the `share` parameter, see context_sharing.
///
/// The created window, framebuffer and context may differ from what you requested, as not all
/// parameters and hints are hard constraints. This includes the size of the window, especially for
/// full screen windows. To query the actual attributes of the created window, framebuffer and
/// context, see glfw.Window.getAttrib, glfw.Window.getSize and glfw.window.getFramebufferSize.
///
/// To create a full screen window, you need to specify the monitor the window will cover. If no
/// monitor is specified, the window will be windowed mode. Unless you have a way for the user to
/// choose a specific monitor, it is recommended that you pick the primary monitor. For more
/// information on how to query connected monitors, see @ref monitor_monitors.
///
/// For full screen windows, the specified size becomes the resolution of the window's _desired
/// video mode_. As long as a full screen window is not iconified, the supported video mode most
/// closely matching the desired video mode is set for the specified monitor. For more information
/// about full screen windows, including the creation of so called _windowed full screen_ or
/// _borderless full screen_ windows, see window_windowed_full_screen.
///
/// Once you have created the window, you can switch it between windowed and full screen mode with
/// glfw.Window.setMonitor. This will not affect its OpenGL or OpenGL ES context.
///
/// By default, newly created windows use the placement recommended by the window system. To create
/// the window at a specific position, make it initially invisible using the glfw.version window
/// hint, set its position and then show it.
///
/// As long as at least one full screen window is not iconified, the screensaver is prohibited from
/// starting.
///
/// Window systems put limits on window sizes. Very large or very small window dimensions may be
/// overridden by the window system on creation. Check the actual size after creation.
///
/// The swap interval is not set during window creation and the initial value may vary depending on
/// driver settings and defaults.
///
/// Possible errors include glfw.Error.NotInitialized, glfw.Error.InvalidEnum, glfw.Error.InvalidValue,
/// glfw.Error.APIUnavailable, glfw.Error.VersionUnavailable, glfw.Error.FormatUnavailable and
/// glfw.Error.PlatformError.
///
/// Parameters are as follows:
///
/// * `width` The desired width, in screen coordinates, of the window.
/// * `height` The desired height, in screen coordinates, of the window.
/// * `title` The initial, UTF-8 encoded window title.
/// * `monitor` The monitor to use for full screen mode, or `null` for windowed mode.
/// * `share` The window whose context to share resources with, or `null` to not share resources.
///
/// win32: Window creation will fail if the Microsoft GDI software OpenGL implementation is the
/// only one available.
///
/// win32: If the executable has an icon resource named `GLFW_ICON`, it will be set as the initial
/// icon for the window. If no such icon is present, the `IDI_APPLICATION` icon will be used
/// instead. To set a different icon, see glfw.Window.setIcon.
///
/// win32: The context to share resources with must not be current on any other thread.
///
/// macos: The OS only supports forward-compatible core profile contexts for OpenGL versions 3.2
/// and later. Before creating an OpenGL context of version 3.2 or later you must set the
/// `glfw.opengl_forward_compat` and `glfw.opengl_profile` hints accordingly. OpenGL 3.0 and 3.1
/// contexts are not supported at all on macOS.
///
/// macos: The GLFW window has no icon, as it is not a document window, but the dock icon will be
/// the same as the application bundle's icon. For more information on bundles, see the
/// [Bundle Programming Guide](https://developer.apple.com/library/mac/documentation/CoreFoundation/Conceptual/CFBundles/)
/// in the Mac Developer Library.
///
/// macos: The first time a window is created the menu bar is created. If GLFW finds a `MainMenu.nib`
/// it is loaded and assumed to contain a menu bar. Otherwise a minimal menu bar is created
/// manually with common commands like Hide, Quit and About. The About entry opens a minimal about
/// dialog with information from the application's bundle. Menu bar creation can be disabled
/// entirely with the glfw.cocoa_menubar init hint.
///
/// macos: On OS X 10.10 and later the window frame will not be rendered at full resolution on
/// Retina displays unless the glfw.cocoa_retina_framebuffer hint is true (1) and the `NSHighResolutionCapable`
/// key is enabled in the application bundle's `Info.plist`. For more information, see
/// [High Resolution Guidelines for OS X](https://developer.apple.com/library/mac/documentation/GraphicsAnimation/Conceptual/HighResolutionOSX/Explained/Explained.html)
/// in the Mac Developer Library. The GLFW test and example programs use a custom `Info.plist`
/// template for this, which can be found as `CMake/MacOSXBundleInfo.plist.in` in the source tree.
///
/// macos: When activating frame autosaving with glfw.cocoa_frame_name, the specified window size
/// and position may be overridden by previously saved values.
///
/// x11: Some window managers will not respect the placement of initially hidden windows.
///
/// x11: Due to the asynchronous nature of X11, it may take a moment for a window to reach its
/// requested state. This means you may not be able to query the final size, position or other
/// attributes directly after window creation.
///
/// x11: The class part of the `WM_CLASS` window property will by default be set to the window title
/// passed to this function. The instance part will use the contents of the `RESOURCE_NAME`
/// environment variable, if present and not empty, or fall back to the window title. Set the glfw.x11_class_name
/// and glfw.x11_instance_name window hints to override this.
///
/// wayland: Compositors should implement the xdg-decoration protocol for GLFW to decorate the
/// window properly. If this protocol isn't supported, or if the compositor prefers client-side
/// decorations, a very simple fallback frame will be drawn using the wp_viewporter protocol. A
/// compositor can still emit close, maximize or fullscreen events, using for instance a keybind
/// mechanism. If neither of these protocols is supported, the window won't be decorated.
///
/// wayland: A full screen window will not attempt to change the mode, no matter what the
/// requested size or refresh rate.
///
/// wayland: Screensaver inhibition requires the idle-inhibit protocol to be implemented in the
/// user's compositor.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_creation, glfw.Window.destroy
pub inline fn create(width: usize, height: usize, title: [*c]const u8, monitor: ?Monitor, share: ?Window) Error!Window {
const handle = c.glfwCreateWindow(
@intCast(c_int, width),
@intCast(c_int, height),
&title[0],
if (monitor) |m| m.handle else null,
if (share) |w| w.handle else null,
);
try getError();
return Window{ .handle = handle.? };
}
/// Destroys the specified window and its context.
///
/// This function destroys the specified window and its context. On calling this function, no
/// further callbacks will be called for that window.
///
/// If the context of the specified window is current on the main thread, it is detached before
/// being destroyed.
///
/// note: The context of the specified window must not be current on any other thread when this
/// function is called.
///
/// @reentrancy This function must not be called from a callback.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_creation, glfw.Window.create
pub inline fn destroy(self: Window) void {
c.glfwDestroyWindow(self.handle);
// Technically, glfwDestroyWindow could produce errors including glfw.Error.NotInitialized and
// glfw.Error.PlatformError. But how would anybody handle them? By creating a new window to
// warn the user? That seems user-hostile. Also, `defer try window.destroy()` isn't possible in
// Zig, so by returning an error we'd make it harder to destroy the window properly. So we differ
// from GLFW here: we discard any potential error from this operation.
getError() catch {};
}
/// Checks the close flag of the specified window.
///
/// This function returns the value of the close flag of the specified window.
///
/// @thread_safety This function may be called from any thread. Access is not synchronized.
///
/// see also: window_close
pub inline fn shouldClose(self: Window) bool {
const flag = c.glfwWindowShouldClose(self.handle);
// The only error shouldClose could return would be glfw.Error.NotInitialized, which would
// definitely have occurred before calls to shouldClose. Returning an error here makes the API
// awkward to use, so we discard it instead.
getError() catch {};
return flag == c.GLFW_TRUE;
}
/// Sets the close flag of the specified window.
///
/// This function sets the value of the close flag of the specified window. This can be used to
/// override the user's attempt to close the window, or to signal that it should be closed.
///
/// Possible errors include glfw.Error.NotInitialized.
///
/// @thread_safety This function may be called from any thread. Access is not
/// synchronized.
///
/// see also: window_close
pub inline fn setShouldClose(self: Window, value: bool) Error!void {
const boolean = if (value) c.GLFW_TRUE else c.GLFW_FALSE;
c.glfwSetWindowShouldClose(self.handle, boolean);
try getError();
}
/// Sets the UTF-8 encoded title of the specified window.
///
/// This function sets the window title, encoded as UTF-8, of the specified window.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError.
///
/// macos: The window title will not be updated until the next time you process events.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_title
pub inline fn setTitle(self: Window, title: [*c]const u8) Error!void {
c.glfwSetWindowTitle(self.handle, title);
}
/// Sets the icon for the specified window.
///
/// This function sets the icon of the specified window. If passed an array of candidate images,
/// those of or closest to the sizes desired by the system are selected. If no images are
/// specified, the window reverts to its default icon.
///
/// The pixels are 32-bit, little-endian, non-premultiplied RGBA, i.e. eight bits per channel with
/// the red channel first. They are arranged canonically as packed sequential rows, starting from
/// the top-left corner.
///
/// The desired image sizes varies depending on platform and system settings. The selected images
/// will be rescaled as needed. Good sizes include 16x16, 32x32 and 48x48.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError.
///
/// @pointer_lifetime The specified image data is copied before this function returns.
///
/// macos: The GLFW window has no icon, as it is not a document window, so this function does
/// nothing. The dock icon will be the same as the application bundle's icon. For more information
/// on bundles, see the [Bundle Programming Guide](https://developer.apple.com/library/mac/documentation/CoreFoundation/Conceptual/CFBundles/)
/// in the Mac Developer Library.
///
/// wayland: There is no existing protocol to change an icon, the window will thus inherit the one
/// defined in the application's desktop file. This function always emits glfw.Error.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_icon
pub inline fn setIcon(self: Window, allocator: *mem.Allocator, images: ?[]Image) Error!void {
if (images) |im| {
const tmp = try allocator.alloc(c.GLFWimage, im.len);
defer allocator.free(tmp);
for (im) |img, index| tmp[index] = img.toC();
c.glfwSetWindowIcon(self.handle, @intCast(c_int, im.len), &tmp[0]);
} else c.glfwSetWindowIcon(self.handle, 0, null);
try getError();
}
const Pos = struct {
x: usize,
y: usize,
};
/// Retrieves the position of the content area of the specified window.
///
/// This function retrieves the position, in screen coordinates, of the upper-left corner of the
// content area of the specified window.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError.
///
/// wayland: There is no way for an application to retrieve the global position of its windows,
/// this function will always emit glfw.Error.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_pos glfw.Window.setPos
pub inline fn getPos(self: Window) Error!Pos {
var x: c_int = 0;
var y: c_int = 0;
c.glfwGetWindowPos(self.handle, &x, &y);
try getError();
return Pos{ .x = @intCast(usize, x), .y = @intCast(usize, y) };
}
/// Sets the position of the content area of the specified window.
///
/// This function sets the position, in screen coordinates, of the upper-left corner of the content
/// area of the specified windowed mode window. If the window is a full screen window, this
/// function does nothing.
///
/// __Do not use this function__ to move an already visible window unless you have very good
/// reasons for doing so, as it will confuse and annoy the user.
///
/// The window manager may put limits on what positions are allowed. GLFW cannot and should not
/// override these limits.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError.
///
/// wayland: There is no way for an application to set the global position of its windows, this
/// function will always emit glfw.Error.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_pos, glfw.Window.getPos
pub inline fn setPos(self: Window, pos: Pos) Error!void {
c.glfwSetWindowPos(self.handle, @intCast(c_int, pos.x), @intCast(c_int, pos.y));
try getError();
}
const Size = struct {
width: usize,
height: usize,
};
/// Retrieves the size of the content area of the specified window.
///
/// This function retrieves the size, in screen coordinates, of the content area of the specified
/// window. If you wish to retrieve the size of the framebuffer of the window in pixels, see
/// glfw.Window.getFramebufferSize.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_size, glfw.Window.setSize
pub inline fn getSize(self: Window) Error!Size {
var width: c_int = 0;
var height: c_int = 0;
c.glfwGetWindowSize(self.handle, &width, &height);
try getError();
return Size{ .width = @intCast(usize, width), .height = @intCast(usize, height) };
}
/// Sets the size of the content area of the specified window.
///
/// This function sets the size, in screen coordinates, of the content area of the specified window.
///
/// For full screen windows, this function updates the resolution of its desired video mode and
/// switches to the video mode closest to it, without affecting the window's context. As the
/// context is unaffected, the bit depths of the framebuffer remain unchanged.
///
/// If you wish to update the refresh rate of the desired video mode in addition to its resolution,
/// see glfw.Window.setMonitor.
///
/// The window manager may put limits on what sizes are allowed. GLFW cannot and should not
/// override these limits.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError.
///
/// wayland: A full screen window will not attempt to change the mode, no matter what the requested
/// size.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_size, glfw.Window.getSize, glfw.Window.SetMonitor
pub inline fn setSize(self: Window, size: Size) Error!void {
c.glfwSetWindowSize(self.handle, @intCast(c_int, size.width), @intCast(c_int, size.height));
try getError();
}
/// Sets the size limits of the specified window's content area.
///
/// This function sets the size limits of the content area of the specified window. If the window
/// is full screen, the size limits only take effect/ once it is made windowed. If the window is not
/// resizable, this function does nothing.
///
/// The size limits are applied immediately to a windowed mode window and may cause it to be resized.
///
/// The maximum dimensions must be greater than or equal to the minimum dimensions. glfw.dont_care
/// may be used for any width/height parameter.
///
/// Possible errors include glfw.Error.NotInitialized, glfw.Error.InvalidValue and glfw.Error.PlatformError.
///
/// If you set size limits and an aspect ratio that conflict, the results are undefined.
///
/// wayland: The size limits will not be applied until the window is actually resized, either by
/// the user or by the compositor.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_sizelimits, glfw.Window.setAspectRatio
pub inline fn setSizeLimits(self: Window, min: Size, max: Size) Error!void {
c.glfwSetWindowSizeLimits(
self.handle,
@intCast(c_int, min.width),
@intCast(c_int, min.height),
@intCast(c_int, max.width),
@intCast(c_int, max.height),
);
try getError();
}
/// Sets the aspect ratio of the specified window.
///
/// This function sets the required aspect ratio of the content area of the specified window. If
/// the window is full screen, the aspect ratio only takes effect once it is made windowed. If the
/// window is not resizable, this function does nothing.
///
/// The aspect ratio is specified as a numerator and a denominator and both values must be greater
/// than zero. For example, the common 16:9 aspect ratio is specified as 16 and 9, respectively.
///
/// If the numerator AND denominator is set to `glfw.dont_care` then the aspect ratio limit is
/// disabled.
///
/// The aspect ratio is applied immediately to a windowed mode window and may cause it to be
/// resized.
///
/// Possible errors include glfw.Error.NotInitialized, glfw.Error.InvalidValue and
/// glfw.Error.PlatformError.
///
/// If you set size limits and an aspect ratio that conflict, the results are undefined.
///
/// wayland: The aspect ratio will not be applied until the window is actually resized, either by
/// the user or by the compositor.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_sizelimits, glfw.Window.setSizeLimits
pub inline fn setAspectRatio(self: Window, numerator: usize, denominator: usize) Error!void {
c.glfwSetWindowAspectRatio(self.handle, @intCast(c_int, numerator), @intCast(c_int, denominator));
try getError();
}
/// Retrieves the size of the framebuffer of the specified window.
///
/// This function retrieves the size, in pixels, of the framebuffer of the specified window. If you
/// wish to retrieve the size of the window in screen coordinates, see @ref glfwGetWindowSize.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_fbsize, glfwWindow.setFramebufferSizeCallback
pub inline fn getFramebufferSize(self: Window) Error!Size {
var width: c_int = 0;
var height: c_int = 0;
c.glfwGetFramebufferSize(self.handle, &width, &height);
try getError();
return Size{ .width = @intCast(usize, width), .height = @intCast(usize, height) };
}
const FrameSize = struct {
left: usize,
top: usize,
right: usize,
bottom: usize,
};
/// Retrieves the size of the frame of the window.
///
/// This function retrieves the size, in screen coordinates, of each edge of the frame of the
/// specified window. This size includes the title bar, if the window has one. The size of the
/// frame may vary depending on the window-related hints used to create it.
///
/// Because this function retrieves the size of each window frame edge and not the offset along a
/// particular coordinate axis, the retrieved values will always be zero or positive.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_size
pub inline fn getFrameSize(self: Window) Error!FrameSize {
var left: c_int = 0;
var top: c_int = 0;
var right: c_int = 0;
var bottom: c_int = 0;
c.glfwGetWindowFrameSize(self.handle, &left, &top, &right, &bottom);
try getError();
return FrameSize{
.left = @intCast(usize, left),
.top = @intCast(usize, top),
.right = @intCast(usize, right),
.bottom = @intCast(usize, bottom),
};
}
pub const ContentScale = struct {
x_scale: f32,
y_scale: f32,
};
/// Retrieves the content scale for the specified window.
///
/// This function retrieves the content scale for the specified window. The content scale is the
/// ratio between the current DPI and the platform's default DPI. This is especially important for
/// text and any UI elements. If the pixel dimensions of your UI scaled by this look appropriate on
/// your machine then it should appear at a reasonable size on other machines regardless of their
/// DPI and scaling settings. This relies on the system DPI and scaling settings being somewhat
/// correct.
///
/// On systems where each monitors can have its own content scale, the window content scale will
/// depend on which monitor the system considers the window to be on.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_scale, glfwSetWindowContentScaleCallback, glfwGetMonitorContentScale
pub inline fn getContentScale(self: Window) Error!ContentScale {
var x_scale: f32 = 0;
var y_scale: f32 = 0;
c.glfwGetWindowContentScale(self.handle, &x_scale, &y_scale);
try getError();
return ContentScale{ .x_scale = x_scale, .y_scale = y_scale };
}
/// Returns the opacity of the whole window.
///
/// This function returns the opacity of the window, including any decorations.
///
/// The opacity (or alpha) value is a positive finite number between zero and one, where zero is
/// fully transparent and one is fully opaque. If the system does not support whole window
/// transparency, this function always returns one.
///
/// The initial opacity value for newly created windows is one.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_transparency, glfw.Window.setOpacity
pub inline fn getOpacity(self: Window) Error!f32 {
const opacity = c.glfwGetWindowOpacity(self.handle);
try getError();
return opacity;
}
/// Sets the opacity of the whole window.
///
/// This function sets the opacity of the window, including any decorations.
///
/// The opacity (or alpha) value is a positive finite number between zero and one, where zero is
/// fully transparent and one is fully opaque.
///
/// The initial opacity value for newly created windows is one.
///
/// A window created with framebuffer transparency may not use whole window transparency. The
/// results of doing this are undefined.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_transparency, glfw.Window.getOpacity
pub inline fn setOpacity(self: Window, opacity: f32) Error!void {
c.glfwSetWindowOpacity(self.handle, opacity);
try getError();
}
/// Iconifies the specified window.
///
/// This function iconifies (minimizes) the specified window if it was previously restored. If the
/// window is already iconified, this function does nothing.
///
/// If the specified window is a full screen window, the original monitor resolution is restored
/// until the window is restored.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError.
///
/// wayland: There is no concept of iconification in wl_shell, this function will emit
/// glfw.Error.PlatformError when using this deprecated protocol.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_iconify, glfw.Window.restore, glfw.Window.maximize
pub inline fn iconify(self: Window) Error!void {
c.glfwIconifyWindow(self.handle);
try getError();
}
test "defaultHints" {
const glfw = @import("main.zig");
try glfw.init();
defer glfw.terminate();
try defaultHints();
}
test "hint" {
const glfw = @import("main.zig");
try glfw.init();
defer glfw.terminate();
try hint(glfw.focused, 1);
try defaultHints();
}
test "hintString" {
const glfw = @import("main.zig");
try glfw.init();
defer glfw.terminate();
try hintString(glfw.x11_class_name, "myclass");
}
test "createWindow" {
const glfw = @import("main.zig");
try glfw.init();
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
}
test "setShouldClose" {
const glfw = @import("main.zig");
try glfw.init();
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
try window.setShouldClose(true);
defer window.destroy();
}
test "setTitle" {
const glfw = @import("main.zig");
try glfw.init();
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
try window.setTitle("Updated title!");
}
// TODO(slimsag): test appears to fail on at least Linux, image size is potentially wrong.
// test "setIcon" {
// const allocator = testing.allocator;
// const glfw = @import("main.zig");
// try glfw.init();
// defer glfw.terminate();
// const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null) catch |err| {
// // return without fail, because most of our CI environments are headless / we cannot open
// // windows on them.
// std.debug.print("note: failed to create window: {}\n", .{err});
// return;
// };
// defer window.destroy();
// // Create an all-red icon image.
// var width: usize = 48;
// var height: usize = 48;
// const icon = try Image.init(allocator, width, height, width * height * 4);
// var x: usize = 0;
// var y: usize = 0;
// while (y <= height) : (y += 1) {
// while (x <= width) : (x += 1) {
// icon.pixels[(x * y * 4) + 0] = 255; // red
// icon.pixels[(x * y * 4) + 1] = 0; // green
// icon.pixels[(x * y * 4) + 2] = 0; // blue
// icon.pixels[(x * y * 4) + 3] = 255; // alpha
// }
// }
// window.setIcon(allocator, &[_]Image{icon}) catch |err| std.debug.print("can't set window icon, wayland maybe? error={}\n", .{err});
// icon.deinit(allocator); // glfw copies it.
// }
test "getPos" {
const glfw = @import("main.zig");
try glfw.init();
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
_ = window.getPos() catch |err| std.debug.print("can't get window position, wayland maybe? error={}\n", .{err});
}
test "setPos" {
const glfw = @import("main.zig");
try glfw.init();
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
_ = window.setPos(.{ .x = 0, .y = 0 }) catch |err| std.debug.print("can't set window position, wayland maybe? error={}\n", .{err});
}
test "getSize" {
const glfw = @import("main.zig");
try glfw.init();
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
_ = try window.getSize();
}
test "setSize" {
const glfw = @import("main.zig");
try glfw.init();
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
_ = try window.setSize(.{ .width = 640, .height = 480 });
}
test "setSizeLimits" {
const glfw = @import("main.zig");
try glfw.init();
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "<NAME>!", null, null) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
try window.setSizeLimits(
.{ .width = 720, .height = 480 },
.{ .width = 1080, .height = 1920 },
);
}
test "setAspectRatio" {
const glfw = @import("main.zig");
try glfw.init();
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "<NAME>!", null, null) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
try window.setAspectRatio(4, 3);
}
test "getFramebufferSize" {
const glfw = @import("main.zig");
try glfw.init();
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
_ = try window.getFramebufferSize();
}
test "getFrameSize" {
const glfw = @import("main.zig");
try glfw.init();
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
_ = try window.getFrameSize();
}
test "getContentScale" {
const glfw = @import("main.zig");
try glfw.init();
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
_ = try window.getContentScale();
}
test "getOpacity" {
const glfw = @import("main.zig");
try glfw.init();
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
_ = try window.getOpacity();
}
test "iconify" {
const glfw = @import("main.zig");
try glfw.init();
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
_ = window.iconify() catch |err| std.debug.print("can't iconify window, wayland maybe? error={}\n", .{err});
} | glfw/src/Window.zig |
const expect = std.testing.expect;
const expectEqualSlices = std.testing.expectEqualSlices;
const expectError = std.testing.expectError;
const std = @import("std");
const mqtt_string = @import("../../mqtt_string.zig");
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const FixedHeader = @import("../packet.zig").Packet.FixedHeader;
const QoS = @import("../../qos.zig").QoS;
pub const Topic = @import("./subscribe/topic.zig").Topic;
pub const Subscribe = struct {
packet_id: u16,
topics: []Topic,
pub const ParseError = error{
InvalidQoS,
EmptyTopics,
};
pub fn parse(fixed_header: FixedHeader, allocator: *Allocator, inner_reader: anytype) !Subscribe {
// Hold this so we can query remaining bytes
var limited_reader = std.io.limitedReader(inner_reader, fixed_header.remaining_length);
const reader = limited_reader.reader();
const packet_id = try reader.readIntBig(u16);
var topics = ArrayList(Topic).init(allocator);
errdefer topics.deinit();
while (limited_reader.bytes_left > 0) {
// If we fail at any step, cleanup all that was allocated until now
errdefer {
for (topics.items) |*t| {
t.deinit(allocator);
}
}
var topic = try Topic.parse(allocator, reader);
errdefer topic.deinit(allocator);
try topics.append(topic);
}
if (topics.items.len == 0) {
return error.EmptyTopics;
}
return Subscribe{
.packet_id = packet_id,
.topics = topics.toOwnedSlice(),
};
}
pub fn serialize(self: Subscribe, writer: anytype) !void {
try writer.writeIntBig(u16, self.packet_id);
for (self.topics) |topic| {
try topic.serialize(writer);
}
}
pub fn serializedLength(self: Subscribe) u32 {
var length: u32 = comptime @sizeOf(@TypeOf(self.packet_id));
for (self.topics) |topic| {
length += topic.serializedLength();
}
return length;
}
pub fn fixedHeaderFlags(self: Subscribe) u4 {
return 0b0010;
}
pub fn deinit(self: *Subscribe, allocator: *Allocator) void {
for (self.topics) |*topic| {
topic.deinit(allocator);
}
allocator.free(self.topics);
}
};
test "Subscribe payload parsing" {
const allocator = std.testing.allocator;
const buffer =
// Packet id, 3
"\x00\x03" ++
// Topic filter length, 7
"\x00\x07" ++
// Topic filter
"foo/bar" ++
// QoS, 1
"\x01" ++
// Topic filter length, 5
"\x00\x05" ++
// Topic filter
"baz/#" ++
// QoS, 2
"\x02";
const stream = std.io.fixedBufferStream(buffer).reader();
const PacketType = @import("../packet.zig").PacketType;
const fixed_header = FixedHeader{
.packet_type = PacketType.subscribe,
.flags = 0b0010,
.remaining_length = @intCast(u32, buffer.len),
};
var subscribe = try Subscribe.parse(fixed_header, allocator, stream);
defer subscribe.deinit(allocator);
try expect(subscribe.packet_id == 3);
try expect(subscribe.topics.len == 2);
try expectEqualSlices(u8, subscribe.topics[0].topic_filter, "foo/bar");
try expect(subscribe.topics[0].qos == .qos1);
try expectEqualSlices(u8, subscribe.topics[1].topic_filter, "baz/#");
try expect(subscribe.topics[1].qos == .qos2);
}
test "Subscribe parsing fails with no topics" {
const allocator = std.testing.allocator;
const buffer =
// Packet id, 3
"\x00\x03";
const stream = std.io.fixedBufferStream(buffer).reader();
const PacketType = @import("../packet.zig").PacketType;
const fixed_header = FixedHeader{
.packet_type = PacketType.subscribe,
.flags = 0b0010,
.remaining_length = @intCast(u32, buffer.len),
};
const result = Subscribe.parse(fixed_header, allocator, stream);
try expectError(error.EmptyTopics, result);
}
test "Subscribe parsing with error doesn't leak" {
const allocator = std.testing.allocator;
const buffer =
// Packet id, 3
"\x00\x03" ++
// Topic filter length, 7
"\x00\x07" ++
// Topic filter
"foo/bar" ++
// QoS, 1
"\x01" ++
// Topic filter length, 9
"\x00\x09" ++
// Topic filter, shorter
"a/b" ++
// QoS, 2
"\x02";
const stream = std.io.fixedBufferStream(buffer).reader();
const PacketType = @import("../packet.zig").PacketType;
const fixed_header = FixedHeader{
.packet_type = PacketType.subscribe,
.flags = 0b0010,
.remaining_length = @intCast(u32, buffer.len),
};
const result = Subscribe.parse(fixed_header, allocator, stream);
try expectError(error.EndOfStream, result);
}
test "serialize/parse roundtrip" {
const allocator = std.testing.allocator;
var topics = ArrayList(Topic).init(allocator);
try topics.append(Topic{ .topic_filter = "foo/#", .qos = .qos2 });
try topics.append(Topic{ .topic_filter = "bar/baz/+", .qos = .qos0 });
var topics_slice = topics.toOwnedSlice();
defer allocator.free(topics_slice);
const subscribe = Subscribe{
.packet_id = 42,
.topics = topics_slice,
};
var buffer = [_]u8{0} ** 100;
var stream = std.io.fixedBufferStream(&buffer);
var writer = stream.writer();
try subscribe.serialize(writer);
const written = try stream.getPos();
stream.reset();
const reader = stream.reader();
const PacketType = @import("../packet.zig").PacketType;
const fixed_header = FixedHeader{
.packet_type = PacketType.subscribe,
.flags = 0b0010,
.remaining_length = @intCast(u32, written),
};
var deser_subscribe = try Subscribe.parse(fixed_header, allocator, reader);
defer deser_subscribe.deinit(allocator);
try expect(subscribe.packet_id == deser_subscribe.packet_id);
try expect(subscribe.topics.len == deser_subscribe.topics.len);
try expect(subscribe.topics[0].qos == deser_subscribe.topics[0].qos);
try expectEqualSlices(u8, subscribe.topics[0].topic_filter, deser_subscribe.topics[0].topic_filter);
try expect(subscribe.topics[1].qos == deser_subscribe.topics[1].qos);
try expectEqualSlices(u8, subscribe.topics[1].topic_filter, deser_subscribe.topics[1].topic_filter);
} | src/mqtt4/packet/subscribe.zig |
const std = @import("std");
const string = []const u8;
const gpa = std.heap.c_allocator;
const knownfolders = @import("known-folders");
const zigmod = @import("../../lib.zig");
const u = @import("./../../util/index.zig");
const common = @import("./../../common.zig");
pub fn execute(args: [][]u8) !void {
const home = try knownfolders.getPath(gpa, .home);
const homepath = home.?;
const homedir = try std.fs.cwd().openDir(homepath, .{});
if (!(try u.does_file_exist(homedir, "zigmod.yml"))) {
const f = try homedir.createFile("zigmod.yml", .{});
defer f.close();
const w = f.writer();
const init = @import("../init.zig");
try init.writeExeManifest(w, try u.random_string(gpa, 48), "zigmod_installation", null, null);
}
// add to ~/zigmod.yml for later
const aqadd = @import("./add.zig");
const pkgurl = aqadd.do(homedir, args[0]) catch |err| switch (err) {
error.AquilaBadResponse => return,
else => return err,
};
// get modfile and dep
const m = try zigmod.ModFile.from_dir(gpa, homedir);
var dep: zigmod.Dep = undefined;
for (m.rootdeps) |d| {
if (std.mem.eql(u8, d.path, pkgurl)) {
dep = d;
break;
}
}
for (m.builddeps) |d| {
if (std.mem.eql(u8, d.path, pkgurl)) {
dep = d;
break;
}
}
//
const cache = try knownfolders.getPath(gpa, .cache);
const cachepath = try std.fs.path.join(gpa, &.{ cache.?, "zigmod", "deps" });
// fetch singular pkg
var fetchoptions = common.CollectOptions{
.log = true,
.update = false,
.alloc = gpa,
};
try fetchoptions.init();
const modpath = try common.get_modpath(cachepath, dep, &fetchoptions);
const moddir = try std.fs.cwd().openDir(modpath, .{});
// zigmod ci
const ci = @import("../ci.zig");
try ci.do(gpa, modpath, moddir);
// zig build
const argv: []const string = &.{
"zig", "build",
"--prefix", try std.fs.path.join(gpa, &.{ homepath, ".zigmod" }),
"--cache-dir", try std.fs.path.join(gpa, &.{ cache.?, "zigmod", "zig" }),
};
const proc = try std.ChildProcess.init(argv, gpa);
proc.cwd = modpath;
const term = try proc.spawnAndWait();
switch (term) {
.Exited => |v| u.assert(v == 0, "zig build failed with exit code: {d}", .{v}),
.Signal => |v| std.log.info("zig build was stopped with signal: {d}", .{v}),
.Stopped => |v| std.log.info("zig build was stopped with code: {d}", .{v}),
.Unknown => |v| std.log.info("zig build encountered unknown: {d}", .{v}),
}
} | src/cmd/aquila/install.zig |
pub const VIRTUAL_STORAGE_TYPE_VENDOR_UNKNOWN = Guid.initString("00000000-0000-0000-0000-000000000000");
pub const VIRTUAL_STORAGE_TYPE_VENDOR_MICROSOFT = Guid.initString("ec984aec-a0f9-47e9-901f-71415a66345b");
pub const VIRTUAL_STORAGE_TYPE_DEVICE_UNKNOWN = @as(u32, 0);
pub const VIRTUAL_STORAGE_TYPE_DEVICE_ISO = @as(u32, 1);
pub const VIRTUAL_STORAGE_TYPE_DEVICE_VHD = @as(u32, 2);
pub const VIRTUAL_STORAGE_TYPE_DEVICE_VHDX = @as(u32, 3);
pub const VIRTUAL_STORAGE_TYPE_DEVICE_VHDSET = @as(u32, 4);
pub const OPEN_VIRTUAL_DISK_RW_DEPTH_DEFAULT = @as(u32, 1);
pub const CREATE_VIRTUAL_DISK_PARAMETERS_DEFAULT_BLOCK_SIZE = @as(u32, 0);
pub const CREATE_VIRTUAL_DISK_PARAMETERS_DEFAULT_SECTOR_SIZE = @as(u32, 0);
pub const VIRTUAL_DISK_MAXIMUM_CHANGE_TRACKING_ID_LENGTH = @as(u32, 256);
pub const MERGE_VIRTUAL_DISK_DEFAULT_MERGE_DEPTH = @as(u32, 1);
//--------------------------------------------------------------------------------
// Section: Types (59)
//--------------------------------------------------------------------------------
pub const VIRTUAL_STORAGE_TYPE = extern struct {
DeviceId: u32,
VendorId: Guid,
};
pub const OPEN_VIRTUAL_DISK_VERSION = enum(i32) {
UNSPECIFIED = 0,
@"1" = 1,
@"2" = 2,
@"3" = 3,
};
pub const OPEN_VIRTUAL_DISK_VERSION_UNSPECIFIED = OPEN_VIRTUAL_DISK_VERSION.UNSPECIFIED;
pub const OPEN_VIRTUAL_DISK_VERSION_1 = OPEN_VIRTUAL_DISK_VERSION.@"1";
pub const OPEN_VIRTUAL_DISK_VERSION_2 = OPEN_VIRTUAL_DISK_VERSION.@"2";
pub const OPEN_VIRTUAL_DISK_VERSION_3 = OPEN_VIRTUAL_DISK_VERSION.@"3";
pub const OPEN_VIRTUAL_DISK_PARAMETERS = extern struct {
Version: OPEN_VIRTUAL_DISK_VERSION,
Anonymous: extern union {
Version1: extern struct {
RWDepth: u32,
},
Version2: extern struct {
GetInfoOnly: BOOL,
ReadOnly: BOOL,
ResiliencyGuid: Guid,
},
Version3: extern struct {
GetInfoOnly: BOOL,
ReadOnly: BOOL,
ResiliencyGuid: Guid,
SnapshotId: Guid,
},
},
};
pub const VIRTUAL_DISK_ACCESS_MASK = enum(u32) {
NONE = 0,
ATTACH_RO = 65536,
ATTACH_RW = 131072,
DETACH = 262144,
GET_INFO = 524288,
CREATE = 1048576,
METAOPS = 2097152,
READ = 851968,
ALL = 4128768,
WRITABLE = 3276800,
_,
pub fn initFlags(o: struct {
NONE: u1 = 0,
ATTACH_RO: u1 = 0,
ATTACH_RW: u1 = 0,
DETACH: u1 = 0,
GET_INFO: u1 = 0,
CREATE: u1 = 0,
METAOPS: u1 = 0,
READ: u1 = 0,
ALL: u1 = 0,
WRITABLE: u1 = 0,
}) VIRTUAL_DISK_ACCESS_MASK {
return @intToEnum(VIRTUAL_DISK_ACCESS_MASK,
(if (o.NONE == 1) @enumToInt(VIRTUAL_DISK_ACCESS_MASK.NONE) else 0)
| (if (o.ATTACH_RO == 1) @enumToInt(VIRTUAL_DISK_ACCESS_MASK.ATTACH_RO) else 0)
| (if (o.ATTACH_RW == 1) @enumToInt(VIRTUAL_DISK_ACCESS_MASK.ATTACH_RW) else 0)
| (if (o.DETACH == 1) @enumToInt(VIRTUAL_DISK_ACCESS_MASK.DETACH) else 0)
| (if (o.GET_INFO == 1) @enumToInt(VIRTUAL_DISK_ACCESS_MASK.GET_INFO) else 0)
| (if (o.CREATE == 1) @enumToInt(VIRTUAL_DISK_ACCESS_MASK.CREATE) else 0)
| (if (o.METAOPS == 1) @enumToInt(VIRTUAL_DISK_ACCESS_MASK.METAOPS) else 0)
| (if (o.READ == 1) @enumToInt(VIRTUAL_DISK_ACCESS_MASK.READ) else 0)
| (if (o.ALL == 1) @enumToInt(VIRTUAL_DISK_ACCESS_MASK.ALL) else 0)
| (if (o.WRITABLE == 1) @enumToInt(VIRTUAL_DISK_ACCESS_MASK.WRITABLE) else 0)
);
}
};
pub const VIRTUAL_DISK_ACCESS_NONE = VIRTUAL_DISK_ACCESS_MASK.NONE;
pub const VIRTUAL_DISK_ACCESS_ATTACH_RO = VIRTUAL_DISK_ACCESS_MASK.ATTACH_RO;
pub const VIRTUAL_DISK_ACCESS_ATTACH_RW = VIRTUAL_DISK_ACCESS_MASK.ATTACH_RW;
pub const VIRTUAL_DISK_ACCESS_DETACH = VIRTUAL_DISK_ACCESS_MASK.DETACH;
pub const VIRTUAL_DISK_ACCESS_GET_INFO = VIRTUAL_DISK_ACCESS_MASK.GET_INFO;
pub const VIRTUAL_DISK_ACCESS_CREATE = VIRTUAL_DISK_ACCESS_MASK.CREATE;
pub const VIRTUAL_DISK_ACCESS_METAOPS = VIRTUAL_DISK_ACCESS_MASK.METAOPS;
pub const VIRTUAL_DISK_ACCESS_READ = VIRTUAL_DISK_ACCESS_MASK.READ;
pub const VIRTUAL_DISK_ACCESS_ALL = VIRTUAL_DISK_ACCESS_MASK.ALL;
pub const VIRTUAL_DISK_ACCESS_WRITABLE = VIRTUAL_DISK_ACCESS_MASK.WRITABLE;
pub const OPEN_VIRTUAL_DISK_FLAG = enum(u32) {
NONE = 0,
NO_PARENTS = 1,
BLANK_FILE = 2,
BOOT_DRIVE = 4,
CACHED_IO = 8,
CUSTOM_DIFF_CHAIN = 16,
PARENT_CACHED_IO = 32,
VHDSET_FILE_ONLY = 64,
IGNORE_RELATIVE_PARENT_LOCATOR = 128,
NO_WRITE_HARDENING = 256,
SUPPORT_COMPRESSED_VOLUMES = 512,
SUPPORT_SPARSE_FILES_ANY_FS = 1024,
SUPPORT_ENCRYPTED_FILES = 2048,
_,
pub fn initFlags(o: struct {
NONE: u1 = 0,
NO_PARENTS: u1 = 0,
BLANK_FILE: u1 = 0,
BOOT_DRIVE: u1 = 0,
CACHED_IO: u1 = 0,
CUSTOM_DIFF_CHAIN: u1 = 0,
PARENT_CACHED_IO: u1 = 0,
VHDSET_FILE_ONLY: u1 = 0,
IGNORE_RELATIVE_PARENT_LOCATOR: u1 = 0,
NO_WRITE_HARDENING: u1 = 0,
SUPPORT_COMPRESSED_VOLUMES: u1 = 0,
SUPPORT_SPARSE_FILES_ANY_FS: u1 = 0,
SUPPORT_ENCRYPTED_FILES: u1 = 0,
}) OPEN_VIRTUAL_DISK_FLAG {
return @intToEnum(OPEN_VIRTUAL_DISK_FLAG,
(if (o.NONE == 1) @enumToInt(OPEN_VIRTUAL_DISK_FLAG.NONE) else 0)
| (if (o.NO_PARENTS == 1) @enumToInt(OPEN_VIRTUAL_DISK_FLAG.NO_PARENTS) else 0)
| (if (o.BLANK_FILE == 1) @enumToInt(OPEN_VIRTUAL_DISK_FLAG.BLANK_FILE) else 0)
| (if (o.BOOT_DRIVE == 1) @enumToInt(OPEN_VIRTUAL_DISK_FLAG.BOOT_DRIVE) else 0)
| (if (o.CACHED_IO == 1) @enumToInt(OPEN_VIRTUAL_DISK_FLAG.CACHED_IO) else 0)
| (if (o.CUSTOM_DIFF_CHAIN == 1) @enumToInt(OPEN_VIRTUAL_DISK_FLAG.CUSTOM_DIFF_CHAIN) else 0)
| (if (o.PARENT_CACHED_IO == 1) @enumToInt(OPEN_VIRTUAL_DISK_FLAG.PARENT_CACHED_IO) else 0)
| (if (o.VHDSET_FILE_ONLY == 1) @enumToInt(OPEN_VIRTUAL_DISK_FLAG.VHDSET_FILE_ONLY) else 0)
| (if (o.IGNORE_RELATIVE_PARENT_LOCATOR == 1) @enumToInt(OPEN_VIRTUAL_DISK_FLAG.IGNORE_RELATIVE_PARENT_LOCATOR) else 0)
| (if (o.NO_WRITE_HARDENING == 1) @enumToInt(OPEN_VIRTUAL_DISK_FLAG.NO_WRITE_HARDENING) else 0)
| (if (o.SUPPORT_COMPRESSED_VOLUMES == 1) @enumToInt(OPEN_VIRTUAL_DISK_FLAG.SUPPORT_COMPRESSED_VOLUMES) else 0)
| (if (o.SUPPORT_SPARSE_FILES_ANY_FS == 1) @enumToInt(OPEN_VIRTUAL_DISK_FLAG.SUPPORT_SPARSE_FILES_ANY_FS) else 0)
| (if (o.SUPPORT_ENCRYPTED_FILES == 1) @enumToInt(OPEN_VIRTUAL_DISK_FLAG.SUPPORT_ENCRYPTED_FILES) else 0)
);
}
};
pub const OPEN_VIRTUAL_DISK_FLAG_NONE = OPEN_VIRTUAL_DISK_FLAG.NONE;
pub const OPEN_VIRTUAL_DISK_FLAG_NO_PARENTS = OPEN_VIRTUAL_DISK_FLAG.NO_PARENTS;
pub const OPEN_VIRTUAL_DISK_FLAG_BLANK_FILE = OPEN_VIRTUAL_DISK_FLAG.BLANK_FILE;
pub const OPEN_VIRTUAL_DISK_FLAG_BOOT_DRIVE = OPEN_VIRTUAL_DISK_FLAG.BOOT_DRIVE;
pub const OPEN_VIRTUAL_DISK_FLAG_CACHED_IO = OPEN_VIRTUAL_DISK_FLAG.CACHED_IO;
pub const OPEN_VIRTUAL_DISK_FLAG_CUSTOM_DIFF_CHAIN = OPEN_VIRTUAL_DISK_FLAG.CUSTOM_DIFF_CHAIN;
pub const OPEN_VIRTUAL_DISK_FLAG_PARENT_CACHED_IO = OPEN_VIRTUAL_DISK_FLAG.PARENT_CACHED_IO;
pub const OPEN_VIRTUAL_DISK_FLAG_VHDSET_FILE_ONLY = OPEN_VIRTUAL_DISK_FLAG.VHDSET_FILE_ONLY;
pub const OPEN_VIRTUAL_DISK_FLAG_IGNORE_RELATIVE_PARENT_LOCATOR = OPEN_VIRTUAL_DISK_FLAG.IGNORE_RELATIVE_PARENT_LOCATOR;
pub const OPEN_VIRTUAL_DISK_FLAG_NO_WRITE_HARDENING = OPEN_VIRTUAL_DISK_FLAG.NO_WRITE_HARDENING;
pub const OPEN_VIRTUAL_DISK_FLAG_SUPPORT_COMPRESSED_VOLUMES = OPEN_VIRTUAL_DISK_FLAG.SUPPORT_COMPRESSED_VOLUMES;
pub const OPEN_VIRTUAL_DISK_FLAG_SUPPORT_SPARSE_FILES_ANY_FS = OPEN_VIRTUAL_DISK_FLAG.SUPPORT_SPARSE_FILES_ANY_FS;
pub const OPEN_VIRTUAL_DISK_FLAG_SUPPORT_ENCRYPTED_FILES = OPEN_VIRTUAL_DISK_FLAG.SUPPORT_ENCRYPTED_FILES;
pub const CREATE_VIRTUAL_DISK_VERSION = enum(i32) {
UNSPECIFIED = 0,
@"1" = 1,
@"2" = 2,
@"3" = 3,
@"4" = 4,
};
pub const CREATE_VIRTUAL_DISK_VERSION_UNSPECIFIED = CREATE_VIRTUAL_DISK_VERSION.UNSPECIFIED;
pub const CREATE_VIRTUAL_DISK_VERSION_1 = CREATE_VIRTUAL_DISK_VERSION.@"1";
pub const CREATE_VIRTUAL_DISK_VERSION_2 = CREATE_VIRTUAL_DISK_VERSION.@"2";
pub const CREATE_VIRTUAL_DISK_VERSION_3 = CREATE_VIRTUAL_DISK_VERSION.@"3";
pub const CREATE_VIRTUAL_DISK_VERSION_4 = CREATE_VIRTUAL_DISK_VERSION.@"4";
pub const CREATE_VIRTUAL_DISK_PARAMETERS = extern struct {
Version: CREATE_VIRTUAL_DISK_VERSION,
Anonymous: extern union {
Version1: extern struct {
UniqueId: Guid,
MaximumSize: u64,
BlockSizeInBytes: u32,
SectorSizeInBytes: u32,
ParentPath: ?[*:0]const u16,
SourcePath: ?[*:0]const u16,
},
Version2: extern struct {
UniqueId: Guid,
MaximumSize: u64,
BlockSizeInBytes: u32,
SectorSizeInBytes: u32,
PhysicalSectorSizeInBytes: u32,
ParentPath: ?[*:0]const u16,
SourcePath: ?[*:0]const u16,
OpenFlags: OPEN_VIRTUAL_DISK_FLAG,
ParentVirtualStorageType: VIRTUAL_STORAGE_TYPE,
SourceVirtualStorageType: VIRTUAL_STORAGE_TYPE,
ResiliencyGuid: Guid,
},
Version3: extern struct {
UniqueId: Guid,
MaximumSize: u64,
BlockSizeInBytes: u32,
SectorSizeInBytes: u32,
PhysicalSectorSizeInBytes: u32,
ParentPath: ?[*:0]const u16,
SourcePath: ?[*:0]const u16,
OpenFlags: OPEN_VIRTUAL_DISK_FLAG,
ParentVirtualStorageType: VIRTUAL_STORAGE_TYPE,
SourceVirtualStorageType: VIRTUAL_STORAGE_TYPE,
ResiliencyGuid: Guid,
SourceLimitPath: ?[*:0]const u16,
BackingStorageType: VIRTUAL_STORAGE_TYPE,
},
Version4: extern struct {
UniqueId: Guid,
MaximumSize: u64,
BlockSizeInBytes: u32,
SectorSizeInBytes: u32,
PhysicalSectorSizeInBytes: u32,
ParentPath: ?[*:0]const u16,
SourcePath: ?[*:0]const u16,
OpenFlags: OPEN_VIRTUAL_DISK_FLAG,
ParentVirtualStorageType: VIRTUAL_STORAGE_TYPE,
SourceVirtualStorageType: VIRTUAL_STORAGE_TYPE,
ResiliencyGuid: Guid,
SourceLimitPath: ?[*:0]const u16,
BackingStorageType: VIRTUAL_STORAGE_TYPE,
PmemAddressAbstractionType: Guid,
DataAlignment: u64,
},
},
};
pub const CREATE_VIRTUAL_DISK_FLAG = enum(u32) {
NONE = 0,
FULL_PHYSICAL_ALLOCATION = 1,
PREVENT_WRITES_TO_SOURCE_DISK = 2,
DO_NOT_COPY_METADATA_FROM_PARENT = 4,
CREATE_BACKING_STORAGE = 8,
USE_CHANGE_TRACKING_SOURCE_LIMIT = 16,
PRESERVE_PARENT_CHANGE_TRACKING_STATE = 32,
VHD_SET_USE_ORIGINAL_BACKING_STORAGE = 64,
SPARSE_FILE = 128,
PMEM_COMPATIBLE = 256,
SUPPORT_COMPRESSED_VOLUMES = 512,
SUPPORT_SPARSE_FILES_ANY_FS = 1024,
_,
pub fn initFlags(o: struct {
NONE: u1 = 0,
FULL_PHYSICAL_ALLOCATION: u1 = 0,
PREVENT_WRITES_TO_SOURCE_DISK: u1 = 0,
DO_NOT_COPY_METADATA_FROM_PARENT: u1 = 0,
CREATE_BACKING_STORAGE: u1 = 0,
USE_CHANGE_TRACKING_SOURCE_LIMIT: u1 = 0,
PRESERVE_PARENT_CHANGE_TRACKING_STATE: u1 = 0,
VHD_SET_USE_ORIGINAL_BACKING_STORAGE: u1 = 0,
SPARSE_FILE: u1 = 0,
PMEM_COMPATIBLE: u1 = 0,
SUPPORT_COMPRESSED_VOLUMES: u1 = 0,
SUPPORT_SPARSE_FILES_ANY_FS: u1 = 0,
}) CREATE_VIRTUAL_DISK_FLAG {
return @intToEnum(CREATE_VIRTUAL_DISK_FLAG,
(if (o.NONE == 1) @enumToInt(CREATE_VIRTUAL_DISK_FLAG.NONE) else 0)
| (if (o.FULL_PHYSICAL_ALLOCATION == 1) @enumToInt(CREATE_VIRTUAL_DISK_FLAG.FULL_PHYSICAL_ALLOCATION) else 0)
| (if (o.PREVENT_WRITES_TO_SOURCE_DISK == 1) @enumToInt(CREATE_VIRTUAL_DISK_FLAG.PREVENT_WRITES_TO_SOURCE_DISK) else 0)
| (if (o.DO_NOT_COPY_METADATA_FROM_PARENT == 1) @enumToInt(CREATE_VIRTUAL_DISK_FLAG.DO_NOT_COPY_METADATA_FROM_PARENT) else 0)
| (if (o.CREATE_BACKING_STORAGE == 1) @enumToInt(CREATE_VIRTUAL_DISK_FLAG.CREATE_BACKING_STORAGE) else 0)
| (if (o.USE_CHANGE_TRACKING_SOURCE_LIMIT == 1) @enumToInt(CREATE_VIRTUAL_DISK_FLAG.USE_CHANGE_TRACKING_SOURCE_LIMIT) else 0)
| (if (o.PRESERVE_PARENT_CHANGE_TRACKING_STATE == 1) @enumToInt(CREATE_VIRTUAL_DISK_FLAG.PRESERVE_PARENT_CHANGE_TRACKING_STATE) else 0)
| (if (o.VHD_SET_USE_ORIGINAL_BACKING_STORAGE == 1) @enumToInt(CREATE_VIRTUAL_DISK_FLAG.VHD_SET_USE_ORIGINAL_BACKING_STORAGE) else 0)
| (if (o.SPARSE_FILE == 1) @enumToInt(CREATE_VIRTUAL_DISK_FLAG.SPARSE_FILE) else 0)
| (if (o.PMEM_COMPATIBLE == 1) @enumToInt(CREATE_VIRTUAL_DISK_FLAG.PMEM_COMPATIBLE) else 0)
| (if (o.SUPPORT_COMPRESSED_VOLUMES == 1) @enumToInt(CREATE_VIRTUAL_DISK_FLAG.SUPPORT_COMPRESSED_VOLUMES) else 0)
| (if (o.SUPPORT_SPARSE_FILES_ANY_FS == 1) @enumToInt(CREATE_VIRTUAL_DISK_FLAG.SUPPORT_SPARSE_FILES_ANY_FS) else 0)
);
}
};
pub const CREATE_VIRTUAL_DISK_FLAG_NONE = CREATE_VIRTUAL_DISK_FLAG.NONE;
pub const CREATE_VIRTUAL_DISK_FLAG_FULL_PHYSICAL_ALLOCATION = CREATE_VIRTUAL_DISK_FLAG.FULL_PHYSICAL_ALLOCATION;
pub const CREATE_VIRTUAL_DISK_FLAG_PREVENT_WRITES_TO_SOURCE_DISK = CREATE_VIRTUAL_DISK_FLAG.PREVENT_WRITES_TO_SOURCE_DISK;
pub const CREATE_VIRTUAL_DISK_FLAG_DO_NOT_COPY_METADATA_FROM_PARENT = CREATE_VIRTUAL_DISK_FLAG.DO_NOT_COPY_METADATA_FROM_PARENT;
pub const CREATE_VIRTUAL_DISK_FLAG_CREATE_BACKING_STORAGE = CREATE_VIRTUAL_DISK_FLAG.CREATE_BACKING_STORAGE;
pub const CREATE_VIRTUAL_DISK_FLAG_USE_CHANGE_TRACKING_SOURCE_LIMIT = CREATE_VIRTUAL_DISK_FLAG.USE_CHANGE_TRACKING_SOURCE_LIMIT;
pub const CREATE_VIRTUAL_DISK_FLAG_PRESERVE_PARENT_CHANGE_TRACKING_STATE = CREATE_VIRTUAL_DISK_FLAG.PRESERVE_PARENT_CHANGE_TRACKING_STATE;
pub const CREATE_VIRTUAL_DISK_FLAG_VHD_SET_USE_ORIGINAL_BACKING_STORAGE = CREATE_VIRTUAL_DISK_FLAG.VHD_SET_USE_ORIGINAL_BACKING_STORAGE;
pub const CREATE_VIRTUAL_DISK_FLAG_SPARSE_FILE = CREATE_VIRTUAL_DISK_FLAG.SPARSE_FILE;
pub const CREATE_VIRTUAL_DISK_FLAG_PMEM_COMPATIBLE = CREATE_VIRTUAL_DISK_FLAG.PMEM_COMPATIBLE;
pub const CREATE_VIRTUAL_DISK_FLAG_SUPPORT_COMPRESSED_VOLUMES = CREATE_VIRTUAL_DISK_FLAG.SUPPORT_COMPRESSED_VOLUMES;
pub const CREATE_VIRTUAL_DISK_FLAG_SUPPORT_SPARSE_FILES_ANY_FS = CREATE_VIRTUAL_DISK_FLAG.SUPPORT_SPARSE_FILES_ANY_FS;
pub const ATTACH_VIRTUAL_DISK_VERSION = enum(i32) {
UNSPECIFIED = 0,
@"1" = 1,
@"2" = 2,
};
pub const ATTACH_VIRTUAL_DISK_VERSION_UNSPECIFIED = ATTACH_VIRTUAL_DISK_VERSION.UNSPECIFIED;
pub const ATTACH_VIRTUAL_DISK_VERSION_1 = ATTACH_VIRTUAL_DISK_VERSION.@"1";
pub const ATTACH_VIRTUAL_DISK_VERSION_2 = ATTACH_VIRTUAL_DISK_VERSION.@"2";
pub const ATTACH_VIRTUAL_DISK_PARAMETERS = extern struct {
Version: ATTACH_VIRTUAL_DISK_VERSION,
Anonymous: extern union {
Version1: extern struct {
Reserved: u32,
},
Version2: extern struct {
RestrictedOffset: u64,
RestrictedLength: u64,
},
},
};
pub const ATTACH_VIRTUAL_DISK_FLAG = enum(u32) {
NONE = 0,
READ_ONLY = 1,
NO_DRIVE_LETTER = 2,
PERMANENT_LIFETIME = 4,
NO_LOCAL_HOST = 8,
NO_SECURITY_DESCRIPTOR = 16,
BYPASS_DEFAULT_ENCRYPTION_POLICY = 32,
NON_PNP = 64,
RESTRICTED_RANGE = 128,
SINGLE_PARTITION = 256,
REGISTER_VOLUME = 512,
_,
pub fn initFlags(o: struct {
NONE: u1 = 0,
READ_ONLY: u1 = 0,
NO_DRIVE_LETTER: u1 = 0,
PERMANENT_LIFETIME: u1 = 0,
NO_LOCAL_HOST: u1 = 0,
NO_SECURITY_DESCRIPTOR: u1 = 0,
BYPASS_DEFAULT_ENCRYPTION_POLICY: u1 = 0,
NON_PNP: u1 = 0,
RESTRICTED_RANGE: u1 = 0,
SINGLE_PARTITION: u1 = 0,
REGISTER_VOLUME: u1 = 0,
}) ATTACH_VIRTUAL_DISK_FLAG {
return @intToEnum(ATTACH_VIRTUAL_DISK_FLAG,
(if (o.NONE == 1) @enumToInt(ATTACH_VIRTUAL_DISK_FLAG.NONE) else 0)
| (if (o.READ_ONLY == 1) @enumToInt(ATTACH_VIRTUAL_DISK_FLAG.READ_ONLY) else 0)
| (if (o.NO_DRIVE_LETTER == 1) @enumToInt(ATTACH_VIRTUAL_DISK_FLAG.NO_DRIVE_LETTER) else 0)
| (if (o.PERMANENT_LIFETIME == 1) @enumToInt(ATTACH_VIRTUAL_DISK_FLAG.PERMANENT_LIFETIME) else 0)
| (if (o.NO_LOCAL_HOST == 1) @enumToInt(ATTACH_VIRTUAL_DISK_FLAG.NO_LOCAL_HOST) else 0)
| (if (o.NO_SECURITY_DESCRIPTOR == 1) @enumToInt(ATTACH_VIRTUAL_DISK_FLAG.NO_SECURITY_DESCRIPTOR) else 0)
| (if (o.BYPASS_DEFAULT_ENCRYPTION_POLICY == 1) @enumToInt(ATTACH_VIRTUAL_DISK_FLAG.BYPASS_DEFAULT_ENCRYPTION_POLICY) else 0)
| (if (o.NON_PNP == 1) @enumToInt(ATTACH_VIRTUAL_DISK_FLAG.NON_PNP) else 0)
| (if (o.RESTRICTED_RANGE == 1) @enumToInt(ATTACH_VIRTUAL_DISK_FLAG.RESTRICTED_RANGE) else 0)
| (if (o.SINGLE_PARTITION == 1) @enumToInt(ATTACH_VIRTUAL_DISK_FLAG.SINGLE_PARTITION) else 0)
| (if (o.REGISTER_VOLUME == 1) @enumToInt(ATTACH_VIRTUAL_DISK_FLAG.REGISTER_VOLUME) else 0)
);
}
};
pub const ATTACH_VIRTUAL_DISK_FLAG_NONE = ATTACH_VIRTUAL_DISK_FLAG.NONE;
pub const ATTACH_VIRTUAL_DISK_FLAG_READ_ONLY = ATTACH_VIRTUAL_DISK_FLAG.READ_ONLY;
pub const ATTACH_VIRTUAL_DISK_FLAG_NO_DRIVE_LETTER = ATTACH_VIRTUAL_DISK_FLAG.NO_DRIVE_LETTER;
pub const ATTACH_VIRTUAL_DISK_FLAG_PERMANENT_LIFETIME = ATTACH_VIRTUAL_DISK_FLAG.PERMANENT_LIFETIME;
pub const ATTACH_VIRTUAL_DISK_FLAG_NO_LOCAL_HOST = ATTACH_VIRTUAL_DISK_FLAG.NO_LOCAL_HOST;
pub const ATTACH_VIRTUAL_DISK_FLAG_NO_SECURITY_DESCRIPTOR = ATTACH_VIRTUAL_DISK_FLAG.NO_SECURITY_DESCRIPTOR;
pub const ATTACH_VIRTUAL_DISK_FLAG_BYPASS_DEFAULT_ENCRYPTION_POLICY = ATTACH_VIRTUAL_DISK_FLAG.BYPASS_DEFAULT_ENCRYPTION_POLICY;
pub const ATTACH_VIRTUAL_DISK_FLAG_NON_PNP = ATTACH_VIRTUAL_DISK_FLAG.NON_PNP;
pub const ATTACH_VIRTUAL_DISK_FLAG_RESTRICTED_RANGE = ATTACH_VIRTUAL_DISK_FLAG.RESTRICTED_RANGE;
pub const ATTACH_VIRTUAL_DISK_FLAG_SINGLE_PARTITION = ATTACH_VIRTUAL_DISK_FLAG.SINGLE_PARTITION;
pub const ATTACH_VIRTUAL_DISK_FLAG_REGISTER_VOLUME = ATTACH_VIRTUAL_DISK_FLAG.REGISTER_VOLUME;
pub const DETACH_VIRTUAL_DISK_FLAG = enum(u32) {
E = 0,
_,
pub fn initFlags(o: struct {
E: u1 = 0,
}) DETACH_VIRTUAL_DISK_FLAG {
return @intToEnum(DETACH_VIRTUAL_DISK_FLAG,
(if (o.E == 1) @enumToInt(DETACH_VIRTUAL_DISK_FLAG.E) else 0)
);
}
};
pub const DETACH_VIRTUAL_DISK_FLAG_NONE = DETACH_VIRTUAL_DISK_FLAG.E;
pub const DEPENDENT_DISK_FLAG = enum(u32) {
NONE = 0,
MULT_BACKING_FILES = 1,
FULLY_ALLOCATED = 2,
READ_ONLY = 4,
REMOTE = 8,
SYSTEM_VOLUME = 16,
SYSTEM_VOLUME_PARENT = 32,
REMOVABLE = 64,
NO_DRIVE_LETTER = 128,
PARENT = 256,
NO_HOST_DISK = 512,
PERMANENT_LIFETIME = 1024,
SUPPORT_COMPRESSED_VOLUMES = 2048,
ALWAYS_ALLOW_SPARSE = 4096,
SUPPORT_ENCRYPTED_FILES = 8192,
_,
pub fn initFlags(o: struct {
NONE: u1 = 0,
MULT_BACKING_FILES: u1 = 0,
FULLY_ALLOCATED: u1 = 0,
READ_ONLY: u1 = 0,
REMOTE: u1 = 0,
SYSTEM_VOLUME: u1 = 0,
SYSTEM_VOLUME_PARENT: u1 = 0,
REMOVABLE: u1 = 0,
NO_DRIVE_LETTER: u1 = 0,
PARENT: u1 = 0,
NO_HOST_DISK: u1 = 0,
PERMANENT_LIFETIME: u1 = 0,
SUPPORT_COMPRESSED_VOLUMES: u1 = 0,
ALWAYS_ALLOW_SPARSE: u1 = 0,
SUPPORT_ENCRYPTED_FILES: u1 = 0,
}) DEPENDENT_DISK_FLAG {
return @intToEnum(DEPENDENT_DISK_FLAG,
(if (o.NONE == 1) @enumToInt(DEPENDENT_DISK_FLAG.NONE) else 0)
| (if (o.MULT_BACKING_FILES == 1) @enumToInt(DEPENDENT_DISK_FLAG.MULT_BACKING_FILES) else 0)
| (if (o.FULLY_ALLOCATED == 1) @enumToInt(DEPENDENT_DISK_FLAG.FULLY_ALLOCATED) else 0)
| (if (o.READ_ONLY == 1) @enumToInt(DEPENDENT_DISK_FLAG.READ_ONLY) else 0)
| (if (o.REMOTE == 1) @enumToInt(DEPENDENT_DISK_FLAG.REMOTE) else 0)
| (if (o.SYSTEM_VOLUME == 1) @enumToInt(DEPENDENT_DISK_FLAG.SYSTEM_VOLUME) else 0)
| (if (o.SYSTEM_VOLUME_PARENT == 1) @enumToInt(DEPENDENT_DISK_FLAG.SYSTEM_VOLUME_PARENT) else 0)
| (if (o.REMOVABLE == 1) @enumToInt(DEPENDENT_DISK_FLAG.REMOVABLE) else 0)
| (if (o.NO_DRIVE_LETTER == 1) @enumToInt(DEPENDENT_DISK_FLAG.NO_DRIVE_LETTER) else 0)
| (if (o.PARENT == 1) @enumToInt(DEPENDENT_DISK_FLAG.PARENT) else 0)
| (if (o.NO_HOST_DISK == 1) @enumToInt(DEPENDENT_DISK_FLAG.NO_HOST_DISK) else 0)
| (if (o.PERMANENT_LIFETIME == 1) @enumToInt(DEPENDENT_DISK_FLAG.PERMANENT_LIFETIME) else 0)
| (if (o.SUPPORT_COMPRESSED_VOLUMES == 1) @enumToInt(DEPENDENT_DISK_FLAG.SUPPORT_COMPRESSED_VOLUMES) else 0)
| (if (o.ALWAYS_ALLOW_SPARSE == 1) @enumToInt(DEPENDENT_DISK_FLAG.ALWAYS_ALLOW_SPARSE) else 0)
| (if (o.SUPPORT_ENCRYPTED_FILES == 1) @enumToInt(DEPENDENT_DISK_FLAG.SUPPORT_ENCRYPTED_FILES) else 0)
);
}
};
pub const DEPENDENT_DISK_FLAG_NONE = DEPENDENT_DISK_FLAG.NONE;
pub const DEPENDENT_DISK_FLAG_MULT_BACKING_FILES = DEPENDENT_DISK_FLAG.MULT_BACKING_FILES;
pub const DEPENDENT_DISK_FLAG_FULLY_ALLOCATED = DEPENDENT_DISK_FLAG.FULLY_ALLOCATED;
pub const DEPENDENT_DISK_FLAG_READ_ONLY = DEPENDENT_DISK_FLAG.READ_ONLY;
pub const DEPENDENT_DISK_FLAG_REMOTE = DEPENDENT_DISK_FLAG.REMOTE;
pub const DEPENDENT_DISK_FLAG_SYSTEM_VOLUME = DEPENDENT_DISK_FLAG.SYSTEM_VOLUME;
pub const DEPENDENT_DISK_FLAG_SYSTEM_VOLUME_PARENT = DEPENDENT_DISK_FLAG.SYSTEM_VOLUME_PARENT;
pub const DEPENDENT_DISK_FLAG_REMOVABLE = DEPENDENT_DISK_FLAG.REMOVABLE;
pub const DEPENDENT_DISK_FLAG_NO_DRIVE_LETTER = DEPENDENT_DISK_FLAG.NO_DRIVE_LETTER;
pub const DEPENDENT_DISK_FLAG_PARENT = DEPENDENT_DISK_FLAG.PARENT;
pub const DEPENDENT_DISK_FLAG_NO_HOST_DISK = DEPENDENT_DISK_FLAG.NO_HOST_DISK;
pub const DEPENDENT_DISK_FLAG_PERMANENT_LIFETIME = DEPENDENT_DISK_FLAG.PERMANENT_LIFETIME;
pub const DEPENDENT_DISK_FLAG_SUPPORT_COMPRESSED_VOLUMES = DEPENDENT_DISK_FLAG.SUPPORT_COMPRESSED_VOLUMES;
pub const DEPENDENT_DISK_FLAG_ALWAYS_ALLOW_SPARSE = DEPENDENT_DISK_FLAG.ALWAYS_ALLOW_SPARSE;
pub const DEPENDENT_DISK_FLAG_SUPPORT_ENCRYPTED_FILES = DEPENDENT_DISK_FLAG.SUPPORT_ENCRYPTED_FILES;
pub const STORAGE_DEPENDENCY_INFO_VERSION = enum(i32) {
UNSPECIFIED = 0,
@"1" = 1,
@"2" = 2,
};
pub const STORAGE_DEPENDENCY_INFO_VERSION_UNSPECIFIED = STORAGE_DEPENDENCY_INFO_VERSION.UNSPECIFIED;
pub const STORAGE_DEPENDENCY_INFO_VERSION_1 = STORAGE_DEPENDENCY_INFO_VERSION.@"1";
pub const STORAGE_DEPENDENCY_INFO_VERSION_2 = STORAGE_DEPENDENCY_INFO_VERSION.@"2";
pub const STORAGE_DEPENDENCY_INFO_TYPE_1 = extern struct {
DependencyTypeFlags: DEPENDENT_DISK_FLAG,
ProviderSpecificFlags: u32,
VirtualStorageType: VIRTUAL_STORAGE_TYPE,
};
pub const STORAGE_DEPENDENCY_INFO_TYPE_2 = extern struct {
DependencyTypeFlags: DEPENDENT_DISK_FLAG,
ProviderSpecificFlags: u32,
VirtualStorageType: VIRTUAL_STORAGE_TYPE,
AncestorLevel: u32,
DependencyDeviceName: ?PWSTR,
HostVolumeName: ?PWSTR,
DependentVolumeName: ?PWSTR,
DependentVolumeRelativePath: ?PWSTR,
};
pub const STORAGE_DEPENDENCY_INFO = extern struct {
Version: STORAGE_DEPENDENCY_INFO_VERSION,
NumberEntries: u32,
Anonymous: extern union {
Version1Entries: [1]STORAGE_DEPENDENCY_INFO_TYPE_1,
Version2Entries: [1]STORAGE_DEPENDENCY_INFO_TYPE_2,
},
};
pub const GET_STORAGE_DEPENDENCY_FLAG = enum(u32) {
NONE = 0,
HOST_VOLUMES = 1,
DISK_HANDLE = 2,
_,
pub fn initFlags(o: struct {
NONE: u1 = 0,
HOST_VOLUMES: u1 = 0,
DISK_HANDLE: u1 = 0,
}) GET_STORAGE_DEPENDENCY_FLAG {
return @intToEnum(GET_STORAGE_DEPENDENCY_FLAG,
(if (o.NONE == 1) @enumToInt(GET_STORAGE_DEPENDENCY_FLAG.NONE) else 0)
| (if (o.HOST_VOLUMES == 1) @enumToInt(GET_STORAGE_DEPENDENCY_FLAG.HOST_VOLUMES) else 0)
| (if (o.DISK_HANDLE == 1) @enumToInt(GET_STORAGE_DEPENDENCY_FLAG.DISK_HANDLE) else 0)
);
}
};
pub const GET_STORAGE_DEPENDENCY_FLAG_NONE = GET_STORAGE_DEPENDENCY_FLAG.NONE;
pub const GET_STORAGE_DEPENDENCY_FLAG_HOST_VOLUMES = GET_STORAGE_DEPENDENCY_FLAG.HOST_VOLUMES;
pub const GET_STORAGE_DEPENDENCY_FLAG_DISK_HANDLE = GET_STORAGE_DEPENDENCY_FLAG.DISK_HANDLE;
pub const GET_VIRTUAL_DISK_INFO_VERSION = enum(i32) {
UNSPECIFIED = 0,
SIZE = 1,
IDENTIFIER = 2,
PARENT_LOCATION = 3,
PARENT_IDENTIFIER = 4,
PARENT_TIMESTAMP = 5,
VIRTUAL_STORAGE_TYPE = 6,
PROVIDER_SUBTYPE = 7,
IS_4K_ALIGNED = 8,
PHYSICAL_DISK = 9,
VHD_PHYSICAL_SECTOR_SIZE = 10,
SMALLEST_SAFE_VIRTUAL_SIZE = 11,
FRAGMENTATION = 12,
IS_LOADED = 13,
VIRTUAL_DISK_ID = 14,
CHANGE_TRACKING_STATE = 15,
};
pub const GET_VIRTUAL_DISK_INFO_UNSPECIFIED = GET_VIRTUAL_DISK_INFO_VERSION.UNSPECIFIED;
pub const GET_VIRTUAL_DISK_INFO_SIZE = GET_VIRTUAL_DISK_INFO_VERSION.SIZE;
pub const GET_VIRTUAL_DISK_INFO_IDENTIFIER = GET_VIRTUAL_DISK_INFO_VERSION.IDENTIFIER;
pub const GET_VIRTUAL_DISK_INFO_PARENT_LOCATION = GET_VIRTUAL_DISK_INFO_VERSION.PARENT_LOCATION;
pub const GET_VIRTUAL_DISK_INFO_PARENT_IDENTIFIER = GET_VIRTUAL_DISK_INFO_VERSION.PARENT_IDENTIFIER;
pub const GET_VIRTUAL_DISK_INFO_PARENT_TIMESTAMP = GET_VIRTUAL_DISK_INFO_VERSION.PARENT_TIMESTAMP;
pub const GET_VIRTUAL_DISK_INFO_VIRTUAL_STORAGE_TYPE = GET_VIRTUAL_DISK_INFO_VERSION.VIRTUAL_STORAGE_TYPE;
pub const GET_VIRTUAL_DISK_INFO_PROVIDER_SUBTYPE = GET_VIRTUAL_DISK_INFO_VERSION.PROVIDER_SUBTYPE;
pub const GET_VIRTUAL_DISK_INFO_IS_4K_ALIGNED = GET_VIRTUAL_DISK_INFO_VERSION.IS_4K_ALIGNED;
pub const GET_VIRTUAL_DISK_INFO_PHYSICAL_DISK = GET_VIRTUAL_DISK_INFO_VERSION.PHYSICAL_DISK;
pub const GET_VIRTUAL_DISK_INFO_VHD_PHYSICAL_SECTOR_SIZE = GET_VIRTUAL_DISK_INFO_VERSION.VHD_PHYSICAL_SECTOR_SIZE;
pub const GET_VIRTUAL_DISK_INFO_SMALLEST_SAFE_VIRTUAL_SIZE = GET_VIRTUAL_DISK_INFO_VERSION.SMALLEST_SAFE_VIRTUAL_SIZE;
pub const GET_VIRTUAL_DISK_INFO_FRAGMENTATION = GET_VIRTUAL_DISK_INFO_VERSION.FRAGMENTATION;
pub const GET_VIRTUAL_DISK_INFO_IS_LOADED = GET_VIRTUAL_DISK_INFO_VERSION.IS_LOADED;
pub const GET_VIRTUAL_DISK_INFO_VIRTUAL_DISK_ID = GET_VIRTUAL_DISK_INFO_VERSION.VIRTUAL_DISK_ID;
pub const GET_VIRTUAL_DISK_INFO_CHANGE_TRACKING_STATE = GET_VIRTUAL_DISK_INFO_VERSION.CHANGE_TRACKING_STATE;
pub const GET_VIRTUAL_DISK_INFO = extern struct {
Version: GET_VIRTUAL_DISK_INFO_VERSION,
Anonymous: extern union {
Size: extern struct {
VirtualSize: u64,
PhysicalSize: u64,
BlockSize: u32,
SectorSize: u32,
},
Identifier: Guid,
ParentLocation: extern struct {
ParentResolved: BOOL,
ParentLocationBuffer: [1]u16,
},
ParentIdentifier: Guid,
ParentTimestamp: u32,
VirtualStorageType: VIRTUAL_STORAGE_TYPE,
ProviderSubtype: u32,
Is4kAligned: BOOL,
IsLoaded: BOOL,
PhysicalDisk: extern struct {
LogicalSectorSize: u32,
PhysicalSectorSize: u32,
IsRemote: BOOL,
},
VhdPhysicalSectorSize: u32,
SmallestSafeVirtualSize: u64,
FragmentationPercentage: u32,
VirtualDiskId: Guid,
ChangeTrackingState: extern struct {
Enabled: BOOL,
NewerChanges: BOOL,
MostRecentId: [1]u16,
},
},
};
pub const SET_VIRTUAL_DISK_INFO_VERSION = enum(i32) {
UNSPECIFIED = 0,
PARENT_PATH = 1,
IDENTIFIER = 2,
PARENT_PATH_WITH_DEPTH = 3,
PHYSICAL_SECTOR_SIZE = 4,
VIRTUAL_DISK_ID = 5,
CHANGE_TRACKING_STATE = 6,
PARENT_LOCATOR = 7,
};
pub const SET_VIRTUAL_DISK_INFO_UNSPECIFIED = SET_VIRTUAL_DISK_INFO_VERSION.UNSPECIFIED;
pub const SET_VIRTUAL_DISK_INFO_PARENT_PATH = SET_VIRTUAL_DISK_INFO_VERSION.PARENT_PATH;
pub const SET_VIRTUAL_DISK_INFO_IDENTIFIER = SET_VIRTUAL_DISK_INFO_VERSION.IDENTIFIER;
pub const SET_VIRTUAL_DISK_INFO_PARENT_PATH_WITH_DEPTH = SET_VIRTUAL_DISK_INFO_VERSION.PARENT_PATH_WITH_DEPTH;
pub const SET_VIRTUAL_DISK_INFO_PHYSICAL_SECTOR_SIZE = SET_VIRTUAL_DISK_INFO_VERSION.PHYSICAL_SECTOR_SIZE;
pub const SET_VIRTUAL_DISK_INFO_VIRTUAL_DISK_ID = SET_VIRTUAL_DISK_INFO_VERSION.VIRTUAL_DISK_ID;
pub const SET_VIRTUAL_DISK_INFO_CHANGE_TRACKING_STATE = SET_VIRTUAL_DISK_INFO_VERSION.CHANGE_TRACKING_STATE;
pub const SET_VIRTUAL_DISK_INFO_PARENT_LOCATOR = SET_VIRTUAL_DISK_INFO_VERSION.PARENT_LOCATOR;
pub const SET_VIRTUAL_DISK_INFO = extern struct {
Version: SET_VIRTUAL_DISK_INFO_VERSION,
Anonymous: extern union {
ParentFilePath: ?[*:0]const u16,
UniqueIdentifier: Guid,
ParentPathWithDepthInfo: extern struct {
ChildDepth: u32,
ParentFilePath: ?[*:0]const u16,
},
VhdPhysicalSectorSize: u32,
VirtualDiskId: Guid,
ChangeTrackingEnabled: BOOL,
ParentLocator: extern struct {
LinkageId: Guid,
ParentFilePath: ?[*:0]const u16,
},
},
};
pub const VIRTUAL_DISK_PROGRESS = extern struct {
OperationStatus: u32,
CurrentValue: u64,
CompletionValue: u64,
};
pub const COMPACT_VIRTUAL_DISK_VERSION = enum(i32) {
UNSPECIFIED = 0,
@"1" = 1,
};
pub const COMPACT_VIRTUAL_DISK_VERSION_UNSPECIFIED = COMPACT_VIRTUAL_DISK_VERSION.UNSPECIFIED;
pub const COMPACT_VIRTUAL_DISK_VERSION_1 = COMPACT_VIRTUAL_DISK_VERSION.@"1";
pub const COMPACT_VIRTUAL_DISK_PARAMETERS = extern struct {
Version: COMPACT_VIRTUAL_DISK_VERSION,
Anonymous: extern union {
Version1: extern struct {
Reserved: u32,
},
},
};
pub const COMPACT_VIRTUAL_DISK_FLAG = enum(u32) {
NE = 0,
_ZERO_SCAN = 1,
_BLOCK_MOVES = 2,
_,
pub fn initFlags(o: struct {
NE: u1 = 0,
_ZERO_SCAN: u1 = 0,
_BLOCK_MOVES: u1 = 0,
}) COMPACT_VIRTUAL_DISK_FLAG {
return @intToEnum(COMPACT_VIRTUAL_DISK_FLAG,
(if (o.NE == 1) @enumToInt(COMPACT_VIRTUAL_DISK_FLAG.NE) else 0)
| (if (o._ZERO_SCAN == 1) @enumToInt(COMPACT_VIRTUAL_DISK_FLAG._ZERO_SCAN) else 0)
| (if (o._BLOCK_MOVES == 1) @enumToInt(COMPACT_VIRTUAL_DISK_FLAG._BLOCK_MOVES) else 0)
);
}
};
pub const COMPACT_VIRTUAL_DISK_FLAG_NONE = COMPACT_VIRTUAL_DISK_FLAG.NE;
pub const COMPACT_VIRTUAL_DISK_FLAG_NO_ZERO_SCAN = COMPACT_VIRTUAL_DISK_FLAG._ZERO_SCAN;
pub const COMPACT_VIRTUAL_DISK_FLAG_NO_BLOCK_MOVES = COMPACT_VIRTUAL_DISK_FLAG._BLOCK_MOVES;
pub const MERGE_VIRTUAL_DISK_VERSION = enum(i32) {
UNSPECIFIED = 0,
@"1" = 1,
@"2" = 2,
};
pub const MERGE_VIRTUAL_DISK_VERSION_UNSPECIFIED = MERGE_VIRTUAL_DISK_VERSION.UNSPECIFIED;
pub const MERGE_VIRTUAL_DISK_VERSION_1 = MERGE_VIRTUAL_DISK_VERSION.@"1";
pub const MERGE_VIRTUAL_DISK_VERSION_2 = MERGE_VIRTUAL_DISK_VERSION.@"2";
pub const MERGE_VIRTUAL_DISK_PARAMETERS = extern struct {
Version: MERGE_VIRTUAL_DISK_VERSION,
Anonymous: extern union {
Version1: extern struct {
MergeDepth: u32,
},
Version2: extern struct {
MergeSourceDepth: u32,
MergeTargetDepth: u32,
},
},
};
pub const MERGE_VIRTUAL_DISK_FLAG = enum(u32) {
E = 0,
_,
pub fn initFlags(o: struct {
E: u1 = 0,
}) MERGE_VIRTUAL_DISK_FLAG {
return @intToEnum(MERGE_VIRTUAL_DISK_FLAG,
(if (o.E == 1) @enumToInt(MERGE_VIRTUAL_DISK_FLAG.E) else 0)
);
}
};
pub const MERGE_VIRTUAL_DISK_FLAG_NONE = MERGE_VIRTUAL_DISK_FLAG.E;
pub const EXPAND_VIRTUAL_DISK_VERSION = enum(i32) {
UNSPECIFIED = 0,
@"1" = 1,
};
pub const EXPAND_VIRTUAL_DISK_VERSION_UNSPECIFIED = EXPAND_VIRTUAL_DISK_VERSION.UNSPECIFIED;
pub const EXPAND_VIRTUAL_DISK_VERSION_1 = EXPAND_VIRTUAL_DISK_VERSION.@"1";
pub const EXPAND_VIRTUAL_DISK_PARAMETERS = extern struct {
Version: EXPAND_VIRTUAL_DISK_VERSION,
Anonymous: extern union {
Version1: extern struct {
NewSize: u64,
},
},
};
pub const EXPAND_VIRTUAL_DISK_FLAG = enum(u32) {
NE = 0,
TIFY_CHANGE = 1,
_,
pub fn initFlags(o: struct {
NE: u1 = 0,
TIFY_CHANGE: u1 = 0,
}) EXPAND_VIRTUAL_DISK_FLAG {
return @intToEnum(EXPAND_VIRTUAL_DISK_FLAG,
(if (o.NE == 1) @enumToInt(EXPAND_VIRTUAL_DISK_FLAG.NE) else 0)
| (if (o.TIFY_CHANGE == 1) @enumToInt(EXPAND_VIRTUAL_DISK_FLAG.TIFY_CHANGE) else 0)
);
}
};
pub const EXPAND_VIRTUAL_DISK_FLAG_NONE = EXPAND_VIRTUAL_DISK_FLAG.NE;
pub const EXPAND_VIRTUAL_DISK_FLAG_NOTIFY_CHANGE = EXPAND_VIRTUAL_DISK_FLAG.TIFY_CHANGE;
pub const RESIZE_VIRTUAL_DISK_VERSION = enum(i32) {
UNSPECIFIED = 0,
@"1" = 1,
};
pub const RESIZE_VIRTUAL_DISK_VERSION_UNSPECIFIED = RESIZE_VIRTUAL_DISK_VERSION.UNSPECIFIED;
pub const RESIZE_VIRTUAL_DISK_VERSION_1 = RESIZE_VIRTUAL_DISK_VERSION.@"1";
pub const RESIZE_VIRTUAL_DISK_PARAMETERS = extern struct {
Version: RESIZE_VIRTUAL_DISK_VERSION,
Anonymous: extern union {
Version1: extern struct {
NewSize: u64,
},
},
};
pub const RESIZE_VIRTUAL_DISK_FLAG = enum(u32) {
NONE = 0,
ALLOW_UNSAFE_VIRTUAL_SIZE = 1,
RESIZE_TO_SMALLEST_SAFE_VIRTUAL_SIZE = 2,
_,
pub fn initFlags(o: struct {
NONE: u1 = 0,
ALLOW_UNSAFE_VIRTUAL_SIZE: u1 = 0,
RESIZE_TO_SMALLEST_SAFE_VIRTUAL_SIZE: u1 = 0,
}) RESIZE_VIRTUAL_DISK_FLAG {
return @intToEnum(RESIZE_VIRTUAL_DISK_FLAG,
(if (o.NONE == 1) @enumToInt(RESIZE_VIRTUAL_DISK_FLAG.NONE) else 0)
| (if (o.ALLOW_UNSAFE_VIRTUAL_SIZE == 1) @enumToInt(RESIZE_VIRTUAL_DISK_FLAG.ALLOW_UNSAFE_VIRTUAL_SIZE) else 0)
| (if (o.RESIZE_TO_SMALLEST_SAFE_VIRTUAL_SIZE == 1) @enumToInt(RESIZE_VIRTUAL_DISK_FLAG.RESIZE_TO_SMALLEST_SAFE_VIRTUAL_SIZE) else 0)
);
}
};
pub const RESIZE_VIRTUAL_DISK_FLAG_NONE = RESIZE_VIRTUAL_DISK_FLAG.NONE;
pub const RESIZE_VIRTUAL_DISK_FLAG_ALLOW_UNSAFE_VIRTUAL_SIZE = RESIZE_VIRTUAL_DISK_FLAG.ALLOW_UNSAFE_VIRTUAL_SIZE;
pub const RESIZE_VIRTUAL_DISK_FLAG_RESIZE_TO_SMALLEST_SAFE_VIRTUAL_SIZE = RESIZE_VIRTUAL_DISK_FLAG.RESIZE_TO_SMALLEST_SAFE_VIRTUAL_SIZE;
pub const MIRROR_VIRTUAL_DISK_VERSION = enum(i32) {
UNSPECIFIED = 0,
@"1" = 1,
};
pub const MIRROR_VIRTUAL_DISK_VERSION_UNSPECIFIED = MIRROR_VIRTUAL_DISK_VERSION.UNSPECIFIED;
pub const MIRROR_VIRTUAL_DISK_VERSION_1 = MIRROR_VIRTUAL_DISK_VERSION.@"1";
pub const MIRROR_VIRTUAL_DISK_PARAMETERS = extern struct {
Version: MIRROR_VIRTUAL_DISK_VERSION,
Anonymous: extern union {
Version1: extern struct {
MirrorVirtualDiskPath: ?[*:0]const u16,
},
},
};
pub const MIRROR_VIRTUAL_DISK_FLAG = enum(u32) {
NONE = 0,
EXISTING_FILE = 1,
SKIP_MIRROR_ACTIVATION = 2,
ENABLE_SMB_COMPRESSION = 4,
IS_LIVE_MIGRATION = 8,
_,
pub fn initFlags(o: struct {
NONE: u1 = 0,
EXISTING_FILE: u1 = 0,
SKIP_MIRROR_ACTIVATION: u1 = 0,
ENABLE_SMB_COMPRESSION: u1 = 0,
IS_LIVE_MIGRATION: u1 = 0,
}) MIRROR_VIRTUAL_DISK_FLAG {
return @intToEnum(MIRROR_VIRTUAL_DISK_FLAG,
(if (o.NONE == 1) @enumToInt(MIRROR_VIRTUAL_DISK_FLAG.NONE) else 0)
| (if (o.EXISTING_FILE == 1) @enumToInt(MIRROR_VIRTUAL_DISK_FLAG.EXISTING_FILE) else 0)
| (if (o.SKIP_MIRROR_ACTIVATION == 1) @enumToInt(MIRROR_VIRTUAL_DISK_FLAG.SKIP_MIRROR_ACTIVATION) else 0)
| (if (o.ENABLE_SMB_COMPRESSION == 1) @enumToInt(MIRROR_VIRTUAL_DISK_FLAG.ENABLE_SMB_COMPRESSION) else 0)
| (if (o.IS_LIVE_MIGRATION == 1) @enumToInt(MIRROR_VIRTUAL_DISK_FLAG.IS_LIVE_MIGRATION) else 0)
);
}
};
pub const MIRROR_VIRTUAL_DISK_FLAG_NONE = MIRROR_VIRTUAL_DISK_FLAG.NONE;
pub const MIRROR_VIRTUAL_DISK_FLAG_EXISTING_FILE = MIRROR_VIRTUAL_DISK_FLAG.EXISTING_FILE;
pub const MIRROR_VIRTUAL_DISK_FLAG_SKIP_MIRROR_ACTIVATION = MIRROR_VIRTUAL_DISK_FLAG.SKIP_MIRROR_ACTIVATION;
pub const MIRROR_VIRTUAL_DISK_FLAG_ENABLE_SMB_COMPRESSION = MIRROR_VIRTUAL_DISK_FLAG.ENABLE_SMB_COMPRESSION;
pub const MIRROR_VIRTUAL_DISK_FLAG_IS_LIVE_MIGRATION = MIRROR_VIRTUAL_DISK_FLAG.IS_LIVE_MIGRATION;
pub const QUERY_CHANGES_VIRTUAL_DISK_RANGE = extern struct {
ByteOffset: u64,
ByteLength: u64,
Reserved: u64,
};
pub const QUERY_CHANGES_VIRTUAL_DISK_FLAG = enum(u32) {
E = 0,
_,
pub fn initFlags(o: struct {
E: u1 = 0,
}) QUERY_CHANGES_VIRTUAL_DISK_FLAG {
return @intToEnum(QUERY_CHANGES_VIRTUAL_DISK_FLAG,
(if (o.E == 1) @enumToInt(QUERY_CHANGES_VIRTUAL_DISK_FLAG.E) else 0)
);
}
};
pub const QUERY_CHANGES_VIRTUAL_DISK_FLAG_NONE = QUERY_CHANGES_VIRTUAL_DISK_FLAG.E;
pub const TAKE_SNAPSHOT_VHDSET_FLAG = enum(u32) {
NONE = 0,
WRITEABLE = 1,
_,
pub fn initFlags(o: struct {
NONE: u1 = 0,
WRITEABLE: u1 = 0,
}) TAKE_SNAPSHOT_VHDSET_FLAG {
return @intToEnum(TAKE_SNAPSHOT_VHDSET_FLAG,
(if (o.NONE == 1) @enumToInt(TAKE_SNAPSHOT_VHDSET_FLAG.NONE) else 0)
| (if (o.WRITEABLE == 1) @enumToInt(TAKE_SNAPSHOT_VHDSET_FLAG.WRITEABLE) else 0)
);
}
};
pub const TAKE_SNAPSHOT_VHDSET_FLAG_NONE = TAKE_SNAPSHOT_VHDSET_FLAG.NONE;
pub const TAKE_SNAPSHOT_VHDSET_FLAG_WRITEABLE = TAKE_SNAPSHOT_VHDSET_FLAG.WRITEABLE;
pub const TAKE_SNAPSHOT_VHDSET_VERSION = enum(i32) {
UNSPECIFIED = 0,
@"1" = 1,
};
pub const TAKE_SNAPSHOT_VHDSET_VERSION_UNSPECIFIED = TAKE_SNAPSHOT_VHDSET_VERSION.UNSPECIFIED;
pub const TAKE_SNAPSHOT_VHDSET_VERSION_1 = TAKE_SNAPSHOT_VHDSET_VERSION.@"1";
pub const TAKE_SNAPSHOT_VHDSET_PARAMETERS = extern struct {
Version: TAKE_SNAPSHOT_VHDSET_VERSION,
Anonymous: extern union {
Version1: extern struct {
SnapshotId: Guid,
},
},
};
pub const DELETE_SNAPSHOT_VHDSET_FLAG = enum(u32) {
NONE = 0,
PERSIST_RCT = 1,
_,
pub fn initFlags(o: struct {
NONE: u1 = 0,
PERSIST_RCT: u1 = 0,
}) DELETE_SNAPSHOT_VHDSET_FLAG {
return @intToEnum(DELETE_SNAPSHOT_VHDSET_FLAG,
(if (o.NONE == 1) @enumToInt(DELETE_SNAPSHOT_VHDSET_FLAG.NONE) else 0)
| (if (o.PERSIST_RCT == 1) @enumToInt(DELETE_SNAPSHOT_VHDSET_FLAG.PERSIST_RCT) else 0)
);
}
};
pub const DELETE_SNAPSHOT_VHDSET_FLAG_NONE = DELETE_SNAPSHOT_VHDSET_FLAG.NONE;
pub const DELETE_SNAPSHOT_VHDSET_FLAG_PERSIST_RCT = DELETE_SNAPSHOT_VHDSET_FLAG.PERSIST_RCT;
pub const DELETE_SNAPSHOT_VHDSET_VERSION = enum(i32) {
UNSPECIFIED = 0,
@"1" = 1,
};
pub const DELETE_SNAPSHOT_VHDSET_VERSION_UNSPECIFIED = DELETE_SNAPSHOT_VHDSET_VERSION.UNSPECIFIED;
pub const DELETE_SNAPSHOT_VHDSET_VERSION_1 = DELETE_SNAPSHOT_VHDSET_VERSION.@"1";
pub const DELETE_SNAPSHOT_VHDSET_PARAMETERS = extern struct {
Version: DELETE_SNAPSHOT_VHDSET_VERSION,
Anonymous: extern union {
Version1: extern struct {
SnapshotId: Guid,
},
},
};
pub const MODIFY_VHDSET_VERSION = enum(i32) {
UNSPECIFIED = 0,
SNAPSHOT_PATH = 1,
REMOVE_SNAPSHOT = 2,
DEFAULT_SNAPSHOT_PATH = 3,
};
pub const MODIFY_VHDSET_UNSPECIFIED = MODIFY_VHDSET_VERSION.UNSPECIFIED;
pub const MODIFY_VHDSET_SNAPSHOT_PATH = MODIFY_VHDSET_VERSION.SNAPSHOT_PATH;
pub const MODIFY_VHDSET_REMOVE_SNAPSHOT = MODIFY_VHDSET_VERSION.REMOVE_SNAPSHOT;
pub const MODIFY_VHDSET_DEFAULT_SNAPSHOT_PATH = MODIFY_VHDSET_VERSION.DEFAULT_SNAPSHOT_PATH;
pub const MODIFY_VHDSET_FLAG = enum(u32) {
NONE = 0,
WRITEABLE_SNAPSHOT = 1,
_,
pub fn initFlags(o: struct {
NONE: u1 = 0,
WRITEABLE_SNAPSHOT: u1 = 0,
}) MODIFY_VHDSET_FLAG {
return @intToEnum(MODIFY_VHDSET_FLAG,
(if (o.NONE == 1) @enumToInt(MODIFY_VHDSET_FLAG.NONE) else 0)
| (if (o.WRITEABLE_SNAPSHOT == 1) @enumToInt(MODIFY_VHDSET_FLAG.WRITEABLE_SNAPSHOT) else 0)
);
}
};
pub const MODIFY_VHDSET_FLAG_NONE = MODIFY_VHDSET_FLAG.NONE;
pub const MODIFY_VHDSET_FLAG_WRITEABLE_SNAPSHOT = MODIFY_VHDSET_FLAG.WRITEABLE_SNAPSHOT;
pub const MODIFY_VHDSET_PARAMETERS = extern struct {
Version: MODIFY_VHDSET_VERSION,
Anonymous: extern union {
SnapshotPath: extern struct {
SnapshotId: Guid,
SnapshotFilePath: ?[*:0]const u16,
},
SnapshotId: Guid,
DefaultFilePath: ?[*:0]const u16,
},
};
pub const APPLY_SNAPSHOT_VHDSET_FLAG = enum(u32) {
NONE = 0,
WRITEABLE = 1,
_,
pub fn initFlags(o: struct {
NONE: u1 = 0,
WRITEABLE: u1 = 0,
}) APPLY_SNAPSHOT_VHDSET_FLAG {
return @intToEnum(APPLY_SNAPSHOT_VHDSET_FLAG,
(if (o.NONE == 1) @enumToInt(APPLY_SNAPSHOT_VHDSET_FLAG.NONE) else 0)
| (if (o.WRITEABLE == 1) @enumToInt(APPLY_SNAPSHOT_VHDSET_FLAG.WRITEABLE) else 0)
);
}
};
pub const APPLY_SNAPSHOT_VHDSET_FLAG_NONE = APPLY_SNAPSHOT_VHDSET_FLAG.NONE;
pub const APPLY_SNAPSHOT_VHDSET_FLAG_WRITEABLE = APPLY_SNAPSHOT_VHDSET_FLAG.WRITEABLE;
pub const APPLY_SNAPSHOT_VHDSET_VERSION = enum(i32) {
UNSPECIFIED = 0,
@"1" = 1,
};
pub const APPLY_SNAPSHOT_VHDSET_VERSION_UNSPECIFIED = APPLY_SNAPSHOT_VHDSET_VERSION.UNSPECIFIED;
pub const APPLY_SNAPSHOT_VHDSET_VERSION_1 = APPLY_SNAPSHOT_VHDSET_VERSION.@"1";
pub const APPLY_SNAPSHOT_VHDSET_PARAMETERS = extern struct {
Version: APPLY_SNAPSHOT_VHDSET_VERSION,
Anonymous: extern union {
Version1: extern struct {
SnapshotId: Guid,
LeafSnapshotId: Guid,
},
},
};
pub const RAW_SCSI_VIRTUAL_DISK_FLAG = enum(u32) {
E = 0,
_,
pub fn initFlags(o: struct {
E: u1 = 0,
}) RAW_SCSI_VIRTUAL_DISK_FLAG {
return @intToEnum(RAW_SCSI_VIRTUAL_DISK_FLAG,
(if (o.E == 1) @enumToInt(RAW_SCSI_VIRTUAL_DISK_FLAG.E) else 0)
);
}
};
pub const RAW_SCSI_VIRTUAL_DISK_FLAG_NONE = RAW_SCSI_VIRTUAL_DISK_FLAG.E;
pub const RAW_SCSI_VIRTUAL_DISK_VERSION = enum(i32) {
UNSPECIFIED = 0,
@"1" = 1,
};
pub const RAW_SCSI_VIRTUAL_DISK_VERSION_UNSPECIFIED = RAW_SCSI_VIRTUAL_DISK_VERSION.UNSPECIFIED;
pub const RAW_SCSI_VIRTUAL_DISK_VERSION_1 = RAW_SCSI_VIRTUAL_DISK_VERSION.@"1";
pub const RAW_SCSI_VIRTUAL_DISK_PARAMETERS = extern struct {
Version: RAW_SCSI_VIRTUAL_DISK_VERSION,
Anonymous: extern union {
Version1: extern struct {
RSVDHandle: BOOL,
DataIn: u8,
CdbLength: u8,
SenseInfoLength: u8,
SrbFlags: u32,
DataTransferLength: u32,
DataBuffer: ?*anyopaque,
SenseInfo: ?*u8,
Cdb: ?*u8,
},
},
};
pub const RAW_SCSI_VIRTUAL_DISK_RESPONSE = extern struct {
Version: RAW_SCSI_VIRTUAL_DISK_VERSION,
Anonymous: extern union {
Version1: extern struct {
ScsiStatus: u8,
SenseInfoLength: u8,
DataTransferLength: u32,
},
},
};
pub const FORK_VIRTUAL_DISK_VERSION = enum(i32) {
UNSPECIFIED = 0,
@"1" = 1,
};
pub const FORK_VIRTUAL_DISK_VERSION_UNSPECIFIED = FORK_VIRTUAL_DISK_VERSION.UNSPECIFIED;
pub const FORK_VIRTUAL_DISK_VERSION_1 = FORK_VIRTUAL_DISK_VERSION.@"1";
pub const FORK_VIRTUAL_DISK_PARAMETERS = extern struct {
Version: FORK_VIRTUAL_DISK_VERSION,
Anonymous: extern union {
Version1: extern struct {
ForkedVirtualDiskPath: ?[*:0]const u16,
},
},
};
pub const FORK_VIRTUAL_DISK_FLAG = enum(u32) {
NONE = 0,
EXISTING_FILE = 1,
_,
pub fn initFlags(o: struct {
NONE: u1 = 0,
EXISTING_FILE: u1 = 0,
}) FORK_VIRTUAL_DISK_FLAG {
return @intToEnum(FORK_VIRTUAL_DISK_FLAG,
(if (o.NONE == 1) @enumToInt(FORK_VIRTUAL_DISK_FLAG.NONE) else 0)
| (if (o.EXISTING_FILE == 1) @enumToInt(FORK_VIRTUAL_DISK_FLAG.EXISTING_FILE) else 0)
);
}
};
pub const FORK_VIRTUAL_DISK_FLAG_NONE = FORK_VIRTUAL_DISK_FLAG.NONE;
pub const FORK_VIRTUAL_DISK_FLAG_EXISTING_FILE = FORK_VIRTUAL_DISK_FLAG.EXISTING_FILE;
//--------------------------------------------------------------------------------
// Section: Functions (29)
//--------------------------------------------------------------------------------
// TODO: this type is limited to platform 'windows6.1'
pub extern "VirtDisk" fn OpenVirtualDisk(
VirtualStorageType: ?*VIRTUAL_STORAGE_TYPE,
Path: ?[*:0]const u16,
VirtualDiskAccessMask: VIRTUAL_DISK_ACCESS_MASK,
Flags: OPEN_VIRTUAL_DISK_FLAG,
Parameters: ?*OPEN_VIRTUAL_DISK_PARAMETERS,
Handle: ?*?HANDLE,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.1'
pub extern "VirtDisk" fn CreateVirtualDisk(
VirtualStorageType: ?*VIRTUAL_STORAGE_TYPE,
Path: ?[*:0]const u16,
VirtualDiskAccessMask: VIRTUAL_DISK_ACCESS_MASK,
SecurityDescriptor: ?*SECURITY_DESCRIPTOR,
Flags: CREATE_VIRTUAL_DISK_FLAG,
ProviderSpecificFlags: u32,
Parameters: ?*CREATE_VIRTUAL_DISK_PARAMETERS,
Overlapped: ?*OVERLAPPED,
Handle: ?*?HANDLE,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.1'
pub extern "VirtDisk" fn AttachVirtualDisk(
VirtualDiskHandle: ?HANDLE,
SecurityDescriptor: ?*SECURITY_DESCRIPTOR,
Flags: ATTACH_VIRTUAL_DISK_FLAG,
ProviderSpecificFlags: u32,
Parameters: ?*ATTACH_VIRTUAL_DISK_PARAMETERS,
Overlapped: ?*OVERLAPPED,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.1'
pub extern "VirtDisk" fn DetachVirtualDisk(
VirtualDiskHandle: ?HANDLE,
Flags: DETACH_VIRTUAL_DISK_FLAG,
ProviderSpecificFlags: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.1'
pub extern "VirtDisk" fn GetVirtualDiskPhysicalPath(
VirtualDiskHandle: ?HANDLE,
DiskPathSizeInBytes: ?*u32,
// TODO: what to do with BytesParamIndex 1?
DiskPath: ?PWSTR,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "VirtDisk" fn GetAllAttachedVirtualDiskPhysicalPaths(
PathsBufferSizeInBytes: ?*u32,
// TODO: what to do with BytesParamIndex 0?
PathsBuffer: ?PWSTR,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.1'
pub extern "VirtDisk" fn GetStorageDependencyInformation(
ObjectHandle: ?HANDLE,
Flags: GET_STORAGE_DEPENDENCY_FLAG,
StorageDependencyInfoSize: u32,
StorageDependencyInfo: ?*STORAGE_DEPENDENCY_INFO,
SizeUsed: ?*u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.1'
pub extern "VirtDisk" fn GetVirtualDiskInformation(
VirtualDiskHandle: ?HANDLE,
VirtualDiskInfoSize: ?*u32,
// TODO: what to do with BytesParamIndex 1?
VirtualDiskInfo: ?*GET_VIRTUAL_DISK_INFO,
SizeUsed: ?*u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.1'
pub extern "VirtDisk" fn SetVirtualDiskInformation(
VirtualDiskHandle: ?HANDLE,
VirtualDiskInfo: ?*SET_VIRTUAL_DISK_INFO,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows8.0'
pub extern "VirtDisk" fn EnumerateVirtualDiskMetadata(
VirtualDiskHandle: ?HANDLE,
NumberOfItems: ?*u32,
Items: [*]Guid,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows8.0'
pub extern "VirtDisk" fn GetVirtualDiskMetadata(
VirtualDiskHandle: ?HANDLE,
Item: ?*const Guid,
MetaDataSize: ?*u32,
// TODO: what to do with BytesParamIndex 2?
MetaData: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows8.0'
pub extern "VirtDisk" fn SetVirtualDiskMetadata(
VirtualDiskHandle: ?HANDLE,
Item: ?*const Guid,
MetaDataSize: u32,
// TODO: what to do with BytesParamIndex 2?
MetaData: ?*const anyopaque,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows8.0'
pub extern "VirtDisk" fn DeleteVirtualDiskMetadata(
VirtualDiskHandle: ?HANDLE,
Item: ?*const Guid,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.1'
pub extern "VirtDisk" fn GetVirtualDiskOperationProgress(
VirtualDiskHandle: ?HANDLE,
Overlapped: ?*OVERLAPPED,
Progress: ?*VIRTUAL_DISK_PROGRESS,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.1'
pub extern "VirtDisk" fn CompactVirtualDisk(
VirtualDiskHandle: ?HANDLE,
Flags: COMPACT_VIRTUAL_DISK_FLAG,
Parameters: ?*COMPACT_VIRTUAL_DISK_PARAMETERS,
Overlapped: ?*OVERLAPPED,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.1'
pub extern "VirtDisk" fn MergeVirtualDisk(
VirtualDiskHandle: ?HANDLE,
Flags: MERGE_VIRTUAL_DISK_FLAG,
Parameters: ?*MERGE_VIRTUAL_DISK_PARAMETERS,
Overlapped: ?*OVERLAPPED,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.1'
pub extern "VirtDisk" fn ExpandVirtualDisk(
VirtualDiskHandle: ?HANDLE,
Flags: EXPAND_VIRTUAL_DISK_FLAG,
Parameters: ?*EXPAND_VIRTUAL_DISK_PARAMETERS,
Overlapped: ?*OVERLAPPED,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows8.0'
pub extern "VirtDisk" fn ResizeVirtualDisk(
VirtualDiskHandle: ?HANDLE,
Flags: RESIZE_VIRTUAL_DISK_FLAG,
Parameters: ?*RESIZE_VIRTUAL_DISK_PARAMETERS,
Overlapped: ?*OVERLAPPED,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows8.0'
pub extern "VirtDisk" fn MirrorVirtualDisk(
VirtualDiskHandle: ?HANDLE,
Flags: MIRROR_VIRTUAL_DISK_FLAG,
Parameters: ?*MIRROR_VIRTUAL_DISK_PARAMETERS,
Overlapped: ?*OVERLAPPED,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows8.0'
pub extern "VirtDisk" fn BreakMirrorVirtualDisk(
VirtualDiskHandle: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows8.0'
pub extern "VirtDisk" fn AddVirtualDiskParent(
VirtualDiskHandle: ?HANDLE,
ParentPath: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows10.0.10240'
pub extern "VirtDisk" fn QueryChangesVirtualDisk(
VirtualDiskHandle: ?HANDLE,
ChangeTrackingId: ?[*:0]const u16,
ByteOffset: u64,
ByteLength: u64,
Flags: QUERY_CHANGES_VIRTUAL_DISK_FLAG,
Ranges: [*]QUERY_CHANGES_VIRTUAL_DISK_RANGE,
RangeCount: ?*u32,
ProcessedLength: ?*u64,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows10.0.10240'
pub extern "VirtDisk" fn TakeSnapshotVhdSet(
VirtualDiskHandle: ?HANDLE,
Parameters: ?*const TAKE_SNAPSHOT_VHDSET_PARAMETERS,
Flags: TAKE_SNAPSHOT_VHDSET_FLAG,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows10.0.10240'
pub extern "VirtDisk" fn DeleteSnapshotVhdSet(
VirtualDiskHandle: ?HANDLE,
Parameters: ?*const DELETE_SNAPSHOT_VHDSET_PARAMETERS,
Flags: DELETE_SNAPSHOT_VHDSET_FLAG,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows10.0.10240'
pub extern "VirtDisk" fn ModifyVhdSet(
VirtualDiskHandle: ?HANDLE,
Parameters: ?*const MODIFY_VHDSET_PARAMETERS,
Flags: MODIFY_VHDSET_FLAG,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows10.0.10240'
pub extern "VirtDisk" fn ApplySnapshotVhdSet(
VirtualDiskHandle: ?HANDLE,
Parameters: ?*const APPLY_SNAPSHOT_VHDSET_PARAMETERS,
Flags: APPLY_SNAPSHOT_VHDSET_FLAG,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows10.0.10240'
pub extern "VirtDisk" fn RawSCSIVirtualDisk(
VirtualDiskHandle: ?HANDLE,
Parameters: ?*const RAW_SCSI_VIRTUAL_DISK_PARAMETERS,
Flags: RAW_SCSI_VIRTUAL_DISK_FLAG,
Response: ?*RAW_SCSI_VIRTUAL_DISK_RESPONSE,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "VirtDisk" fn ForkVirtualDisk(
VirtualDiskHandle: ?HANDLE,
Flags: FORK_VIRTUAL_DISK_FLAG,
Parameters: ?*const FORK_VIRTUAL_DISK_PARAMETERS,
Overlapped: ?*OVERLAPPED,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "VirtDisk" fn CompleteForkVirtualDisk(
VirtualDiskHandle: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) u32;
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (0)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../zig.zig").unicode_mode) {
.ansi => struct {
},
.wide => struct {
},
.unspecified => if (@import("builtin").is_test) struct {
} else struct {
},
};
//--------------------------------------------------------------------------------
// Section: Imports (6)
//--------------------------------------------------------------------------------
const Guid = @import("../zig.zig").Guid;
const BOOL = @import("../foundation.zig").BOOL;
const HANDLE = @import("../foundation.zig").HANDLE;
const OVERLAPPED = @import("../system/io.zig").OVERLAPPED;
const PWSTR = @import("../foundation.zig").PWSTR;
const SECURITY_DESCRIPTOR = @import("../security.zig").SECURITY_DESCRIPTOR;
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/vhd.zig |
pub const MIN_EVENT = @as(u32, 100);
pub const BEGIN_NESTED_SYSTEM_CHANGE_NORP = @as(u32, 104);
pub const MAX_EVENT = @as(u32, 104);
pub const MIN_RPT = @as(u32, 0);
pub const DESKTOP_SETTING = @as(u32, 2);
pub const ACCESSIBILITY_SETTING = @as(u32, 3);
pub const OE_SETTING = @as(u32, 4);
pub const APPLICATION_RUN = @as(u32, 5);
pub const RESTORE = @as(u32, 6);
pub const CHECKPOINT = @as(u32, 7);
pub const WINDOWS_SHUTDOWN = @as(u32, 8);
pub const WINDOWS_BOOT = @as(u32, 9);
pub const FIRSTRUN = @as(u32, 11);
pub const BACKUP_RECOVERY = @as(u32, 14);
pub const BACKUP = @as(u32, 15);
pub const MANUAL_CHECKPOINT = @as(u32, 16);
pub const WINDOWS_UPDATE = @as(u32, 17);
pub const CRITICAL_UPDATE = @as(u32, 18);
pub const MAX_RPT = @as(u32, 18);
pub const MAX_DESC = @as(u32, 64);
pub const MAX_DESC_W = @as(u32, 256);
//--------------------------------------------------------------------------------
// Section: Types (6)
//--------------------------------------------------------------------------------
pub const RESTOREPOINTINFO_TYPE = enum(u32) {
APPLICATION_INSTALL = 0,
APPLICATION_UNINSTALL = 1,
DEVICE_DRIVER_INSTALL = 10,
MODIFY_SETTINGS = 12,
CANCELLED_OPERATION = 13,
};
pub const APPLICATION_INSTALL = RESTOREPOINTINFO_TYPE.APPLICATION_INSTALL;
pub const APPLICATION_UNINSTALL = RESTOREPOINTINFO_TYPE.APPLICATION_UNINSTALL;
pub const DEVICE_DRIVER_INSTALL = RESTOREPOINTINFO_TYPE.DEVICE_DRIVER_INSTALL;
pub const MODIFY_SETTINGS = RESTOREPOINTINFO_TYPE.MODIFY_SETTINGS;
pub const CANCELLED_OPERATION = RESTOREPOINTINFO_TYPE.CANCELLED_OPERATION;
pub const RESTOREPOINTINFO_EVENT_TYPE = enum(u32) {
BEGIN_NESTED_SYSTEM_CHANGE = 102,
BEGIN_SYSTEM_CHANGE = 100,
END_NESTED_SYSTEM_CHANGE = 103,
END_SYSTEM_CHANGE = 101,
};
pub const BEGIN_NESTED_SYSTEM_CHANGE = RESTOREPOINTINFO_EVENT_TYPE.BEGIN_NESTED_SYSTEM_CHANGE;
pub const BEGIN_SYSTEM_CHANGE = RESTOREPOINTINFO_EVENT_TYPE.BEGIN_SYSTEM_CHANGE;
pub const END_NESTED_SYSTEM_CHANGE = RESTOREPOINTINFO_EVENT_TYPE.END_NESTED_SYSTEM_CHANGE;
pub const END_SYSTEM_CHANGE = RESTOREPOINTINFO_EVENT_TYPE.END_SYSTEM_CHANGE;
pub const RESTOREPOINTINFOA = packed struct {
dwEventType: RESTOREPOINTINFO_EVENT_TYPE,
dwRestorePtType: RESTOREPOINTINFO_TYPE,
llSequenceNumber: i64,
szDescription: [64]CHAR,
};
pub const RESTOREPOINTINFOW = packed struct {
dwEventType: RESTOREPOINTINFO_EVENT_TYPE,
dwRestorePtType: RESTOREPOINTINFO_TYPE,
llSequenceNumber: i64,
szDescription: [256]u16,
};
pub const _RESTOREPTINFOEX = packed struct {
ftCreation: FILETIME,
dwEventType: u32,
dwRestorePtType: u32,
dwRPNum: u32,
szDescription: [256]u16,
};
pub const STATEMGRSTATUS = packed struct {
nStatus: u32,
llSequenceNumber: i64,
};
//--------------------------------------------------------------------------------
// Section: Functions (2)
//--------------------------------------------------------------------------------
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "sfc" fn SRSetRestorePointA(
pRestorePtSpec: ?*RESTOREPOINTINFOA,
pSMgrStatus: ?*STATEMGRSTATUS,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "sfc" fn SRSetRestorePointW(
pRestorePtSpec: ?*RESTOREPOINTINFOW,
pSMgrStatus: ?*STATEMGRSTATUS,
) callconv(@import("std").os.windows.WINAPI) BOOL;
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (2)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../zig.zig").unicode_mode) {
.ansi => struct {
pub const RESTOREPOINTINFO = thismodule.RESTOREPOINTINFOA;
pub const SRSetRestorePoint = thismodule.SRSetRestorePointA;
},
.wide => struct {
pub const RESTOREPOINTINFO = thismodule.RESTOREPOINTINFOW;
pub const SRSetRestorePoint = thismodule.SRSetRestorePointW;
},
.unspecified => if (@import("builtin").is_test) struct {
pub const RESTOREPOINTINFO = *opaque{};
pub const SRSetRestorePoint = *opaque{};
} else struct {
pub const RESTOREPOINTINFO = @compileError("'RESTOREPOINTINFO' requires that UNICODE be set to true or false in the root module");
pub const SRSetRestorePoint = @compileError("'SRSetRestorePoint' requires that UNICODE be set to true or false in the root module");
},
};
//--------------------------------------------------------------------------------
// Section: Imports (3)
//--------------------------------------------------------------------------------
const BOOL = @import("../foundation.zig").BOOL;
const CHAR = @import("../foundation.zig").CHAR;
const FILETIME = @import("../foundation.zig").FILETIME;
test {
@setEvalBranchQuota(
@import("std").meta.declarations(@This()).len * 3
);
// reference all the pub declarations
if (!@import("builtin").is_test) return;
inline for (@import("std").meta.declarations(@This())) |decl| {
if (decl.is_pub) {
_ = decl;
}
}
} | win32/system/restore.zig |
const std = @import("std");
const with_trace = true;
const assert = std.debug.assert;
fn trace(comptime fmt: []const u8, args: anytype) void {
if (with_trace) std.debug.print(fmt, args);
}
const SpellEffect = struct {
damage: i32 = 0,
armor: i32 = 0,
heal: i32 = 0,
manabonus: i32 = 0,
};
const Spell = struct {
cost: i32,
// effect: i32,
duration: i32 = 0,
};
const Carac = struct {
points: i32,
damage: i32,
armor: i32,
mana: i32,
};
const effects = [_]SpellEffect{
.{ .damage = 4 },
.{ .damage = 2, .heal = 2 },
.{ .armor = 7 },
.{ .damage = 3 },
.{ .manabonus = 101 },
};
const spells = [_]Spell{
.{ .cost = 53 },
.{ .cost = 73 },
.{ .cost = 113, .duration = 6 },
.{ .cost = 173, .duration = 6 },
.{ .cost = 229, .duration = 5 },
};
fn apply_effect(boss: *Carac, player: *Carac, idx: usize) void {
const e = effects[idx];
boss.points -= e.damage;
player.armor += e.armor;
player.mana += e.manabonus;
player.points += e.heal;
}
fn playfight_bfs(boss: Carac, player: Carac, active_spells: [5]i32, turn: u32) ?i32 {
const spaces = " ";
const playerturn = (turn % 2) == 1;
// const padding = spaces[0 .. (turn - 1) * 2];
var b0 = boss;
var p0 = player;
var as0 = [5]i32{ 0, 0, active_spells[2], active_spells[3], active_spells[4] };
// trace("{}turn={}, spells={},{},{}, player: {},{},{}, boss: {}\n", padding, turn, as0[2], as0[3], as0[4], p0.points, p0.mana, p0.armor, b0.points);
p0.armor = 0;
for (as0) |*duration, i| {
if (duration.* > 0) {
apply_effect(&b0, &p0, i);
duration.* -= 1;
}
}
const hardmode = true;
if (hardmode and playerturn) {
p0.points -= 1;
}
if (p0.points <= 0)
return null;
if (b0.points <= 0)
return 0;
if (playerturn) {
var bestcost: ?i32 = null;
for (spells) |s, i| {
var b1 = b0;
var p1 = p0;
var as1 = [5]i32{ 0, 0, as0[2], as0[3], as0[4] };
if (s.duration == 0 and s.cost <= p1.mana) {
// trace("{}player casts: {}\n", padding, i);
p1.mana -= s.cost;
apply_effect(&b1, &p1, i);
if (b1.points <= 0) {
if (bestcost == null or s.cost < bestcost.?)
bestcost = s.cost;
} else {
if (playfight_bfs(b1, p1, as1, turn + 1)) |cost| {
if (bestcost == null or cost + s.cost < bestcost.?)
bestcost = cost + s.cost;
}
}
} else if (as1[i] == 0 and s.cost <= p1.mana) {
// trace("{}player casts: {}\n", padding, i);
p1.mana -= s.cost;
as1[i] = s.duration;
if (playfight_bfs(b1, p1, as1, turn + 1)) |cost| {
if (bestcost == null or cost + s.cost < bestcost.?)
bestcost = cost + s.cost;
}
}
}
return bestcost;
} else {
var dmg = b0.damage - p0.armor;
if (dmg <= 0)
dmg = 1;
p0.points -= dmg;
// trace("{}boss deals {}\n", padding, dmg);
if (p0.points <= 0)
return null;
return playfight_bfs(b0, p0, as0, turn + 1);
}
}
pub fn main() anyerror!void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
const boss = Carac{ .points = 71, .damage = 10, .armor = 0, .mana = 0 };
const player = Carac{ .points = 50, .damage = 0, .armor = 0, .mana = 500 };
//const boss = Carac{ .points = 14, .damage = 8, .armor = 0, .mana = 0 };
//const player = Carac{ .points = 10, .damage = 0, .armor = 0, .mana = 250 };
const active_spells = [5]i32{ 0, 0, 0, 0, 0 };
const out = std.io.getStdOut().writer();
try out.print("ans = {}\n", playfight_bfs(boss, player, active_spells, 1));
// return error.SolutionNotFound;
} | 2015/day22.zig |
const std = @import("std");
fn score_bad(x: u8) usize {
if (x == ')') {
return 3;
} else if (x == ']') {
return 57;
} else if (x == '}') {
return 1197;
} else if (x == '>') {
return 25137;
} else {
return 100000000;
}
}
fn score_good(x: u8) usize {
if (x == '(') {
return 1;
} else if (x == '[') {
return 2;
} else if (x == '{') {
return 3;
} else {
return 4;
}
}
fn matches(a: u8, b: u8) bool {
return (a == '<' and b == '>') or
(a == '{' and b == '}') or
(a == '[' and b == ']') or
(a == '(' and b == ')');
}
pub fn main() !void {
var good_scores: [100]usize = undefined;
var gs_count: usize = 0;
const stdout = std.io.getStdOut().writer();
const stdin = &std.io.getStdIn().reader();
var buf: [256]u8 = undefined;
var lines: i32 = 0;
var chars: usize = 0;
var bad_score: usize = 0;
while (true) {
if (try stdin.readUntilDelimiterOrEof(buf[0..], '\n')) |user_input| {
var stack: [256]u8 = undefined;
var stack_ptr: usize = 0;
for (user_input) |ch| {
if ((ch == '{') or (ch == '[') or (ch == '<') or (ch == '(')) {
stack[stack_ptr] = ch;
stack_ptr += 1;
} else {
if (stack_ptr == 0 or !matches(stack[stack_ptr - 1], ch)) {
var bad = score_bad(ch);
bad_score += bad;
// try stdout.print("bad {c}/{c} {d} on line {d}\n", .{ stack[stack_ptr - 1], ch, bad, lines });
stack_ptr = 0;
break;
} else {
stack_ptr -= 1;
}
}
}
var gs: usize = 0;
var stack_size: usize = stack_ptr;
while (stack_ptr > 0) {
stack_ptr -= 1;
gs *= 5;
gs += score_good(stack[stack_ptr]);
}
if (0 < gs) {
good_scores[gs_count] = gs;
gs_count += 1;
}
} else {
break;
}
lines += 1;
}
// It's faster to do this by hand than it is to look up how to do it, apparently.
var i: usize = 0;
while (i < gs_count) {
var j: usize = 1;
while (j < gs_count) {
if (good_scores[j] < good_scores[j - 1]) {
var tmp: usize = good_scores[j];
good_scores[j] = good_scores[j - 1];
good_scores[j - 1] = tmp;
}
j += 1;
}
i += 1;
}
try stdout.print("part 1: {d}\n", .{bad_score});
try stdout.print("part 2: {d}\n", .{good_scores[gs_count / 2]});
} | 10/syntax_scoring.zig |
const std = @import("std");
const c = @import("../c_global.zig").c_imp;
// dross-zig
const Application = @import("application.zig").Application;
const Vector2 = @import("vector2.zig").Vector2;
// ---------------------------------------------------------
// -----------------------------------------
// - Input -
// -----------------------------------------
/// Input wrapper for GLFW
pub const Input = struct {
/// Returns true if the key in question is currently pressed.
pub fn keyPressed(key: DrossKey) bool {
var state = key_map.get(key).?;
return state == DrossInputState.Pressed or state == DrossInputState.Down;
}
/// Returns the f32 value version of getKeyPressed
pub fn keyPressedValue(key: DrossKey) f32 {
const key_pressed = keyPressed(key);
return @intToFloat(f32, @boolToInt(key_pressed));
}
/// Returns true if the key in question was just released.
pub fn keyReleased(key: DrossKey) bool {
return key_released_set.contains(key);
}
/// Returns the f32 value version of getKeyReleased
pub fn keyReleasedValue(key: DrossKey) f32 {
const key_released = keyReleased(key);
return @intToFloat(f32, @boolToInt(key_released));
}
/// Returns true if the key in question is registered has held
/// down (takes a few frames to register).
pub fn keyDown(key: DrossKey) bool {
var state = key_map.get(key).?;
return state == DrossInputState.Down;
}
/// Returns the f32 value version of getKeyDown
pub fn keyDownValue(key: DrossKey) f32 {
const key_down = keyDown(key);
return @intToFloat(f32, @boolToInt(key_down));
}
/// Returns the Mouse's position as a Vector2
/// The position is in screen coordinates (relative to the left bounds)
/// and top bounds of the content area.
pub fn mousePosition() Vector2 {
return mouse_position;
}
/// Returns if the mouse button has been pressed this frame
pub fn mouseButtonPressed(button: DrossMouseButton) bool {
const state = mouse_button_map.get(button).?;
return state == DrossInputState.Pressed or state == DrossInputState.Down;
}
/// Returns if the mouse button has been held down for multiple frames
/// NOTE(devon): Currently does not work!
/// TODO(devon): Create a timer to find out if the button has
/// be held down for multiple frames.
pub fn mouseButtonDown(button: DrossMouseButton) bool {
const state = mouse_button_map.get(button).?;
return state == DrossInputState.Down;
}
/// Returns if the mouse button has been released this frame
pub fn mouseButtonReleased(button: DrossMouseButton) bool {
return mouse_button_released_set.contains(button);
}
/// Allocates and builds the required components for the Input system.
/// Comments: Any allocated memory will be owned by the Input System.
pub fn new(allocator: *std.mem.Allocator) !void {
// Connect the callbacks
_ = c.glfwSetKeyCallback(Application.window(), keyCallback);
_ = c.glfwSetCursorPosCallback(Application.window(), mousePositionCallback);
_ = c.glfwSetMouseButtonCallback(Application.window(), mouseButtonCallback);
// Initialize the mouse-related
mouse_position = Vector2.new(0.0, 0.0);
mouse_button_map = std.AutoHashMap(DrossMouseButton, DrossInputState).init(allocator);
mouse_button_released_set = std.AutoHashMap(DrossMouseButton, void).init(allocator);
// Initialize the key maps
key_map = std.AutoHashMap(DrossKey, DrossInputState).init(allocator);
key_released_set = std.AutoHashMap(DrossKey, void).init(allocator);
// Populate the mouse button map
try mouse_button_map.put(DrossMouseButton.MouseButtonLeft, DrossInputState.Neutral);
try mouse_button_map.put(DrossMouseButton.MouseButtonRight, DrossInputState.Neutral);
try mouse_button_map.put(DrossMouseButton.MouseButtonMiddle, DrossInputState.Neutral);
try mouse_button_map.put(DrossMouseButton.MouseButton4, DrossInputState.Neutral);
try mouse_button_map.put(DrossMouseButton.MouseButton5, DrossInputState.Neutral);
try mouse_button_map.put(DrossMouseButton.MouseButton6, DrossInputState.Neutral);
try mouse_button_map.put(DrossMouseButton.MouseButton7, DrossInputState.Neutral);
try mouse_button_map.put(DrossMouseButton.MouseButton8, DrossInputState.Neutral);
// Populate the keyboard map
try key_map.put(DrossKey.KeyF1, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyF2, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyF3, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyF4, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyF5, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyF6, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyF7, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyF8, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyF9, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyF10, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyF11, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyF12, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyF13, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyF14, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyF15, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyF16, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyF17, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyF18, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyF19, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyF20, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyF21, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyF22, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyF23, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyF24, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyF25, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyA, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyB, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyC, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyD, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyE, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyF, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyG, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyH, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyI, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyJ, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyK, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyL, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyM, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyN, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyO, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyP, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyQ, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyR, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyS, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyT, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyU, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyV, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyW, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyX, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyY, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyZ, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyUnknown, DrossInputState.Neutral);
try key_map.put(DrossKey.KeySpace, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyApostrophe, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyComma, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyMinus, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyPeriod, DrossInputState.Neutral);
try key_map.put(DrossKey.KeySlash, DrossInputState.Neutral);
try key_map.put(DrossKey.Key0, DrossInputState.Neutral);
try key_map.put(DrossKey.Key1, DrossInputState.Neutral);
try key_map.put(DrossKey.Key2, DrossInputState.Neutral);
try key_map.put(DrossKey.Key3, DrossInputState.Neutral);
try key_map.put(DrossKey.Key4, DrossInputState.Neutral);
try key_map.put(DrossKey.Key5, DrossInputState.Neutral);
try key_map.put(DrossKey.Key6, DrossInputState.Neutral);
try key_map.put(DrossKey.Key7, DrossInputState.Neutral);
try key_map.put(DrossKey.Key8, DrossInputState.Neutral);
try key_map.put(DrossKey.Key9, DrossInputState.Neutral);
try key_map.put(DrossKey.KeySemiColon, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyEqual, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyLeftBracket, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyBackslash, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyRightBracket, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyBacktick, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyWorld1, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyWorld2, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyEscape, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyEnter, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyTab, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyBackspace, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyInsert, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyDelete, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyRight, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyLeft, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyUp, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyDown, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyPageUp, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyPageDown, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyHome, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyEnd, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyCapsLock, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyScrollLock, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyNumLock, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyPrintScreen, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyPause, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyKeypad0, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyKeypad1, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyKeypad2, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyKeypad3, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyKeypad4, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyKeypad5, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyKeypad6, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyKeypad7, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyKeypad8, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyKeypad9, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyKeypadDecimal, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyKeypadDivide, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyKeypadMultiply, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyKeypadSubtract, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyKeypadAdd, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyKeypadEnter, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyKeypadEqual, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyLeftShift, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyLeftControl, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyLeftAlt, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyLeftSuper, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyRightShift, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyRightControl, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyRightAlt, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyRightSuper, DrossInputState.Neutral);
try key_map.put(DrossKey.KeyMenu, DrossInputState.Neutral);
}
/// Frees any allocated memory that was required for Input
pub fn free(allocator: *std.mem.Allocator) void {
mouse_button_map.deinit();
mouse_button_released_set.deinit();
key_map.deinit();
key_released_set.deinit();
}
/// Updates the cached input states
pub fn updateInput() void {
updateReleasedMouseButtons();
updateReleasedKeys();
}
};
/// The possible states of input
const DrossInputState = enum(u8) {
/// If the input is in the default position and has not been changed
Neutral = 3,
/// If the input just pressed this frame
Pressed = c.GLFW_PRESS,
/// If the input was released this frame
Released = c.GLFW_RELEASE,
/// If the input was help for multiple frames
Down = c.GLFW_REPEAT,
};
// --------------------------------------------------------
// - Mouse Specific -
// --------------------------------------------------------
/// Stores the mouse position in screen coordinates (relative to the bound
/// of the content area).
var mouse_position: Vector2 = undefined;
/// Holds the most recent mouse button states
var mouse_button_map: std.AutoHashMap(DrossMouseButton, DrossInputState) = undefined;
/// A HashSet that holds any mouse buttons that have recently
/// been released. Released only needs to be held for frame or so, and
/// then any mouse buttons stored will be set to neutral.
var mouse_button_released_set: std.AutoHashMap(DrossMouseButton, void) = undefined;
/// Wrapper for the numerical values representing the mouse buttons.
pub const DrossMouseButton = enum(u8) {
MouseButtonLeft = 0,
MouseButtonRight = 1,
MouseButtonMiddle = 2,
MouseButton4 = 3,
MouseButton5 = 4,
MouseButton6 = 5,
MouseButton7 = 6,
MouseButton8 = 7,
};
/// Checks for any released mouse buttons from the previous frame, and resets them to neutral.
fn updateReleasedMouseButtons() void {
if (mouse_button_released_set.count() == 0) return;
// Cycle through the released map
var iterator = mouse_button_released_set.iterator();
while (iterator.next()) |entry| {
const key = entry.key;
// Check if the state of the mouse button has changed from released to pressed or down
const current_state = mouse_button_map.get(key).?;
// If it has not changed, then set it to neutral.
if (current_state == DrossInputState.Released) {
mouse_button_map.put(key, DrossInputState.Neutral) catch |err| {
if (err == error.OutOfMemory) @panic("[Input] Ran out of memory when trying put into mouse button state map!");
};
}
// Otherwise, leave the state alone and just remove all keys at the end.
_ = mouse_button_released_set.remove(key);
}
}
/// The mouse position callback for GLFW.
/// Comments: INTERNAL use only.
pub fn mousePositionCallback(window: ?*c.GLFWwindow, x_pos: f64, y_pos: f64) callconv(.C) void {
mouse_position = Vector2.new(@floatCast(f32, x_pos), @floatCast(f32, y_pos));
}
/// The mouse button callback for GLFW.
/// Comments: INTERNAL use only.
pub fn mouseButtonCallback(window: ?*c.GLFWwindow, button: c_int, action: c_int, mods: c_int) callconv(.C) void {
const button_convert = @intCast(u8, button);
const button_enum = @intToEnum(DrossMouseButton, button_convert);
if (mouse_button_map.contains(button_enum)) {
if (action == c.GLFW_PRESS) {
mouse_button_map.put(button_enum, DrossInputState.Pressed) catch |err| {
if (err == error.OutOfMemory) @panic("[Input] Ran out of memory when trying put into mouse button state map!");
};
} else if (action == c.GLFW_RELEASE) {
mouse_button_map.put(button_enum, DrossInputState.Released) catch |err| {
if (err == error.OutOfMemory) @panic("[Input] Ran out of memory when trying put into mouse button state map!");
};
mouse_button_released_set.put(button_enum, {}) catch |err| {
if (err == error.OutOfMemory) @panic("[Input] Ran out of memory when trying put into mouse button state map!");
};
} else if (action == c.GLFW_REPEAT) {
mouse_button_map.put(button_enum, DrossInputState.Down) catch |err| {
if (err == error.OutOfMemory) @panic("[Input] Ran out of memory when trying put into mouse button state map!");
};
}
}
}
// --------------------------------------------------------
// - Keyboard Specific -
// --------------------------------------------------------
/// Holds the most recent key states
var key_map: std.AutoHashMap(DrossKey, DrossInputState) = undefined;
/// A HashSet that holds any keys that have recently been released.
/// Released only needs to be held for frame or so, and
/// then any keys stored will be set to neutral.
var key_released_set: std.AutoHashMap(DrossKey, void) = undefined;
/// Checks for any released keys from the previous frame, and resets them to neutral.
fn updateReleasedKeys() void {
if (key_released_set.count() == 0) return;
// Cycle through the released map
var iterator = key_released_set.iterator();
while (iterator.next()) |entry| {
const key = entry.key;
// Check if the state of the key has changed from released to pressed or down
const current_state = key_map.get(key).?;
// If it has not changed, then set it to neutral.
if (current_state == DrossInputState.Released) {
key_map.put(key, DrossInputState.Neutral) catch |err| {
if (err == error.OutOfMemory) @panic("[Input] Ran out of memory when trying put into key state map!");
};
}
// Otherwise, leave the state alone and just remove all keys at the end.
_ = key_released_set.remove(key);
}
}
/// The key callback for GLFW so that we can more accurately keep track of key states.
/// Comments: INTERNAL use only.
pub fn keyCallback(window: ?*c.GLFWwindow, key: c_int, scancode: c_int, action: c_int, mods: c_int) callconv(.C) void {
const key_convert = @intCast(i16, key);
const key_enum = @intToEnum(DrossKey, key_convert);
if (key_map.contains(key_enum)) {
if (action == c.GLFW_PRESS) {
key_map.put(key_enum, DrossInputState.Pressed) catch |err| {
if (err == error.OutOfMemory) @panic("[Input] Ran out of memory when trying put into key state map!");
};
} else if (action == c.GLFW_RELEASE) {
key_map.put(key_enum, DrossInputState.Released) catch |err| {
if (err == error.OutOfMemory) @panic("[Input] Ran out of memory when trying put into key state map!");
};
key_released_set.put(key_enum, {}) catch |err| {
if (err == error.OutOfMemory) @panic("[Input] Ran out of memory when trying put into key state map!");
};
} else if (action == c.GLFW_REPEAT) {
key_map.put(key_enum, DrossInputState.Down) catch |err| {
if (err == error.OutOfMemory) @panic("[Input] Ran out of memory when trying put into key state map!");
};
}
}
}
/// Keycode wrapper for GLFW
// zig fmt: off
pub const DrossKey = enum(i16){
KeyUnknown = -1,
KeySpace = 32,
KeyApostrophe = 39, // '
KeyComma = 44, // ,
KeyMinus = 45, // -
KeyPeriod = 46, // .
KeySlash = 47, // /
Key0 = 48,
Key1 = 49,
Key2 = 50,
Key3 = 51,
Key4 = 52,
Key5 = 53,
Key6 = 54,
Key7 = 55,
Key8 = 56,
Key9 = 57,
KeySemiColon = 59, // ;
KeyEqual = 61, // =
KeyA = 65,
KeyB = 66,
KeyC = 67,
KeyD = 68,
KeyE = 69,
KeyF = 70,
KeyG = 71,
KeyH = 72,
KeyI = 73,
KeyJ = 74,
KeyK = 75,
KeyL = 76,
KeyM = 77,
KeyN = 78,
KeyO = 79,
KeyP = 80,
KeyQ = 81,
KeyR = 82,
KeyS = 83,
KeyT = 84,
KeyU = 85,
KeyV = 86,
KeyW = 87,
KeyX = 88,
KeyY = 89,
KeyZ = 90,
KeyLeftBracket = 91, // [
KeyBackslash = 92, // \
KeyRightBracket = 93, // ]
KeyBacktick = 96, // `
KeyWorld1 = 161, //non-US #1
KeyWorld2 = 162, //non-US #2
KeyEscape = 256,
KeyEnter = 257,
KeyTab = 258,
KeyBackspace = 259,
KeyInsert = 260,
KeyDelete = 261,
KeyRight = 262,
KeyLeft = 263,
KeyDown = 264,
KeyUp = 265,
KeyPageUp = 266,
KeyPageDown = 267,
KeyHome = 268,
KeyEnd = 269,
KeyCapsLock = 280,
KeyScrollLock = 281,
KeyNumLock = 282,
KeyPrintScreen = 283,
KeyPause = 284,
KeyF1 = 290,
KeyF2 = 291,
KeyF3 = 292,
KeyF4 = 293,
KeyF5 = 294,
KeyF6 = 295,
KeyF7 = 296,
KeyF8 = 297,
KeyF9 = 298,
KeyF10 = 299,
KeyF11 = 300,
KeyF12 = 301,
KeyF13 = 302,
KeyF14 = 303,
KeyF15 = 304,
KeyF16 = 305,
KeyF17 = 306,
KeyF18 = 307,
KeyF19 = 308,
KeyF20 = 309,
KeyF21 = 310,
KeyF22 = 311,
KeyF23 = 312,
KeyF24 = 313,
KeyF25 = 314,
KeyKeypad0 = 320,
KeyKeypad1 = 321,
KeyKeypad2 = 322,
KeyKeypad3 = 323,
KeyKeypad4 = 324,
KeyKeypad5 = 325,
KeyKeypad6 = 326,
KeyKeypad7 = 327,
KeyKeypad8 = 328,
KeyKeypad9 = 329,
KeyKeypadDecimal = 330,
KeyKeypadDivide = 331,
KeyKeypadMultiply = 332,
KeyKeypadSubtract = 333,
KeyKeypadAdd = 334,
KeyKeypadEnter = 335,
KeyKeypadEqual = 336,
KeyLeftShift = 340,
KeyLeftControl = 341,
KeyLeftAlt = 342,
KeyLeftSuper = 343,
KeyRightShift = 344,
KeyRightControl = 345,
KeyRightAlt = 346,
KeyRightSuper = 347,
KeyMenu = 348,
}; | src/core/input.zig |
const std = @import("std");
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
const math = std.math;
const approxEq = math.approxEq;
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const Buffer = std.Buffer;
const fixedBufferStream = std.io.fixedBufferStream;
pub const Pos = struct {
x: isize,
y: isize,
const Self = @This();
pub fn eq(a: Self, b: Self) bool {
return a.x == b.x and a.y == b.y;
}
};
pub fn pos(x: isize, y: isize) Pos {
return Pos{ .x = x, .y = y };
}
fn absDiff(x: isize, y: isize) isize {
return if (x > y) x - y else y - x;
}
fn diff(x: isize, y: isize) isize {
return x - y;
}
fn sign(x: isize) isize {
if (x > 0) {
return 1;
} else if (x < 0) {
return -1;
} else {
return 0;
}
}
fn divToFloat(x: isize, y: isize) f64 {
return @intToFloat(f64, x) / @intToFloat(f64, y);
}
pub fn obstructs(origin: Pos, dest: Pos, obstr: Pos) bool {
// the possible obstruction must be nearer
if (absDiff(origin.x, dest.x) < absDiff(origin.x, obstr.x))
return false;
if (absDiff(origin.y, dest.y) < absDiff(origin.y, obstr.y))
return false;
const origin_dest_x = diff(dest.x, origin.x);
const origin_obstr_x = diff(obstr.x, origin.x);
if (sign(origin_dest_x) != sign(origin_obstr_x))
return false;
const origin_dest_y = diff(dest.y, origin.y);
const origin_obstr_y = diff(obstr.y, origin.y);
if (sign(origin_dest_y) != sign(origin_obstr_y))
return false;
// the multiple of x and y must be the same
if (origin_dest_x == 0) {
return origin_obstr_x == 0;
} else if (origin_dest_y == 0) {
return origin_obstr_y == 0;
} else {
const epsilon = 0.000001;
return approxEq(f64, divToFloat(origin_obstr_x, origin_dest_x), divToFloat(origin_obstr_y, origin_dest_y), epsilon);
}
}
test "obstruction" {
expectEqual(true, obstructs(pos(0, 0), pos(4, 4), pos(2, 2)));
expectEqual(true, obstructs(pos(0, 0), pos(6, 6), pos(2, 2)));
expectEqual(true, obstructs(pos(0, 0), pos(6, 6), pos(4, 4)));
expectEqual(false, obstructs(pos(0, 0), pos(2, 2), pos(4, 4)));
expectEqual(false, obstructs(pos(2, 2), pos(0, 0), pos(4, 4)));
expectEqual(false, obstructs(pos(2, 2), pos(4, 0), pos(4, 4)));
expectEqual(true, obstructs(pos(0, 0), pos(2, 6), pos(1, 3)));
expectEqual(false, obstructs(pos(0, 0), pos(2, 7), pos(1, 3)));
expectEqual(true, obstructs(pos(0, 0), pos(0, 5), pos(0, 2)));
expectEqual(true, obstructs(pos(0, 0), pos(5, 0), pos(2, 0)));
}
fn rotatedAngle(vector: Pos) f64 {
const angle = math.atan2(f64, @intToFloat(f64, -vector.y), @intToFloat(f64, vector.x));
const angle_2pi = if (angle < 0.0) 2.0 * math.pi + angle else angle;
const rotated = @mod((-angle_2pi + (math.pi / 2.0)), (2.0 * math.pi));
return rotated;
}
test "rotatedAngle" {
const epsilon = 0.00001;
expect(approxEq(f64, rotatedAngle(Pos{ .x = 0, .y = -1 }), 0.0, epsilon));
expect(approxEq(f64, rotatedAngle(Pos{ .x = 1, .y = 0 }), math.pi / 2.0, epsilon));
expect(approxEq(f64, rotatedAngle(Pos{ .x = 0, .y = 1 }), math.pi, epsilon));
expect(approxEq(f64, rotatedAngle(Pos{ .x = -1, .y = 0 }), 3.0 * math.pi / 2.0, epsilon));
}
fn lessThan(context: void, lhs: Pos, rhs: Pos) bool {
const lhs_angle = rotatedAngle(lhs);
const rhs_angle = rotatedAngle(rhs);
return lhs_angle < rhs_angle;
}
pub const AsteroidMap = struct {
asteroids: []Pos,
const Self = @This();
pub fn fromStream(stream: anytype, allocator: *Allocator) !Self {
var asteroids = ArrayList(Pos).init(allocator);
var y: isize = 0;
while (stream.readUntilDelimiterAlloc(allocator, '\n', 1024)) |line| {
for (line) |c, i| {
switch (c) {
'#' => try asteroids.append(Pos{
.x = @intCast(isize, i),
.y = y,
}),
'.' => {},
else => {
std.debug.warn("invalid char: {}\n", .{c});
return error.InvalidMapCharacter;
},
}
}
y += 1;
} else |e| switch (e) {
error.EndOfStream => {},
else => return e,
}
return Self{
.asteroids = asteroids.items,
};
}
pub fn detectableAsteroids(alloc: *Allocator, asteroids: []Pos, position: Pos) ![]Pos {
var result = ArrayList(Pos).init(alloc);
for (asteroids) |x| {
if (x.eq(position))
continue;
const obstructed = for (asteroids) |y| {
if (y.eq(position) or y.eq(x))
continue;
if (obstructs(position, x, y))
break true;
} else false;
if (!obstructed)
try result.append(x);
}
return result.items;
}
pub fn countDetectableAsteroids(self: Self, position: Pos) usize {
var result: usize = 0;
for (self.asteroids) |x| {
if (x.eq(position))
continue;
const obstructed = for (self.asteroids) |y| {
if (y.eq(position) or y.eq(x))
continue;
if (obstructs(position, x, y))
break true;
} else false;
if (!obstructed)
result += 1;
}
return result;
}
pub fn stationLocation(self: Self) ?Pos {
var max_detectable: ?usize = null;
var result: ?Pos = null;
for (self.asteroids) |x| {
const val = self.countDetectableAsteroids(x);
if (max_detectable) |max| {
if (val > max) {
max_detectable = val;
result = x;
}
} else {
max_detectable = val;
result = x;
}
}
return result;
}
pub fn maxDetectableAsteroids(self: Self) ?usize {
if (self.stationLocation()) |loc| {
return self.countDetectableAsteroids(loc);
} else {
return null;
}
}
pub fn initiateVaporization(self: Self, alloc: *Allocator, station: Pos) ![]Pos {
var result = ArrayList(Pos).init(alloc);
var remaining_asteroids = ArrayList(Pos).init(alloc);
try remaining_asteroids.appendSlice(self.asteroids);
defer remaining_asteroids.deinit();
var i: usize = 0;
while (i < remaining_asteroids.items.len) : (i += 1) {
if (station.eq(remaining_asteroids.items[i])) {
_ = remaining_asteroids.swapRemove(i);
}
}
while (remaining_asteroids.items.len > 0) {
var this_rotation = try Self.detectableAsteroids(alloc, remaining_asteroids.items, station);
defer alloc.free(this_rotation);
// Convert asteroids to vectors
for (this_rotation) |*x| {
x.x = x.x - station.x;
x.y = x.y - station.y;
}
// Sort asteroids to remove
std.sort.sort(Pos, this_rotation, {}, lessThan);
// Convert vectors back to asteroids
for (this_rotation) |*x| {
x.x = x.x + station.x;
x.y = x.y + station.y;
}
// Remove from remaining asteroids
for (this_rotation) |x| {
i = 0;
while (i < remaining_asteroids.items.len) : (i += 1) {
if (x.eq(remaining_asteroids.items[i])) {
_ = remaining_asteroids.swapRemove(i);
}
}
}
// Add to removed asteroids
try result.appendSlice(this_rotation);
}
return result.items;
}
};
test "read asteroid map" {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const allocator = &arena.allocator;
defer arena.deinit();
var input_stream = fixedBufferStream(
\\..#
\\#.#
\\...
\\
).reader();
const map = try AsteroidMap.fromStream(input_stream, allocator);
expectEqual(@intCast(usize, 3), map.asteroids.len);
expectEqual(map.asteroids[0], Pos{ .x = 2, .y = 0 });
expectEqual(map.asteroids[1], Pos{ .x = 0, .y = 1 });
expectEqual(map.asteroids[2], Pos{ .x = 2, .y = 1 });
}
test "count visible asteroids" {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const allocator = &arena.allocator;
defer arena.deinit();
var input_stream = fixedBufferStream(
\\.#..#
\\.....
\\#####
\\....#
\\...##
\\
).reader();
const map = try AsteroidMap.fromStream(input_stream, allocator);
expectEqual(@intCast(usize, 10), map.asteroids.len);
expectEqual(@intCast(usize, 7), map.countDetectableAsteroids(pos(1, 0)));
expectEqual(@intCast(usize, 7), map.countDetectableAsteroids(pos(4, 0)));
expectEqual(@intCast(usize, 6), map.countDetectableAsteroids(pos(0, 2)));
expectEqual(@intCast(usize, 7), map.countDetectableAsteroids(pos(1, 2)));
expectEqual(@intCast(usize, 7), map.countDetectableAsteroids(pos(2, 2)));
expectEqual(@intCast(usize, 7), map.countDetectableAsteroids(pos(3, 2)));
expectEqual(@intCast(usize, 5), map.countDetectableAsteroids(pos(4, 2)));
expectEqual(@intCast(usize, 7), map.countDetectableAsteroids(pos(4, 3)));
expectEqual(@intCast(usize, 7), map.countDetectableAsteroids(pos(4, 4)));
expectEqual(@intCast(usize, 8), map.countDetectableAsteroids(pos(3, 4)));
}
test "max visible asteroids 1" {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const allocator = &arena.allocator;
defer arena.deinit();
var input_stream = fixedBufferStream(
\\.#..#
\\.....
\\#####
\\....#
\\...##
\\
).reader();
const map = try AsteroidMap.fromStream(input_stream, allocator);
expectEqual(@intCast(usize, 10), map.asteroids.len);
expectEqual(@intCast(usize, 8), map.maxDetectableAsteroids().?);
}
test "max visible asteroids 2" {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const allocator = &arena.allocator;
defer arena.deinit();
var input_stream = fixedBufferStream(
\\......#.#.
\\#..#.#....
\\..#######.
\\.#.#.###..
\\.#..#.....
\\..#....#.#
\\#..#....#.
\\.##.#..###
\\##...#..#.
\\.#....####
\\
).reader();
const map = try AsteroidMap.fromStream(input_stream, allocator);
expectEqual(@intCast(usize, 33), map.maxDetectableAsteroids().?);
}
test "max visible asteroids 3" {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const allocator = &arena.allocator;
defer arena.deinit();
var input_stream = fixedBufferStream(
\\#.#...#.#.
\\.###....#.
\\.#....#...
\\##.#.#.#.#
\\....#.#.#.
\\.##..###.#
\\..#...##..
\\..##....##
\\......#...
\\.####.###.
\\
).reader();
const map = try AsteroidMap.fromStream(input_stream, allocator);
expectEqual(@intCast(usize, 35), map.maxDetectableAsteroids().?);
}
test "max visible asteroids 4" {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const allocator = &arena.allocator;
defer arena.deinit();
var input_stream = fixedBufferStream(
\\.#..#..###
\\####.###.#
\\....###.#.
\\..###.##.#
\\##.##.#.#.
\\....###..#
\\..#.#..#.#
\\#..#.#.###
\\.##...##.#
\\.....#.#..
\\
).reader();
const map = try AsteroidMap.fromStream(input_stream, allocator);
expectEqual(@intCast(usize, 41), map.maxDetectableAsteroids().?);
}
test "max visible asteroids 5" {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const allocator = &arena.allocator;
defer arena.deinit();
var input_stream = fixedBufferStream(
\\.#..##.###...#######
\\##.############..##.
\\.#.######.########.#
\\.###.#######.####.#.
\\#####.##.#.##.###.##
\\..#####..#.#########
\\####################
\\#.####....###.#.#.##
\\##.#################
\\#####.##.###..####..
\\..######..##.#######
\\####.##.####...##..#
\\.#####..#.######.###
\\##...#.##########...
\\#.##########.#######
\\.####.#.###.###.#.##
\\....##.##.###..#####
\\.#.#.###########.###
\\#.#.#.#####.####.###
\\###.##.####.##.#..##
\\
).reader();
const map = try AsteroidMap.fromStream(input_stream, allocator);
expectEqual(@intCast(usize, 210), map.maxDetectableAsteroids().?);
}
test "vaporize" {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const allocator = &arena.allocator;
defer arena.deinit();
var input_stream = fixedBufferStream(
\\.#..##.###...#######
\\##.############..##.
\\.#.######.########.#
\\.###.#######.####.#.
\\#####.##.#.##.###.##
\\..#####..#.#########
\\####################
\\#.####....###.#.#.##
\\##.#################
\\#####.##.###..####..
\\..######..##.#######
\\####.##.####...##..#
\\.#####..#.######.###
\\##...#.##########...
\\#.##########.#######
\\.####.#.###.###.#.##
\\....##.##.###..#####
\\.#.#.###########.###
\\#.#.#.#####.####.###
\\###.##.####.##.#..##
\\
).reader();
const map = try AsteroidMap.fromStream(input_stream, allocator);
const vaporize_order = try map.initiateVaporization(allocator, Pos{ .x = 11, .y = 13 });
expectEqual(Pos{ .x = 11, .y = 12 }, vaporize_order[0]);
expectEqual(Pos{ .x = 12, .y = 1 }, vaporize_order[1]);
expectEqual(Pos{ .x = 12, .y = 2 }, vaporize_order[2]);
expectEqual(Pos{ .x = 12, .y = 8 }, vaporize_order[9]);
expectEqual(Pos{ .x = 16, .y = 0 }, vaporize_order[19]);
expectEqual(Pos{ .x = 16, .y = 9 }, vaporize_order[49]);
expectEqual(Pos{ .x = 10, .y = 16 }, vaporize_order[99]);
expectEqual(Pos{ .x = 9, .y = 6 }, vaporize_order[198]);
expectEqual(Pos{ .x = 8, .y = 2 }, vaporize_order[199]);
expectEqual(Pos{ .x = 10, .y = 9 }, vaporize_order[200]);
expectEqual(Pos{ .x = 11, .y = 1 }, vaporize_order[298]);
}
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const allocator = &arena.allocator;
defer arena.deinit();
const input_file = try std.fs.cwd().openFile("input10.txt", .{});
var input_stream = input_file.reader();
const map = try AsteroidMap.fromStream(input_stream, allocator);
const station_location = map.stationLocation() orelse return error.NoStationLocation;
std.debug.warn("max detectable asteroids: {}\n", .{map.countDetectableAsteroids(station_location)});
std.debug.warn("station location: {}\n", .{station_location});
const vaporization_order = try map.initiateVaporization(allocator, station_location);
std.debug.warn("200th asteroid: {}\n", .{vaporization_order[199]});
std.debug.warn("soltion: {}\n", .{vaporization_order[199].x * 100 + vaporization_order[199].y});
} | zig/10_2.zig |
const std = @import("std");
const mem = std.mem;
const maxInt = std.math.maxInt;
// RFC 2898 Section 5.2
//
// FromSpec:
//
// PBKDF2 applies a pseudorandom function (see Appendix B.1 for an
// example) to derive keys. The length of the derived key is essentially
// unbounded. (However, the maximum effective search space for the
// derived key may be limited by the structure of the underlying
// pseudorandom function. See Appendix B.1 for further discussion.)
// PBKDF2 is recommended for new applications.
//
// PBKDF2 (P, S, c, dkLen)
//
// Options: PRF underlying pseudorandom function (hLen
// denotes the length in octets of the
// pseudorandom function output)
//
// Input: P password, an octet string
// S salt, an octet string
// c iteration count, a positive integer
// dkLen intended length in octets of the derived
// key, a positive integer, at most
// (2^32 - 1) * hLen
//
// Output: DK derived key, a dkLen-octet string
// Based on Apple's CommonKeyDerivation, based originally on code by <NAME>.
pub const Pbkdf2Error = error{
/// At least one round is required
TooFewRounds,
/// Maximum length of the derived key is `maxInt(u32) * Prf.mac_length`
DerivedKeyTooLong,
};
/// Apply PBKDF2 to generate a key from a password.
///
/// PBKDF2 is defined in RFC 2898, and is a recommendation of NIST SP 800-132.
///
/// derivedKey: Slice of appropriate size for generated key. Generally 16 or 32 bytes in length.
/// May be uninitialized. All bytes will be overwritten.
/// Maximum size is `maxInt(u32) * Hash.digest_length`
/// It is a programming error to pass buffer longer than the maximum size.
///
/// password: Arbitrary sequence of bytes of any length, including empty.
///
/// salt: Arbitrary sequence of bytes of any length, including empty. A common length is 8 bytes.
///
/// rounds: Iteration count. Must be greater than 0. Common values range from 1,000 to 100,000.
/// Larger iteration counts improve security by increasing the time required to compute
/// the derivedKey. It is common to tune this parameter to achieve approximately 100ms.
///
/// Prf: Pseudo-random function to use. A common choice is `std.crypto.auth.hmac.HmacSha256`.
pub fn pbkdf2(derivedKey: []u8, password: []const u8, salt: []const u8, rounds: u32, comptime Prf: type) Pbkdf2Error!void {
if (rounds < 1) return error.TooFewRounds;
const dkLen = derivedKey.len;
const hLen = Prf.mac_length;
comptime std.debug.assert(hLen >= 1);
// FromSpec:
//
// 1. If dkLen > maxInt(u32) * hLen, output "derived key too long" and
// stop.
//
if (comptime (maxInt(usize) > maxInt(u32) * hLen) and (dkLen > @as(usize, maxInt(u32) * hLen))) {
// If maxInt(usize) is less than `maxInt(u32) * hLen` then dkLen is always inbounds
return error.DerivedKeyTooLong;
}
// FromSpec:
//
// 2. Let l be the number of hLen-long blocks of bytes in the derived key,
// rounding up, and let r be the number of bytes in the last
// block
//
// l will not overflow, proof:
// let `L(dkLen, hLen) = (dkLen + hLen - 1) / hLen`
// then `L^-1(l, hLen) = l*hLen - hLen + 1`
// 1) L^-1(maxInt(u32), hLen) <= maxInt(u32)*hLen
// 2) maxInt(u32)*hLen - hLen + 1 <= maxInt(u32)*hLen // subtract maxInt(u32)*hLen + 1
// 3) -hLen <= -1 // multiply by -1
// 4) hLen >= 1
const r_ = dkLen % hLen;
const l = @intCast(u32, (dkLen / hLen) + @as(u1, if (r_ == 0) 0 else 1)); // original: (dkLen + hLen - 1) / hLen
const r = if (r_ == 0) hLen else r_;
// FromSpec:
//
// 3. For each block of the derived key apply the function F defined
// below to the password P, the salt S, the iteration count c, and
// the block index to compute the block:
//
// T_1 = F (P, S, c, 1) ,
// T_2 = F (P, S, c, 2) ,
// ...
// T_l = F (P, S, c, l) ,
//
// where the function F is defined as the exclusive-or sum of the
// first c iterates of the underlying pseudorandom function PRF
// applied to the password P and the concatenation of the salt S
// and the block index i:
//
// F (P, S, c, i) = U_1 \xor U_2 \xor ... \xor U_c
//
// where
//
// U_1 = PRF (P, S || INT (i)) ,
// U_2 = PRF (P, U_1) ,
// ...
// U_c = PRF (P, U_{c-1}) .
//
// Here, INT (i) is a four-octet encoding of the integer i, most
// significant octet first.
//
// 4. Concatenate the blocks and extract the first dkLen octets to
// produce a derived key DK:
//
// DK = T_1 || T_2 || ... || T_l<0..r-1>
var block: u32 = 0; // Spec limits to u32
while (block < l) : (block += 1) {
var prevBlock: [hLen]u8 = undefined;
var newBlock: [hLen]u8 = undefined;
// U_1 = PRF (P, S || INT (i))
const blockIndex = mem.toBytes(mem.nativeToBig(u32, block + 1)); // Block index starts at 0001
var ctx = Prf.init(password);
ctx.update(salt);
ctx.update(blockIndex[0..]);
ctx.final(prevBlock[0..]);
// Choose portion of DK to write into (T_n) and initialize
const offset = block * hLen;
const blockLen = if (block != l - 1) hLen else r;
const dkBlock: []u8 = derivedKey[offset..][0..blockLen];
mem.copy(u8, dkBlock, prevBlock[0..dkBlock.len]);
var i: u32 = 1;
while (i < rounds) : (i += 1) {
// U_c = PRF (P, U_{c-1})
Prf.create(&newBlock, prevBlock[0..], password);
mem.copy(u8, prevBlock[0..], newBlock[0..]);
// F (P, S, c, i) = U_1 \xor U_2 \xor ... \xor U_c
for (dkBlock) |_, j| {
dkBlock[j] ^= newBlock[j];
}
}
}
}
const htest = @import("test.zig");
const HmacSha1 = std.crypto.auth.hmac.HmacSha1;
// RFC 6070 PBKDF2 HMAC-SHA1 Test Vectors
test "RFC 6070 one iteration" {
const p = "password";
const s = "<PASSWORD>";
const c = 1;
const dkLen = 20;
var derivedKey: [dkLen]u8 = undefined;
try pbkdf2(&derivedKey, p, s, c, HmacSha1);
const expected = "0c60c80f961f0e71f3a9b524af6012062fe037a6";
htest.assertEqual(expected, derivedKey[0..]);
}
test "RFC 6070 two iterations" {
const p = "password";
const s = "<PASSWORD>";
const c = 2;
const dkLen = 20;
var derivedKey: [dkLen]u8 = undefined;
try pbkdf2(&derivedKey, p, s, c, HmacSha1);
const expected = "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957";
htest.assertEqual(expected, derivedKey[0..]);
}
test "RFC 6070 4096 iterations" {
const p = "password";
const s = "<PASSWORD>";
const c = 4096;
const dkLen = 20;
var derivedKey: [dkLen]u8 = undefined;
try pbkdf2(&derivedKey, p, s, c, HmacSha1);
const expected = "4b007901b765489abead49d926f721d065a429c1";
htest.assertEqual(expected, derivedKey[0..]);
}
test "RFC 6070 16,777,216 iterations" {
// These iteration tests are slow so we always skip them. Results have been verified.
if (true) {
return error.SkipZigTest;
}
const p = "password";
const s = "salt";
const c = 16777216;
const dkLen = 20;
var derivedKey = [_]u8{0} ** dkLen;
try pbkdf2(&derivedKey, p, s, c, HmacSha1);
const expected = "eefe3d61cd4da4e4e9945b3d6ba2158c2634e984";
htest.assertEqual(expected, derivedKey[0..]);
}
test "RFC 6070 multi-block salt and password" {
const p = "passwordPASSWORDpassword";
const s = "saltSALTsaltSALTsaltSALTsaltSALTsalt";
const c = 4096;
const dkLen = 25;
var derivedKey: [dkLen]u8 = undefined;
try pbkdf2(&derivedKey, p, s, c, HmacSha1);
const expected = "3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038";
htest.assertEqual(expected, derivedKey[0..]);
}
test "RFC 6070 embedded NUL" {
const p = "<PASSWORD>";
const s = "sa\x00lt";
const c = 4096;
const dkLen = 16;
var derivedKey: [dkLen]u8 = undefined;
try pbkdf2(&derivedKey, p, s, c, HmacSha1);
const expected = "56fa6aa75548099dcc37d7f03425e0c3";
htest.assertEqual(expected, derivedKey[0..]);
}
test "Very large dkLen" {
// This test allocates 8GB of memory and is expected to take several hours to run.
if (true) {
return error.SkipZigTest;
}
const p = "password";
const s = "salt";
const c = 1;
const dkLen = 1 << 33;
var derivedKey = try std.testing.allocator.alloc(u8, dkLen);
defer {
std.testing.allocator.free(derivedKey);
}
try pbkdf2(derivedKey, p, s, c, HmacSha1);
// Just verify this doesn't crash with an overflow
} | lib/std/crypto/pbkdf2.zig |
const std = @import("std");
const path = std.fs.path;
const mem = std.mem;
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
const out_dir = "out";
try std.fs.cwd().makePath(out_dir);
{
const out_file = out_dir ++ path.sep_str ++ "index.json";
const in_file = "index.json";
try render(allocator, in_file, out_file, .plain);
}
}
fn render(
allocator: mem.Allocator,
in_file: []const u8,
out_file: []const u8,
fmt: enum {
html,
plain,
},
) !void {
const in_contents = try std.fs.cwd().readFileAlloc(allocator, in_file, 1 * 1024 * 1024);
var vars = try std.process.getEnvMap(allocator);
var buffer = std.ArrayList(u8).init(allocator);
defer buffer.deinit();
const State = enum {
Start,
OpenBrace,
VarName,
EndBrace,
};
const writer = buffer.writer();
var state = State.Start;
var var_name_start: usize = undefined;
var line: usize = 1;
for (in_contents) |byte, index| {
switch (state) {
State.Start => switch (byte) {
'{' => {
state = State.OpenBrace;
},
else => try writer.writeByte(byte),
},
State.OpenBrace => switch (byte) {
'{' => {
state = State.VarName;
var_name_start = index + 1;
},
else => {
try writer.writeByte('{');
try writer.writeByte(byte);
state = State.Start;
},
},
State.VarName => switch (byte) {
'}' => {
const var_name = in_contents[var_name_start..index];
if (vars.get(var_name)) |value| {
const trimmed = mem.trim(u8, value, " \r\n");
if (fmt == .html and mem.endsWith(u8, var_name, "BYTESIZE")) {
const size = try std.fmt.parseInt(u64, trimmed, 10);
try writer.print("{:.1}", .{std.fmt.fmtIntSizeDec(size)});
} else {
try writer.writeAll(trimmed);
}
} else {
std.debug.warn("line {d}: missing variable: {s}\n", .{ line, var_name });
try writer.writeAll("(missing)");
}
state = State.EndBrace;
},
else => {},
},
State.EndBrace => switch (byte) {
'}' => {
state = State.Start;
},
else => {
std.debug.warn("line {d}: invalid byte: '0x{x}'", .{ line, byte });
std.process.exit(1);
},
},
}
if (byte == '\n') {
line += 1;
}
}
try std.fs.cwd().writeFile(out_file, buffer.items);
} | ci/srht/update-download-page.zig |
const std = @import("std");
const warn = std.debug.warn;
const span = @import("./span.zig");
const filepath = @import("../filepath/filepath.zig");
const url = @import("../url/url.zig");
const testing = std.testing;
test "fileURI" {
const sample = [][]const u8{
"C:/Windows/System32",
"C:/Go/src/bob.go",
"c:/Go/src/bob.go",
"/path/to/dir",
"/a/b/c/src/bob.go",
};
var a = std.debug.global_allocator;
var test_path = &try std.Buffer.init(a, "");
var expect_path = &try std.Buffer.init(a, "");
var expect_uri = &try std.Buffer.init(a, "");
var tmp = &try std.Buffer.init(a, "");
var file_uri = &try std.Buffer.init(a, "");
defer {
test_path.deinit();
expect_path.deinit();
expect_uri.deinit();
tmp.deinit();
file_uri.deinit();
}
for (sample) |path, idx| {
try test_path.resize(0);
try expect_path.resize(0);
try expect_uri.resize(0);
try file_uri.resize(0);
try filepath.fromSlash(path, test_path);
try expect_path.append(test_path.toSlice());
if (path[0] == '/') {
if (filepath.abs(a, path)) |abs| {
try expect_path.replaceContents(abs);
a.free(abs);
} else |_| {}
}
try filepath.toSlash(expect_path.toSlice(), expect_uri);
if (expect_uri.toSlice()[0] != '/') {
try tmp.replaceContents("/");
try tmp.append(expect_uri.toSlice());
try expect_uri.replaceContents(tmp.toSlice());
}
try tmp.replaceContents("file://");
try tmp.append(expect_uri.toSlice());
try expect_uri.replaceContents(tmp.toSlice());
var got_uri = try span.URI.fromFile(a, test_path.toSlice());
testing.expect(expect_uri.eql(got_uri.data));
got_uri.deinit();
}
}
test "parse" {
const sample = [][3][]const u8{
[][]const u8{ "C:/file_a", "C:/file_a", "file:///C:/file_a:1:1#0" },
[][]const u8{ "C:/file_b:1:2", "C:/file_b:#1", "file:///C:/file_b:1:2#1" },
[][]const u8{ "C:/file_c:1000", "C:/file_c:#9990", "file:///C:/file_c:1000:1#9990" },
[][]const u8{ "C:/file_d:14:9", "C:/file_d:#138", "file:///C:/file_d:14:9#138" },
[][]const u8{ "C:/file_e:1:2-7", "C:/file_e:#1-#6", "file:///C:/file_e:1:2#1-1:7#6" },
[][]const u8{ "C:/file_f:500-502", "C:/file_f:#4990-#5010", "file:///C:/file_f:500:1#4990-502:1#5010" },
[][]const u8{ "C:/file_g:3:7-8", "C:/file_g:#26-#27", "file:///C:/file_g:3:7#26-3:8#27" },
[][]const u8{ "C:/file_h:3:7-4:8", "C:/file_h:#26-#37", "file:///C:/file_h:3:7#26-4:8#37" },
};
const formats = [][]const u8{ "{}", "{#}", "{+}" };
var a = std.debug.global_allocator;
for (sample) |ts| {
for (ts) |ti, idx| {
var s = try span.parse(a, ti);
s.deinit();
}
}
} | src/lsp/span/span_test.zig |
const std = @import("std");
const log = std.log.scoped(.Cuda);
pub const cu = @import("cuda_cimports.zig").cu;
pub const Error = error{
OutOfMemory,
LaunchOutOfResources,
UnexpectedByCudaz,
NotSupported,
NotReady,
// TODO: add more generic errors to allow forward compatibilities with more
// Cuda versions / Cudaz development.
};
/// Converts the Cuda result code into a simplified Zig error.
/// The goal is to only surface errors that are recoverable and aren't due to a
/// bug in caller code, library code or kernel code.
/// Cuda can yield a lot of different errors, but there are different categories.
/// Note that in any case we will log the detailed error and its message.
/// * Resource errors: typically out of memory.
/// -> original error (OutOfMemory, ...)
/// * Device capability errors: the current device doesn't support this function.
/// -> NotSupported
/// * API usage errors: errors that will deterministically be returned
/// when the API is misused. Cudaz is allowed to panic here.
/// Cudaz aims at preventing this kind of error by providing an API harder to misuses.
/// Typically calling Cuda methods before calling cuInit().
/// This can also be due to passing host pointer to functions expecting device pointer.
/// -> @panic
/// * Message passing: not actual error, but things that should be retried.
/// eg: CUDA_ERROR_NOT_READY
/// -> NotReady
/// * Bug in Cudaz: Cudaz is creating a default context and loading the compiled
/// Cuda code for you. Those operation shouldn't fail unless bug in Cudaz.
/// -> @panic
/// * Kernel execution error:
/// There was a bug during kernel execution (stackoverflow, segfault, ...)
/// Typically those leave the driver in unusable state, the process must be restarted.
/// Cudaz will panic here.
/// This will typically not trigger at the expected place because they will
/// happen asynchronously to the host code execution.
/// -> @panic
/// * Unhandled errors:
/// Cudaz doesn't support the full Cuda API (yet ?). Trying to use Cudaz
/// check on errors returned by unsupported part of the API will trigger a @panic
/// (this will only happen if you directly call cuda). Feel free to open PR
/// to support more parts of Cuda
/// -> @panic
pub fn check(result: cu.CUresult) Error!void {
if (result == cu.CUDA_SUCCESS) return;
log_err_message(result);
return silent_check(result);
}
pub fn silent_check(result: cu.CUresult) Error!void {
var err: Error = switch (result) {
cu.CUDA_SUCCESS => return,
// Resource errors:
cu.CUDA_ERROR_OUT_OF_MEMORY => error.OutOfMemory,
// Device capability error:
cu.CUDA_ERROR_STUB_LIBRARY,
cu.CUDA_ERROR_NO_DEVICE,
cu.CUDA_ERROR_INVALID_DEVICE,
cu.CUDA_ERROR_DEVICE_NOT_LICENSED,
cu.CUDA_ERROR_NOT_PERMITTED, // TODO: make a distinctions for permission ?
cu.CUDA_ERROR_NOT_SUPPORTED,
cu.CUDA_ERROR_SYSTEM_NOT_READY,
cu.CUDA_ERROR_SYSTEM_DRIVER_MISMATCH,
cu.CUDA_ERROR_COMPAT_NOT_SUPPORTED_ON_DEVICE,
=> error.NotSupported,
// LAUNCH_OUT_OF_RESOURCES can indicate either that the too many threads
// where requested wrt to the maximum supported by the GPU.
// It can also be triggered by passing too many args to a kernel,
// but this should be caught at compile time by Cudaz, so we will ignore this.
cu.CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES => error.NotSupported,
// API usage errors:
cu.CUDA_ERROR_INVALID_VALUE => @panic("Received invalid parameters (typically device/host pointer mismatch"),
cu.CUDA_ERROR_NOT_INITIALIZED,
cu.CUDA_ERROR_DEINITIALIZED,
cu.CUDA_ERROR_PROFILER_NOT_INITIALIZED,
cu.CUDA_ERROR_PROFILER_ALREADY_STARTED,
cu.CUDA_ERROR_PROFILER_ALREADY_STOPPED,
cu.CUDA_ERROR_PROFILER_DISABLED,
cu.CUDA_ERROR_CONTEXT_ALREADY_CURRENT,
cu.CUDA_ERROR_CONTEXT_ALREADY_IN_USE,
cu.CUDA_ERROR_INVALID_HANDLE,
=> @panic("Invalid API usage"),
// Bug in Cudaz:
cu.CUDA_ERROR_INVALID_IMAGE,
cu.CUDA_ERROR_INVALID_CONTEXT,
cu.CUDA_ERROR_NO_BINARY_FOR_GPU,
cu.CUDA_ERROR_INVALID_PTX,
cu.CUDA_ERROR_INVALID_GRAPHICS_CONTEXT,
cu.CUDA_ERROR_UNSUPPORTED_PTX_VERSION,
cu.CUDA_ERROR_INVALID_SOURCE,
cu.CUDA_ERROR_FILE_NOT_FOUND,
cu.CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND,
cu.CUDA_ERROR_SHARED_OBJECT_INIT_FAILED,
cu.CUDA_ERROR_NOT_FOUND,
=> @panic("Something looks wrong with compiled device code"),
// Kernel execution error:
cu.CUDA_ERROR_ECC_UNCORRECTABLE,
cu.CUDA_ERROR_HARDWARE_STACK_ERROR,
cu.CUDA_ERROR_ILLEGAL_INSTRUCTION,
cu.CUDA_ERROR_MISALIGNED_ADDRESS,
cu.CUDA_ERROR_ILLEGAL_ADDRESS,
cu.CUDA_ERROR_INVALID_ADDRESS_SPACE,
cu.CUDA_ERROR_INVALID_PC,
cu.CUDA_ERROR_LAUNCH_FAILED,
cu.CUDA_ERROR_EXTERNAL_DEVICE,
=> @panic("Unrecoverable error while running device code"),
// Unhandled errors:
// Map, Stream, Graph
else => @panic("Part of the API not handled by Cudaz"),
};
return err;
}
pub fn error_name(result: cu.CUresult) []const u8 {
return switch (result) {
cu.CUDA_SUCCESS => "CUDA_SUCCESS",
cu.CUDA_ERROR_INVALID_VALUE => "CUDA_ERROR_INVALID_VALUE",
cu.CUDA_ERROR_OUT_OF_MEMORY => "CUDA_ERROR_OUT_OF_MEMORY",
cu.CUDA_ERROR_NOT_INITIALIZED => "CUDA_ERROR_NOT_INITIALIZED",
cu.CUDA_ERROR_DEINITIALIZED => "CUDA_ERROR_DEINITIALIZED",
cu.CUDA_ERROR_PROFILER_DISABLED => "CUDA_ERROR_PROFILER_DISABLED",
cu.CUDA_ERROR_PROFILER_NOT_INITIALIZED => "CUDA_ERROR_PROFILER_NOT_INITIALIZED",
cu.CUDA_ERROR_PROFILER_ALREADY_STARTED => "CUDA_ERROR_PROFILER_ALREADY_STARTED",
cu.CUDA_ERROR_PROFILER_ALREADY_STOPPED => "CUDA_ERROR_PROFILER_ALREADY_STOPPED",
cu.CUDA_ERROR_STUB_LIBRARY => "CUDA_ERROR_STUB_LIBRARY",
cu.CUDA_ERROR_NO_DEVICE => "CUDA_ERROR_NO_DEVICE",
cu.CUDA_ERROR_INVALID_DEVICE => "CUDA_ERROR_INVALID_DEVICE",
cu.CUDA_ERROR_DEVICE_NOT_LICENSED => "CUDA_ERROR_DEVICE_NOT_LICENSED",
cu.CUDA_ERROR_INVALID_IMAGE => "CUDA_ERROR_INVALID_IMAGE",
cu.CUDA_ERROR_INVALID_CONTEXT => "CUDA_ERROR_INVALID_CONTEXT",
cu.CUDA_ERROR_CONTEXT_ALREADY_CURRENT => "CUDA_ERROR_CONTEXT_ALREADY_CURRENT",
cu.CUDA_ERROR_MAP_FAILED => "CUDA_ERROR_MAP_FAILED",
cu.CUDA_ERROR_UNMAP_FAILED => "CUDA_ERROR_UNMAP_FAILED",
cu.CUDA_ERROR_ARRAY_IS_MAPPED => "CUDA_ERROR_ARRAY_IS_MAPPED",
cu.CUDA_ERROR_ALREADY_MAPPED => "CUDA_ERROR_ALREADY_MAPPED",
cu.CUDA_ERROR_NO_BINARY_FOR_GPU => "CUDA_ERROR_NO_BINARY_FOR_GPU",
cu.CUDA_ERROR_ALREADY_ACQUIRED => "CUDA_ERROR_ALREADY_ACQUIRED",
cu.CUDA_ERROR_NOT_MAPPED => "CUDA_ERROR_NOT_MAPPED",
cu.CUDA_ERROR_NOT_MAPPED_AS_ARRAY => "CUDA_ERROR_NOT_MAPPED_AS_ARRAY",
cu.CUDA_ERROR_NOT_MAPPED_AS_POINTER => "CUDA_ERROR_NOT_MAPPED_AS_POINTER",
cu.CUDA_ERROR_ECC_UNCORRECTABLE => "CUDA_ERROR_ECC_UNCORRECTABLE",
cu.CUDA_ERROR_UNSUPPORTED_LIMIT => "CUDA_ERROR_UNSUPPORTED_LIMIT",
cu.CUDA_ERROR_CONTEXT_ALREADY_IN_USE => "CUDA_ERROR_CONTEXT_ALREADY_IN_USE",
cu.CUDA_ERROR_PEER_ACCESS_UNSUPPORTED => "CUDA_ERROR_PEER_ACCESS_UNSUPPORTED",
cu.CUDA_ERROR_INVALID_PTX => "CUDA_ERROR_INVALID_PTX",
cu.CUDA_ERROR_INVALID_GRAPHICS_CONTEXT => "CUDA_ERROR_INVALID_GRAPHICS_CONTEXT",
cu.CUDA_ERROR_NVLINK_UNCORRECTABLE => "CUDA_ERROR_NVLINK_UNCORRECTABLE",
cu.CUDA_ERROR_JIT_COMPILER_NOT_FOUND => "CUDA_ERROR_JIT_COMPILER_NOT_FOUND",
cu.CUDA_ERROR_UNSUPPORTED_PTX_VERSION => "CUDA_ERROR_UNSUPPORTED_PTX_VERSION",
cu.CUDA_ERROR_JIT_COMPILATION_DISABLED => "CUDA_ERROR_JIT_COMPILATION_DISABLED",
cu.CUDA_ERROR_UNSUPPORTED_EXEC_AFFINITY => "CUDA_ERROR_UNSUPPORTED_EXEC_AFFINITY",
cu.CUDA_ERROR_INVALID_SOURCE => "CUDA_ERROR_INVALID_SOURCE",
cu.CUDA_ERROR_FILE_NOT_FOUND => "CUDA_ERROR_FILE_NOT_FOUND",
cu.CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND => "CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND",
cu.CUDA_ERROR_SHARED_OBJECT_INIT_FAILED => "CUDA_ERROR_SHARED_OBJECT_INIT_FAILED",
cu.CUDA_ERROR_OPERATING_SYSTEM => "CUDA_ERROR_OPERATING_SYSTEM",
cu.CUDA_ERROR_INVALID_HANDLE => "CUDA_ERROR_INVALID_HANDLE",
cu.CUDA_ERROR_ILLEGAL_STATE => "CUDA_ERROR_ILLEGAL_STATE",
cu.CUDA_ERROR_NOT_FOUND => "CUDA_ERROR_NOT_FOUND",
cu.CUDA_ERROR_NOT_READY => "CUDA_ERROR_NOT_READY",
cu.CUDA_ERROR_ILLEGAL_ADDRESS => "CUDA_ERROR_ILLEGAL_ADDRESS",
cu.CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES => "CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES",
cu.CUDA_ERROR_LAUNCH_TIMEOUT => "CUDA_ERROR_LAUNCH_TIMEOUT",
cu.CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING => "CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING",
cu.CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED => "CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED",
cu.CUDA_ERROR_PEER_ACCESS_NOT_ENABLED => "CUDA_ERROR_PEER_ACCESS_NOT_ENABLED",
cu.CUDA_ERROR_PRIMARY_CONTEXT_ACTIVE => "CUDA_ERROR_PRIMARY_CONTEXT_ACTIVE",
cu.CUDA_ERROR_CONTEXT_IS_DESTROYED => "CUDA_ERROR_CONTEXT_IS_DESTROYED",
cu.CUDA_ERROR_ASSERT => "CUDA_ERROR_ASSERT",
cu.CUDA_ERROR_TOO_MANY_PEERS => "CUDA_ERROR_TOO_MANY_PEERS",
cu.CUDA_ERROR_HOST_MEMORY_ALREADY_REGISTERED => "CUDA_ERROR_HOST_MEMORY_ALREADY_REGISTERED",
cu.CUDA_ERROR_HOST_MEMORY_NOT_REGISTERED => "CUDA_ERROR_HOST_MEMORY_NOT_REGISTERED",
cu.CUDA_ERROR_HARDWARE_STACK_ERROR => "CUDA_ERROR_HARDWARE_STACK_ERROR",
cu.CUDA_ERROR_ILLEGAL_INSTRUCTION => "CUDA_ERROR_ILLEGAL_INSTRUCTION",
cu.CUDA_ERROR_MISALIGNED_ADDRESS => "CUDA_ERROR_MISALIGNED_ADDRESS",
cu.CUDA_ERROR_INVALID_ADDRESS_SPACE => "CUDA_ERROR_INVALID_ADDRESS_SPACE",
cu.CUDA_ERROR_INVALID_PC => "CUDA_ERROR_INVALID_PC",
cu.CUDA_ERROR_LAUNCH_FAILED => "CUDA_ERROR_LAUNCH_FAILED",
cu.CUDA_ERROR_COOPERATIVE_LAUNCH_TOO_LARGE => "CUDA_ERROR_COOPERATIVE_LAUNCH_TOO_LARGE",
cu.CUDA_ERROR_NOT_PERMITTED => "CUDA_ERROR_NOT_PERMITTED",
cu.CUDA_ERROR_NOT_SUPPORTED => "CUDA_ERROR_NOT_SUPPORTED",
cu.CUDA_ERROR_SYSTEM_NOT_READY => "CUDA_ERROR_SYSTEM_NOT_READY",
cu.CUDA_ERROR_SYSTEM_DRIVER_MISMATCH => "CUDA_ERROR_SYSTEM_DRIVER_MISMATCH",
cu.CUDA_ERROR_COMPAT_NOT_SUPPORTED_ON_DEVICE => "CUDA_ERROR_COMPAT_NOT_SUPPORTED_ON_DEVICE",
cu.CUDA_ERROR_MPS_CONNECTION_FAILED => "CUDA_ERROR_MPS_CONNECTION_FAILED",
cu.CUDA_ERROR_MPS_RPC_FAILURE => "CUDA_ERROR_MPS_RPC_FAILURE",
cu.CUDA_ERROR_MPS_SERVER_NOT_READY => "CUDA_ERROR_MPS_SERVER_NOT_READY",
cu.CUDA_ERROR_MPS_MAX_CLIENTS_REACHED => "CUDA_ERROR_MPS_MAX_CLIENTS_REACHED",
cu.CUDA_ERROR_MPS_MAX_CONNECTIONS_REACHED => "CUDA_ERROR_MPS_MAX_CONNECTIONS_REACHED",
cu.CUDA_ERROR_STREAM_CAPTURE_UNSUPPORTED => "CUDA_ERROR_STREAM_CAPTURE_UNSUPPORTED",
cu.CUDA_ERROR_STREAM_CAPTURE_INVALIDATED => "CUDA_ERROR_STREAM_CAPTURE_INVALIDATED",
cu.CUDA_ERROR_STREAM_CAPTURE_MERGE => "CUDA_ERROR_STREAM_CAPTURE_MERGE",
cu.CUDA_ERROR_STREAM_CAPTURE_UNMATCHED => "CUDA_ERROR_STREAM_CAPTURE_UNMATCHED",
cu.CUDA_ERROR_STREAM_CAPTURE_UNJOINED => "CUDA_ERROR_STREAM_CAPTURE_UNJOINED",
cu.CUDA_ERROR_STREAM_CAPTURE_ISOLATION => "CUDA_ERROR_STREAM_CAPTURE_ISOLATION",
cu.CUDA_ERROR_STREAM_CAPTURE_IMPLICIT => "CUDA_ERROR_STREAM_CAPTURE_IMPLICIT",
cu.CUDA_ERROR_CAPTURED_EVENT => "CUDA_ERROR_CAPTURED_EVENT",
cu.CUDA_ERROR_STREAM_CAPTURE_WRONG_THREAD => "CUDA_ERROR_STREAM_CAPTURE_WRONG_THREAD",
cu.CUDA_ERROR_TIMEOUT => "CUDA_ERROR_TIMEOUT",
cu.CUDA_ERROR_GRAPH_EXEC_UPDATE_FAILURE => "CUDA_ERROR_GRAPH_EXEC_UPDATE_FAILURE",
cu.CUDA_ERROR_EXTERNAL_DEVICE => "CUDA_ERROR_EXTERNAL_DEVICE",
cu.CUDA_ERROR_UNKNOWN => "CUDA_ERROR_UNKNOWN",
else => "<Unexpected cuda error please open a bug to Cudaz>",
};
}
pub fn log_err_message(result: cu.CUresult) void {
const err_name = error_name(result);
var err_message: [*c]const u8 = undefined;
const error_string_res = cu.cuGetErrorString(result, &err_message);
if (error_string_res != cu.CUDA_SUCCESS) {
err_message = "(no error message)";
}
log.err("{s}({d}): {s}", .{ err_name, result, err_message });
} | cudaz/src/cuda_errors.zig |
const std = @import("std");
const assert = std.debug.assert;
const testing = std.testing;
// Returns an error if the end of the string is reached
pub fn skipWhitespace(s: *([]const u8)) !void {
var i: u32 = 0;
while (i < s.*.len and (s.*[i] == ' ' or s.*[i] == '\t' or s.*[i] == '\n' or s.*[i] == '\r')) {
i += 1;
}
if (i == s.*.len) {
return error.EndOfString;
}
s.* = s.*[i..];
}
test "skipWhitespace" {
var s: []const u8 = " \nabc ";
try skipWhitespace(&s);
testing.expect(std.mem.eql(u8, s, "abc "));
}
pub fn skipNewline(s: *([]const u8)) !void {
if (s.*.len == 0) {
return error.EmptyString;
}
if (s.*[0] == '\n') {
s.* = s.*[1..];
} else {
if (s.*.len == 1) {
if (s.*[0] == '\r') {
return error.InvalidNewLine;
}
} else {
// len > 1, first char != '\n'
if (s.*[0] == '\r' and s.*[1] == '\n') {
s.* = s.*[2..];
}
}
}
}
test "skipNewline" {
var s: []const u8 = "\nb";
try skipNewline(&s);
testing.expect(std.mem.eql(u8, s, "b"));
s = "\r\nb";
try skipNewline(&s);
testing.expect(std.mem.eql(u8, s, "b"));
s = "a\r\nb";
try skipNewline(&s);
testing.expect(std.mem.eql(u8, s, "a\r\nb"));
}
// Returns an error if the rest of the string is non-whitespace
pub fn strLenNonWhitespace(s: []const u8) !u32 {
var i: u32 = 0;
while (i < s.len and s[i] != ' ' and s[i] != '\t' and s[i] != '\n' and s[i] != '\r') {
i += 1;
}
if (i == s.len) {
return error.EndOfString;
}
return i;
}
test "strLenNonWhitespace" {
testing.expect((try strLenNonWhitespace("abc\t \t")) == 3);
}
// Returns bytes until next \n or \r\n
pub fn getLineLen(s: []const u8) !u32 {
var i: u32 = 0;
while (i < s.len and s[i] != '\n' and s[i] != '\r') {
i += 1;
}
if (i == s.len) {
return error.EndOfString;
}
return i;
}
test "getLineLen" {
testing.expect((try getLineLen("abc\n")) == 3);
}
pub fn caseInsensitiveStartsWith(s: []const u8, prefix: []const u8) bool {
assert(prefix.len != 0 and s.len != 0);
if (prefix.len > s.len or prefix.len == 0 or s.len == 0) {
return false;
}
var i: u32 = 0;
while (i < prefix.len) : (i += 1) {
if (s[i] == prefix[i]) {
continue;
}
if (s[i] >= 'a' and s[i] < 'z') {
if (prefix[i] != s[i] - ('a' - 'A')) {
return false;
}
} else if (s[i] >= 'A' and s[i] < 'Z') {
if (prefix[i] != s[i] + ('a' - 'A')) {
return false;
}
} else {
return false;
}
}
return true;
}
test "caseInsensitiveStartsWith" {
testing.expect(caseInsensitiveStartsWith("abc\n", "aBc"));
testing.expect(!caseInsensitiveStartsWith("abc\n", "5"));
testing.expect(!caseInsensitiveStartsWith("abc\n", "long string"));
testing.expect(!caseInsensitiveStartsWith("abc\n", " a"));
testing.expect(!caseInsensitiveStartsWith("abc a: def\n", "abc:"));
}
// Ignores end whitespace on s
pub fn caseInsensitiveCompareIgnoreEndWhitespace(s: []const u8, b: []const u8) bool {
if (!caseInsensitiveStartsWith(s, b)) {
return false;
}
if (s.len == b.len) {
return true;
}
var s2 = s[b.len..];
var i: u32 = 0;
while (i < s2.len) : (i += 1) {
if (s2[i] != ' ' and s2[i] != '\t' and s2[i] != '\r' and s2[i] != '\n') {
return false;
}
}
return true;
}
test "caseInsensitiveCompareIgnoreEndWhitespace" {
testing.expect(caseInsensitiveCompareIgnoreEndWhitespace("abc ", "aBc"));
testing.expect(!caseInsensitiveCompareIgnoreEndWhitespace("abc a", "aBc"));
testing.expect(!caseInsensitiveCompareIgnoreEndWhitespace("abcd ", "aBc "));
}
// Returns error when end of string is reached
// Returns null when end of line is reached
// Moves slice to start of next field/line
pub fn getCSVField(s_: *([]const u8)) !?[]const u8 {
if (s_.*.len == 0) {
return error.EndOfString;
}
if (s_.*[0] == '\n') {
s_.* = s_.*[1..];
return null;
}
if (s_.*[0] == '\r') {
if (s_.*.len > 1 and s_.*[1] == '\n') {
s_.* = s_.*[2..];
} else {
s_.* = s_.*[1..];
}
return null;
}
const s = s_.*;
var i: u32 = 0;
while (i < s.len and s[i] != ',' and s[i] != '\n' and s[i] != '\r') {
i += 1;
}
if (i == s.len) {
s_.* = s[s.len - 1 .. s.len - 1];
assert(s_.*.len == 0);
return s;
}
s_.* = s[i..];
if (s_.*[0] == ',') {
s_.* = s_.*[1..];
}
return s[0..i];
}
test "csv" {
var s: []const u8 = "a,b,c\nc,d,eee\n,,f,\n";
testing.expect(std.mem.eql(u8, (try getCSVField(&s)).?, "a"));
testing.expect(std.mem.eql(u8, (try getCSVField(&s)).?, "b"));
testing.expect(std.mem.eql(u8, (try getCSVField(&s)).?, "c"));
testing.expect((try getCSVField(&s)) == null);
try skipWhitespace(&s);
testing.expect(std.mem.eql(u8, (try getCSVField(&s)).?, "c"));
testing.expect(std.mem.eql(u8, (try getCSVField(&s)).?, "d"));
testing.expect(std.mem.eql(u8, (try getCSVField(&s)).?, "eee"));
testing.expect((try getCSVField(&s)) == null);
try skipWhitespace(&s);
testing.expect(std.mem.eql(u8, (try getCSVField(&s)).?, ""));
testing.expect(std.mem.eql(u8, (try getCSVField(&s)).?, ""));
testing.expect(std.mem.eql(u8, (try getCSVField(&s)).?, "f"));
testing.expect((try getCSVField(&s)) == null);
testing.expectError(error.EndOfString, getCSVField(&s));
} | src/Parse.zig |
const std = @import("std");
const Postgres = @import("postgres");
const build_options = @import("build_options");
const Pg = Postgres.Pg;
const Result = Postgres.Result;
const Builder = Postgres.Builder;
const FieldInfo = Postgres.FieldInfo;
const Parser = Postgres.Parser;
const testing = std.testing;
const Allocator = std.mem.Allocator;
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = &gpa.allocator;
const Users = struct {
id: u16,
name: []const u8,
age: u16,
};
test "database" {
var db = try Pg.connect(allocator, build_options.db_uri);
defer db.deinit();
const schema =
\\CREATE DATABASE IF NOT EXISTS root;
\\CREATE TABLE IF NOT EXISTS users (id INT, name TEXT, age INT);
;
_ = try db.exec(schema);
var data = Users{ .id = 2, .name = "Steve", .age = 25 };
var data2 = Users{ .id = 3, .name = "Tom", .age = 25 };
_ = try db.insert(Users{ .id = 1, .name = "Charlie", .age = 20 });
_ = try db.insert(data);
//Insert pointer
_ = try db.insert(&data2);
//Insert array
_ = try db.insert(&[_]Users{
Users{ .id = 4, .name = "Tony", .age = 33 },
Users{ .id = 5, .name = "Sara", .age = 33 },
Users{ .id = 6, .name = "Tony", .age = 33 },
});
var result = try db.execValues("SELECT * FROM users WHERE name = {s}", .{"Charlie"});
var result2 = try db.execValues("SELECT * FROM users WHERE id = {d}", .{2});
var result3 = try db.execValues("SELECT * FROM users WHERE age = {d}", .{25});
var result4 = try db.execValues("SELECT * FROM users WHERE age = {d}", .{33});
//When all results are not parsed, the memory must be manually deinited
defer result4.deinit();
var user = result.parse(Users, null).?;
var user2 = result2.parse(Users, null).?;
var user3 = result4.parse(Users, null).?;
while (result3.parse(Users, null)) |res| testing.expectEqual(res.age, 25);
//Temp memory
var temp_memory = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const temp_allocator = &temp_memory.allocator;
//SQL query builder
var builder = Builder.new(.Update, temp_allocator).table("users").where(try Builder.buildQuery("WHERE id = {d};", .{2}, temp_allocator));
defer {
builder.deinit();
temp_memory.deinit();
}
try builder.addColumn("name");
try builder.addValue("Harold");
try builder.end();
_ = try db.exec(builder.command());
var result5 = try db.execValues("SELECT * FROM users WHERE id = {d}", .{2});
var user4 = result5.parse(Users, null).?;
testing.expectEqual(result.rows, 1);
testing.expectEqual(result2.rows, 1);
testing.expectEqual(result3.rows, 2);
testing.expectEqual(result4.rows, 3);
testing.expectEqual(user.id, 1);
testing.expectEqual(user.age, 20);
testing.expectEqual(user2.id, 2);
testing.expectEqualStrings(user2.name, "Steve");
testing.expectEqual(user3.id, 4);
testing.expectEqualStrings(user3.name, "Tony");
testing.expectEqual(user4.id, 2);
testing.expectEqualStrings(user4.name, "Harold");
_ = try db.exec("DROP TABLE users");
}
const Stats = struct { wins: u16 = 0, losses: u16 = 0 };
const Player = struct {
id: u16,
name: []const u8,
stats: Stats,
cards: ?[][]const u8 = null,
pub fn onSave(self: *Player, comptime field: FieldInfo, builder: *Builder, value: anytype) !void {
switch (field.type) {
?[][]const u8 => try builder.addStringArray(value.?),
Stats => try builder.addJson(value),
else => {},
}
}
pub fn onLoad(self: *Player, comptime field: FieldInfo, value: []const u8, parser: Parser) !void {
switch (field.type) {
?[][]const u8 => self.cards = try parser.parseArray(value, ","),
Stats => self.stats = try parser.parseJson(Stats, value),
else => {},
}
}
};
test "Custom types" {
var db = try Pg.connect(allocator, build_options.db_uri);
defer {
std.debug.assert(!gpa.deinit());
db.deinit();
}
const schema =
\\CREATE DATABASE IF NOT EXISTS root;
\\CREATE TABLE IF NOT EXISTS player (id INT, name TEXT, stats JSONB, cards STRING[]);
;
_ = try db.exec(schema);
var cards = [3][]const u8{
"Ace",
"2",
"Queen",
};
var data = Player{ .id = 2, .name = "Steve", .stats = .{ .wins = 5, .losses = 3 }, .cards = cards[0..] };
_ = try db.insert(&data);
var result = try db.execValues("SELECT * FROM player WHERE name = {s}", .{"Steve"});
var data_cache = result.parse(Player, allocator).?;
testing.expectEqual(data_cache.id, 2);
testing.expectEqualStrings(data_cache.name, "Steve");
testing.expectEqual(data_cache.stats.wins, 5);
testing.expectEqual(data_cache.stats.losses, 3);
//Free cards allocation
defer allocator.free(data_cache.cards.?);
_ = try db.exec("DROP TABLE player");
}
const KeyValue = struct {
id: ?u32 = null,
value: i32,
};
test "Nullable type" {
var db = try Pg.connect(allocator, build_options.db_uri);
defer {
std.debug.assert(!gpa.deinit());
db.deinit();
}
const schema =
\\CREATE DATABASE IF NOT EXISTS root;
\\CREATE TABLE IF NOT EXISTS keyValue (id SERIAL PRIMARY KEY, value int);
;
_ = try db.exec(schema);
_ = try db.insert(&[_]KeyValue{
KeyValue{ .value = 42 },
KeyValue{ .value = 741 },
KeyValue{ .value = 33 },
});
var result = try db.execValues("SELECT * FROM keyValue WHERE value = {d}", .{42});
var value42 = result.parse(KeyValue, null).?;
testing.expect(value42.id != null);
testing.expectEqual(value42.value, 42);
var result2 = try db.execValues("SELECT * FROM keyValue WHERE value = {d}", .{33});
var value33 = result2.parse(KeyValue, null).?;
testing.expect(value33.id != null);
testing.expect(value33.id > value42.id);
_ = try db.exec("DROP TABLE keyValue");
} | tests/database.zig |
const std = @import("std");
const expectEqual = std.testing.expectEqual;
pub const alloc = std.testing.allocator;
pub fn expect(pred: bool) !void {
try std.testing.expect(pred);
}
pub fn expectError(act_err_union: anytype, exp: anyerror) !void {
return std.testing.expectError(exp, act_err_union);
}
pub fn eq(act: anytype, exp: @TypeOf(act)) !void {
try std.testing.expectEqual(exp, act);
}
// Currently zig doesn't let you use @TypeOf on a arg to the right. We'll want this when it does.
// pub fn eq(act: @TypeOf(exp), exp: anytype) !void {
// try std.testing.expectEqual(exp, act);
// }
pub fn eqT(comptime T: type, act: T, exp: T) !void {
try std.testing.expectEqual(exp, act);
}
pub fn neq(act: anytype, exp: @TypeOf(act)) !void {
// TODO: expectEqual still prints debug messages when not equal.
std.testing.expectEqual(exp, act) catch return;
return error.Equal;
}
test "neq" {
neq(1, 1) catch {};
try neq(1, 2);
}
pub fn eqApprox(act: anytype, exp: @TypeOf(act), tolerance: @TypeOf(act)) !void {
try std.testing.expectApproxEqAbs(exp, act, tolerance);
}
pub fn eqApproxEps(act: anytype, exp: @TypeOf(act)) !void {
const eps = comptime std.math.epsilon(@TypeOf(exp));
try eqApprox(act, exp, eps);
}
// Format using decimal.
pub fn eqApproxDec(act: anytype, exp: @TypeOf(act), tolerance: @TypeOf(act)) !void {
const T = @TypeOf(exp);
switch (@typeInfo(T)) {
.Float => if (!std.math.approxEqAbs(T, exp, act, tolerance)) {
std.debug.print("actual {d}, not within absolute tolerance {d:.3} of expected {d}\n", .{ act, tolerance, exp });
return error.TestExpectedApproxEqAbs;
},
.ComptimeFloat => @compileError("Cannot approximately compare two comptime_float values"),
else => @compileError("Unable to compare non floating point values"),
}
}
pub fn eqUnionEnum(act: anytype, exp: @Type(.EnumLiteral)) !void {
if (@typeInfo(@TypeOf(act)) == .Union) {
try eq(@enumToInt(act), @enumToInt(@as(@typeInfo(@TypeOf(act)).Union.tag_type.?, exp)));
} else {
unreachable;
}
}
pub fn eqStr(act: []const u8, exp: []const u8) !void {
try std.testing.expectEqualStrings(exp, act);
}
pub fn eqSlice(comptime T: type, act: []const T, exp: []const T) !void {
try std.testing.expectEqualSlices(T, exp, act);
}
pub fn eqStringSlices(act: []const []const u8, exp: []const []const u8) !void {
const S = struct {
fn check(act_: []const u8, exp_: []const u8) !void {
try eqSlice(u8, act_, exp_);
}
};
try eqSliceCb([]const u8, S.check, act, exp);
}
pub fn eqSliceCb(comptime T: type, cb: fn (act: T, exp: T) anyerror!void, act_slice: []const T, exp_slice: []const T) !void {
try eq(act_slice.len, exp_slice.len);
for (act_slice) |act, i| {
cb(act, exp_slice[i]) catch |err| {
std.debug.print("expected {any}, found {any} at idx {}\n", .{ exp_slice[i], act, i });
return err;
};
}
}
pub fn fail() !void {
return error.Fail;
}
pub fn setLogLevel(level: std.log.Level) void {
std.testing.log_level = level;
}
var mocks: std.ArrayList(*Mock) = std.ArrayList(*Mock).init(alloc);
pub fn unitTrace(loc: std.builtin.SourceLocation) void {
for (mocks.items) |mock| {
if (mock.funcs.getEntry(loc.fn_name)) |entry| {
entry.value_ptr.call_count += 1;
}
}
}
pub export fn unitTraceC(fn_name_ptr: [*]const u8, fn_name_len: usize) void {
const fn_name = fn_name_ptr[0..fn_name_len];
for (mocks.items) |mock| {
if (mock.funcs.getEntry(fn_name)) |entry| {
entry.value_ptr.call_count += 1;
}
}
}
pub const Mock = struct {
const Self = @This();
funcs: std.StringHashMap(FuncMock),
pub fn create() *Self {
const m = alloc.create(Mock) catch unreachable;
m.* = .{
.funcs = std.StringHashMap(FuncMock).init(alloc),
};
mocks.append(m) catch unreachable;
return m;
}
pub fn destroy(self: *Self) void {
self.funcs.deinit();
alloc.destroy(self);
for (mocks.items) |it, i| {
if (it == self) {
_ = mocks.orderedRemove(i);
if (mocks.items.len == 0) {
mocks.clearAndFree();
}
break;
}
}
}
pub fn add(self: *Self, comptime E: @Type(.EnumLiteral)) void {
std.debug.print("add {s}\n", .{@tagName(E)});
std.debug.assert(!self.funcs.contains(@tagName(E)));
self.funcs.put(@tagName(E), .{
.call_count = 0,
}) catch unreachable;
}
pub fn getNumCalls(self: Self, comptime E: @Type(.EnumLiteral)) u32 {
return self.funcs.get(@tagName(E)).?.call_count;
}
};
const FuncMock = struct {
call_count: u32,
}; | stdx/testing.zig |
const std = @import("std");
const mach = @import("mach");
const gpu = @import("gpu");
const glfw = @import("glfw");
const App = mach.App(*FrameParams, .{});
const Vertex = struct {
pos: @Vector(4, f32),
uv: @Vector(2, f32),
};
const vertices = [_]Vertex{
.{ .pos = .{ -1, -1, 0, 1 }, .uv = .{ 0, 0 } },
.{ .pos = .{ 1, -1, 0, 1 }, .uv = .{ 1, 0 } },
.{ .pos = .{ 1, 1, 0, 1 }, .uv = .{ 1, 1 } },
.{ .pos = .{ -1, 1, 0, 1 }, .uv = .{ 0, 1 } },
};
const indices = [_]u16{ 0, 1, 2, 2, 3, 0 };
const UniformBufferObject = struct {
resolution: @Vector(2, f32),
time: f32,
};
var timer: std.time.Timer = undefined;
pub fn main() !void {
timer = try std.time.Timer.start();
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var allocator = gpa.allocator();
const ctx = try allocator.create(FrameParams);
var app = try App.init(allocator, ctx, .{});
app.window.setKeyCallback(struct {
fn callback(window: glfw.Window, key: glfw.Key, scancode: i32, action: glfw.Action, mods: glfw.Mods) void {
_ = scancode;
_ = mods;
if (action == .press) {
switch (key) {
.space => window.setShouldClose(true),
else => {},
}
}
}
}.callback);
// On linux if we don't set a minimum size, you can squish the window to 0 pixels of width and height,
// this makes some strange effects when that happens, so it's better to leave a minimum size to avoid that,
// this doesn't prevent you from minimizing the window.
try app.window.setSizeLimits(.{ .width = 20, .height = 20 }, .{ .width = null, .height = null });
var fragment_file: std.fs.File = undefined;
var last_mtime: i128 = undefined;
if (std.fs.cwd().openFile("shaderexp/frag.wgsl", .{ .mode = .read_only })) |file| {
fragment_file = file;
if (file.stat()) |stat| {
last_mtime = stat.mtime;
} else |err| {
std.debug.print("Something went wrong when attempting to stat file: {}\n", .{err});
return;
}
} else |e| {
std.debug.print("Something went wrong when attempting to open file: {}\n", .{e});
return;
}
defer fragment_file.close();
var code = try fragment_file.readToEndAllocOptions(allocator, std.math.maxInt(u16), null, 1, 0);
defer allocator.free(code);
const queue = app.device.getQueue();
const vertex_buffer = app.device.createBuffer(&.{
.usage = .{ .vertex = true },
.size = @sizeOf(Vertex) * vertices.len,
.mapped_at_creation = true,
});
var vertex_mapped = vertex_buffer.getMappedRange(Vertex, 0, vertices.len);
std.mem.copy(Vertex, vertex_mapped, vertices[0..]);
vertex_buffer.unmap();
defer vertex_buffer.release();
const index_buffer = app.device.createBuffer(&.{
.usage = .{ .index = true },
.size = @sizeOf(u16) * indices.len,
.mapped_at_creation = true,
});
var index_mapped = index_buffer.getMappedRange(@TypeOf(indices[0]), 0, indices.len);
std.mem.copy(u16, index_mapped, indices[0..]);
index_buffer.unmap();
defer index_buffer.release();
// We need a bgl to bind the UniformBufferObject, but it is also needed for creating
// the RenderPipeline, so we pass it to recreatePipeline as a pointer
var bgl: gpu.BindGroupLayout = undefined;
const pipeline = recreatePipeline(&app, code, &bgl);
const uniform_buffer = app.device.createBuffer(&.{
.usage = .{ .copy_dst = true, .uniform = true },
.size = @sizeOf(UniformBufferObject),
.mapped_at_creation = false,
});
defer uniform_buffer.release();
const bind_group = app.device.createBindGroup(
&gpu.BindGroup.Descriptor{
.layout = bgl,
.entries = &.{
gpu.BindGroup.Entry.buffer(0, uniform_buffer, 0, @sizeOf(UniformBufferObject)),
},
},
);
defer bind_group.release();
ctx.* = FrameParams{
.pipeline = pipeline,
.queue = queue,
.vertex_buffer = vertex_buffer,
.index_buffer = index_buffer,
.uniform_buffer = uniform_buffer,
.bind_group = bind_group,
.fragment_shader_file = fragment_file,
.fragment_shader_code = code,
.last_mtime = last_mtime,
};
bgl.release();
try app.run(.{ .frame = frame });
}
const FrameParams = struct {
pipeline: gpu.RenderPipeline,
queue: gpu.Queue,
vertex_buffer: gpu.Buffer,
index_buffer: gpu.Buffer,
uniform_buffer: gpu.Buffer,
bind_group: gpu.BindGroup,
fragment_shader_file: std.fs.File,
fragment_shader_code: [:0]const u8,
last_mtime: i128,
};
fn frame(app: *App, params: *FrameParams) !void {
if (params.fragment_shader_file.stat()) |stat| {
if (params.last_mtime < stat.mtime) {
std.log.info("The fragment shader has been changed", .{});
params.last_mtime = stat.mtime;
params.fragment_shader_file.seekTo(0) catch unreachable;
params.fragment_shader_code = params.fragment_shader_file.readToEndAllocOptions(app.allocator, std.math.maxInt(u32), null, 1, 0) catch |err| {
std.log.err("Err: {}", .{err});
return;
};
params.pipeline = recreatePipeline(app, params.fragment_shader_code, null);
}
} else |err| {
std.log.err("Something went wrong when attempting to stat file: {}\n", .{err});
}
const back_buffer_view = app.swap_chain.?.getCurrentTextureView();
const color_attachment = gpu.RenderPassColorAttachment{
.view = back_buffer_view,
.resolve_target = null,
.clear_value = std.mem.zeroes(gpu.Color),
.load_op = .clear,
.store_op = .store,
};
const encoder = app.device.createCommandEncoder(null);
const render_pass_info = gpu.RenderPassEncoder.Descriptor{
.color_attachments = &.{color_attachment},
.depth_stencil_attachment = null,
};
const time = @intToFloat(f32, timer.read()) / @as(f32, std.time.ns_per_s);
const ubo = UniformBufferObject{
.resolution = .{ @intToFloat(f32, app.current_desc.width), @intToFloat(f32, app.current_desc.height) },
.time = time,
};
encoder.writeBuffer(params.uniform_buffer, 0, UniformBufferObject, &.{ubo});
const pass = encoder.beginRenderPass(&render_pass_info);
pass.setVertexBuffer(0, params.vertex_buffer, 0, @sizeOf(Vertex) * vertices.len);
pass.setIndexBuffer(params.index_buffer, .uint16, 0, @sizeOf(u16) * indices.len);
pass.setPipeline(params.pipeline);
pass.setBindGroup(0, params.bind_group, &.{0});
pass.drawIndexed(indices.len, 1, 0, 0, 0);
pass.end();
pass.release();
var command = encoder.finish(null);
encoder.release();
params.queue.submit(&.{command});
command.release();
app.swap_chain.?.present();
back_buffer_view.release();
}
fn recreatePipeline(app: *const App, fragment_shader_code: [:0]const u8, bgl: ?*gpu.BindGroupLayout) gpu.RenderPipeline {
const vs_module = app.device.createShaderModule(&.{
.label = "my vertex shader",
.code = .{ .wgsl = @embedFile("vert.wgsl") },
});
defer vs_module.release();
const vertex_attributes = [_]gpu.VertexAttribute{
.{ .format = .float32x4, .offset = @offsetOf(Vertex, "pos"), .shader_location = 0 },
.{ .format = .float32x2, .offset = @offsetOf(Vertex, "uv"), .shader_location = 1 },
};
const vertex_buffer_layout = gpu.VertexBufferLayout{
.array_stride = @sizeOf(Vertex),
.step_mode = .vertex,
.attribute_count = vertex_attributes.len,
.attributes = &vertex_attributes,
};
// Check wether the fragment shader code compiled successfully, if not
// print the validation layer error and show a black screen
app.device.pushErrorScope(.validation);
var fs_module = app.device.createShaderModule(&gpu.ShaderModule.Descriptor{
.label = "my fragment shader",
.code = .{ .wgsl = fragment_shader_code },
});
var error_occurred: bool = false;
// popErrorScope() returns always true, (unless maybe it fails to capture the error scope?)
_ = app.device.popErrorScope(&gpu.ErrorCallback.init(*bool, &error_occurred, struct {
fn callback(ctx: *bool, typ: gpu.ErrorType, message: [*:0]const u8) void {
if (typ != .noError) {
std.debug.print("🔴🔴🔴🔴:\n{s}\n", .{message});
ctx.* = true;
}
}
}.callback));
if (error_occurred) {
fs_module = app.device.createShaderModule(&gpu.ShaderModule.Descriptor{
.label = "my fragment shader",
.code = .{ .wgsl = @embedFile("black_screen_frag.wgsl") },
});
}
defer fs_module.release();
const blend = gpu.BlendState{
.color = .{
.operation = .add,
.src_factor = .one,
.dst_factor = .zero,
},
.alpha = .{
.operation = .add,
.src_factor = .one,
.dst_factor = .zero,
},
};
const color_target = gpu.ColorTargetState{
.format = app.swap_chain_format,
.blend = &blend,
.write_mask = gpu.ColorWriteMask.all,
};
const fragment = gpu.FragmentState{
.module = fs_module,
.entry_point = "main",
.targets = &.{color_target},
.constants = null,
};
const bgle = gpu.BindGroupLayout.Entry.buffer(0, .{ .fragment = true }, .uniform, true, 0);
// bgl is needed outside, for the creation of the uniform_buffer in main
const bgl_tmp = app.device.createBindGroupLayout(
&gpu.BindGroupLayout.Descriptor{
.entries = &.{bgle},
},
);
defer {
// In frame we don't need to use bgl, so we can release it inside this function, else we pass bgl
if (bgl == null) {
bgl_tmp.release();
} else {
bgl.?.* = bgl_tmp;
}
}
const bind_group_layouts = [_]gpu.BindGroupLayout{bgl_tmp};
const pipeline_layout = app.device.createPipelineLayout(&.{
.bind_group_layouts = &bind_group_layouts,
});
defer pipeline_layout.release();
const pipeline_descriptor = gpu.RenderPipeline.Descriptor{
.fragment = &fragment,
.layout = pipeline_layout,
.depth_stencil = null,
.vertex = .{
.module = vs_module,
.entry_point = "main",
.buffers = &.{vertex_buffer_layout},
},
.multisample = .{
.count = 1,
.mask = 0xFFFFFFFF,
.alpha_to_coverage_enabled = false,
},
.primitive = .{
.front_face = .ccw,
.cull_mode = .none,
.topology = .triangle_list,
.strip_index_format = .none,
},
};
// Create the render pipeline. Even if the shader compilation succeeded, this could fail if the
// shader is missing a `main` entrypoint.
app.device.pushErrorScope(.validation);
const pipeline = app.device.createRenderPipeline(&pipeline_descriptor);
// popErrorScope() returns always true, (unless maybe it fails to capture the error scope?)
_ = app.device.popErrorScope(&gpu.ErrorCallback.init(*bool, &error_occurred, struct {
fn callback(ctx: *bool, typ: gpu.ErrorType, message: [*:0]const u8) void {
if (typ != .noError) {
std.debug.print("🔴🔴🔴🔴:\n{s}\n", .{message});
ctx.* = true;
}
}
}.callback));
if (error_occurred) {
// Retry with black_screen_frag which we know will work.
return recreatePipeline(app, @embedFile("black_screen_frag.wgsl"), bgl);
}
return pipeline;
} | shaderexp/main.zig |
const aoc = @import("../aoc.zig");
const std = @import("std");
const Intersector = struct {
coords_encountered: std.AutoHashMap(aoc.Coord2D, void),
coords_crossed: std.AutoHashMap(aoc.Coord2D, void),
fn init(allocator: std.mem.Allocator) Intersector {
return .{
.coords_encountered = std.AutoHashMap(aoc.Coord2D, void).init(allocator),
.coords_crossed = std.AutoHashMap(aoc.Coord2D, void).init(allocator),
};
}
fn deinit(self: *Intersector) void {
self.coords_encountered.deinit();
self.coords_crossed.deinit();
}
fn process(self: *Intersector, from: aoc.Coord2D, to: aoc.Coord2D) !void {
const delta = aoc.Coord2D.init(.{ cmp(from.x, to.x), cmp(from.y, to.y) });
var curr = from;
while (true) {
if ((try self.coords_encountered.fetchPut(curr, {})) != null) {
try self.coords_crossed.put(curr, {});
}
if (curr.equals(to)) {
break;
}
curr.mutAdd(delta);
}
}
inline fn cmp(b: isize, a: isize) i8 {
return if (a < b) -1 else if (a > b) @as(i8, 1) else 0;
}
};
pub fn run(problem: *aoc.Problem) !aoc.Solution {
var straight_intersector = Intersector.init(problem.allocator);
defer straight_intersector.deinit();
var diag_intersector = Intersector.init(problem.allocator);
defer diag_intersector.deinit();
while (problem.line()) |line| {
var tokens = std.mem.tokenize(u8, line, " ,->");
const from = aoc.Coord2D.init(.{
try std.fmt.parseInt(isize, tokens.next().?, 10),
try std.fmt.parseInt(isize, tokens.next().?, 10),
});
const to = aoc.Coord2D.init(.{
try std.fmt.parseInt(isize, tokens.next().?, 10),
try std.fmt.parseInt(isize, tokens.next().?, 10),
});
if (from.x == to.x or from.y == to.y) {
try straight_intersector.process(from, to);
}
try diag_intersector.process(from, to);
}
return problem.solution(
straight_intersector.coords_crossed.count(),
diag_intersector.coords_crossed.count()
);
} | src/main/zig/2021/day05.zig |
const std = @import("std");
const builtin = @import("builtin");
const mem = std.mem;
const TypeInfo = std.builtin.TypeInfo;
const TypeId = std.builtin.TypeId;
const expect = std.testing.expect;
const expectEqualStrings = std.testing.expectEqualStrings;
test "type info: tag type, void info" {
try testBasic();
comptime try testBasic();
}
fn testBasic() !void {
try expectEqual(@typeInfo(TypeInfo).Union.tag_type, TypeId);
const void_info = @typeInfo(void);
try expectEqual(void_info, TypeId.Void);
try expectEqual(void_info.Void, {});
}
test "type info: integer, floating point type info" {
try testIntFloat();
comptime try testIntFloat();
}
fn testIntFloat() !void {
const u8_info = @typeInfo(u8);
try expectEqual(u8_info, .Int);
try expectEqual(u8_info.Int.signedness, .unsigned);
try expectEqual(u8_info.Int.bits, 8);
const f64_info = @typeInfo(f64);
try expectEqual(f64_info, .Float);
try expectEqual(f64_info.Float.bits, 64);
}
test "type info: pointer type info" {
try testPointer();
comptime try testPointer();
}
fn testPointer() !void {
const u32_ptr_info = @typeInfo(*u32);
try expectEqual(u32_ptr_info, .Pointer);
try expectEqual(u32_ptr_info.Pointer.size, TypeInfo.Pointer.Size.One);
try expectEqual(u32_ptr_info.Pointer.is_const, false);
try expectEqual(u32_ptr_info.Pointer.is_volatile, false);
try expectEqual(u32_ptr_info.Pointer.alignment, @alignOf(u32));
try expectEqual(u32_ptr_info.Pointer.child, u32);
try expectEqual(u32_ptr_info.Pointer.sentinel, null);
}
test "type info: unknown length pointer type info" {
try testUnknownLenPtr();
comptime try testUnknownLenPtr();
}
fn testUnknownLenPtr() !void {
const u32_ptr_info = @typeInfo([*]const volatile f64);
try expectEqual(u32_ptr_info, .Pointer);
try expectEqual(u32_ptr_info.Pointer.size, TypeInfo.Pointer.Size.Many);
try expectEqual(u32_ptr_info.Pointer.is_const, true);
try expectEqual(u32_ptr_info.Pointer.is_volatile, true);
try expectEqual(u32_ptr_info.Pointer.sentinel, null);
try expectEqual(u32_ptr_info.Pointer.alignment, @alignOf(f64));
try expectEqual(u32_ptr_info.Pointer.child, f64);
}
test "type info: null terminated pointer type info" {
try testNullTerminatedPtr();
comptime try testNullTerminatedPtr();
}
fn testNullTerminatedPtr() !void {
const ptr_info = @typeInfo([*:0]u8);
try expectEqual(ptr_info, .Pointer);
try expectEqual(ptr_info.Pointer.size, TypeInfo.Pointer.Size.Many);
try expectEqual(ptr_info.Pointer.is_const, false);
try expectEqual(ptr_info.Pointer.is_volatile, false);
try expectEqual(ptr_info.Pointer.sentinel.?, 0);
try expect(@typeInfo([:0]u8).Pointer.sentinel != null);
}
test "type info: C pointer type info" {
try testCPtr();
comptime try testCPtr();
}
fn testCPtr() !void {
const ptr_info = @typeInfo([*c]align(4) const i8);
try expectEqual(ptr_info, .Pointer);
try expectEqual(ptr_info.Pointer.size, .C);
try expect(ptr_info.Pointer.is_const);
try expect(!ptr_info.Pointer.is_volatile);
try expectEqual(ptr_info.Pointer.alignment, 4);
try expectEqual(ptr_info.Pointer.child, i8);
}
test "type info: slice type info" {
try testSlice();
comptime try testSlice();
}
fn testSlice() !void {
const u32_slice_info = @typeInfo([]u32);
try expectEqual(u32_slice_info, .Pointer);
try expectEqual(u32_slice_info.Pointer.size, .Slice);
try expectEqual(u32_slice_info.Pointer.is_const, false);
try expectEqual(u32_slice_info.Pointer.is_volatile, false);
try expectEqual(u32_slice_info.Pointer.alignment, 4);
try expectEqual(u32_slice_info.Pointer.child, u32);
}
test "type info: array type info" {
try testArray();
comptime try testArray();
}
fn testArray() !void {
{
const info = @typeInfo([42]u8);
try expectEqual(info, .Array);
try expectEqual(info.Array.len, 42);
try expectEqual(info.Array.child, u8);
try expectEqual(info.Array.sentinel, null);
}
{
const info = @typeInfo([10:0]u8);
try expectEqual(info.Array.len, 10);
try expectEqual(info.Array.child, u8);
try expectEqual(info.Array.sentinel.?, @as(u8, 0));
try expectEqual(@sizeOf([10:0]u8), info.Array.len + 1);
}
}
test "type info: optional type info" {
try testOptional();
comptime try testOptional();
}
fn testOptional() !void {
const null_info = @typeInfo(?void);
try expectEqual(null_info, .Optional);
try expectEqual(null_info.Optional.child, void);
}
test "type info: error set, error union info" {
try testErrorSet();
comptime try testErrorSet();
}
fn testErrorSet() !void {
const TestErrorSet = error{
First,
Second,
Third,
};
const error_set_info = @typeInfo(TestErrorSet);
try expectEqual(error_set_info, .ErrorSet);
try expectEqual(error_set_info.ErrorSet.?.len, 3);
try expect(mem.eql(u8, error_set_info.ErrorSet.?[0].name, "First"));
const error_union_info = @typeInfo(TestErrorSet!usize);
try expectEqual(error_union_info, .ErrorUnion);
try expectEqual(error_union_info.ErrorUnion.error_set, TestErrorSet);
try expectEqual(error_union_info.ErrorUnion.payload, usize);
const global_info = @typeInfo(anyerror);
try expectEqual(global_info, .ErrorSet);
try expectEqual(global_info.ErrorSet, null);
}
test "type info: enum info" {
try testEnum();
comptime try testEnum();
}
fn testEnum() !void {
const Os = enum {
Windows,
Macos,
Linux,
FreeBSD,
};
const os_info = @typeInfo(Os);
try expectEqual(os_info, .Enum);
try expectEqual(os_info.Enum.layout, .Auto);
try expectEqual(os_info.Enum.fields.len, 4);
try expect(mem.eql(u8, os_info.Enum.fields[1].name, "Macos"));
try expectEqual(os_info.Enum.fields[3].value, 3);
try expectEqual(os_info.Enum.tag_type, u2);
try expectEqual(os_info.Enum.decls.len, 0);
}
test "type info: union info" {
try testUnion();
comptime try testUnion();
}
fn testUnion() !void {
const typeinfo_info = @typeInfo(TypeInfo);
try expectEqual(typeinfo_info, .Union);
try expectEqual(typeinfo_info.Union.layout, .Auto);
try expectEqual(typeinfo_info.Union.tag_type.?, TypeId);
try expectEqual(typeinfo_info.Union.fields.len, 25);
try expectEqual(typeinfo_info.Union.fields[4].field_type, @TypeOf(@typeInfo(u8).Int));
try expectEqual(typeinfo_info.Union.decls.len, 22);
const TestNoTagUnion = union {
Foo: void,
Bar: u32,
};
const notag_union_info = @typeInfo(TestNoTagUnion);
try expectEqual(notag_union_info, .Union);
try expectEqual(notag_union_info.Union.tag_type, null);
try expectEqual(notag_union_info.Union.layout, .Auto);
try expectEqual(notag_union_info.Union.fields.len, 2);
try expectEqual(notag_union_info.Union.fields[0].alignment, @alignOf(void));
try expectEqual(notag_union_info.Union.fields[1].field_type, u32);
try expectEqual(notag_union_info.Union.fields[1].alignment, @alignOf(u32));
const TestExternUnion = extern union {
foo: *c_void,
};
const extern_union_info = @typeInfo(TestExternUnion);
try expectEqual(extern_union_info.Union.layout, .Extern);
try expectEqual(extern_union_info.Union.tag_type, null);
try expectEqual(extern_union_info.Union.fields[0].field_type, *c_void);
}
test "type info: struct info" {
try testStruct();
comptime try testStruct();
}
fn testStruct() !void {
const unpacked_struct_info = @typeInfo(TestUnpackedStruct);
try expectEqual(unpacked_struct_info.Struct.is_tuple, false);
try expectEqual(unpacked_struct_info.Struct.fields[0].alignment, @alignOf(u32));
try expectEqual(unpacked_struct_info.Struct.fields[0].default_value.?, 4);
try expectEqualStrings("foobar", unpacked_struct_info.Struct.fields[1].default_value.?);
const struct_info = @typeInfo(TestStruct);
try expectEqual(struct_info, .Struct);
try expectEqual(struct_info.Struct.is_tuple, false);
try expectEqual(struct_info.Struct.layout, .Packed);
try expectEqual(struct_info.Struct.fields.len, 4);
try expectEqual(struct_info.Struct.fields[0].alignment, 2 * @alignOf(usize));
try expectEqual(struct_info.Struct.fields[2].field_type, *TestStruct);
try expectEqual(struct_info.Struct.fields[2].default_value, null);
try expectEqual(struct_info.Struct.fields[3].default_value.?, 4);
try expectEqual(struct_info.Struct.fields[3].alignment, 1);
try expectEqual(struct_info.Struct.decls.len, 2);
try expect(struct_info.Struct.decls[0].is_pub);
try expect(!struct_info.Struct.decls[0].data.Fn.is_extern);
try expectEqual(struct_info.Struct.decls[0].data.Fn.lib_name, null);
try expectEqual(struct_info.Struct.decls[0].data.Fn.return_type, void);
try expectEqual(struct_info.Struct.decls[0].data.Fn.fn_type, fn (*const TestStruct) void);
}
const TestUnpackedStruct = struct {
fieldA: u32 = 4,
fieldB: *const [6:0]u8 = "foobar",
};
const TestStruct = packed struct {
fieldA: usize align(2 * @alignOf(usize)),
fieldB: void,
fieldC: *Self,
fieldD: u32 = 4,
pub fn foo(self: *const Self) void {
_ = self;
}
const Self = @This();
};
test "type info: opaque info" {
try testOpaque();
comptime try testOpaque();
}
fn testOpaque() !void {
const Foo = opaque {
const A = 1;
fn b() void {}
};
const foo_info = @typeInfo(Foo);
try expectEqual(foo_info.Opaque.decls.len, 2);
}
test "type info: function type info" {
// wasm doesn't support align attributes on functions
if (builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64) return error.SkipZigTest;
try testFunction();
comptime try testFunction();
}
fn testFunction() !void {
const fn_info = @typeInfo(@TypeOf(foo));
try expectEqual(fn_info, .Fn);
try expect(fn_info.Fn.alignment > 0);
try expectEqual(fn_info.Fn.calling_convention, .C);
try expect(!fn_info.Fn.is_generic);
try expectEqual(fn_info.Fn.args.len, 2);
try expect(fn_info.Fn.is_var_args);
try expectEqual(fn_info.Fn.return_type.?, usize);
const fn_aligned_info = @typeInfo(@TypeOf(fooAligned));
try expectEqual(fn_aligned_info.Fn.alignment, 4);
const test_instance: TestStruct = undefined;
const bound_fn_info = @typeInfo(@TypeOf(test_instance.foo));
try expectEqual(bound_fn_info, .BoundFn);
try expectEqual(bound_fn_info.BoundFn.args[0].arg_type.?, *const TestStruct);
}
extern fn foo(a: usize, b: bool, ...) callconv(.C) usize;
extern fn fooAligned(a: usize, b: bool, ...) align(4) callconv(.C) usize;
test "typeInfo with comptime parameter in struct fn def" {
const S = struct {
pub fn func(comptime x: f32) void {
_ = x;
}
};
comptime var info = @typeInfo(S);
_ = info;
}
test "type info: vectors" {
try testVector();
comptime try testVector();
}
fn testVector() !void {
const vec_info = @typeInfo(std.meta.Vector(4, i32));
try expectEqual(vec_info, .Vector);
try expectEqual(vec_info.Vector.len, 4);
try expectEqual(vec_info.Vector.child, i32);
}
test "type info: anyframe and anyframe->T" {
try testAnyFrame();
comptime try testAnyFrame();
}
fn testAnyFrame() !void {
{
const anyframe_info = @typeInfo(anyframe->i32);
try expectEqual(anyframe_info, .AnyFrame);
try expectEqual(anyframe_info.AnyFrame.child.?, i32);
}
{
const anyframe_info = @typeInfo(anyframe);
try expectEqual(anyframe_info, .AnyFrame);
try expectEqual(anyframe_info.AnyFrame.child, null);
}
}
test "type info: pass to function" {
_ = passTypeInfo(@typeInfo(void));
_ = comptime passTypeInfo(@typeInfo(void));
}
fn passTypeInfo(comptime info: TypeInfo) type {
_ = info;
return void;
}
test "type info: TypeId -> TypeInfo impl cast" {
_ = passTypeInfo(TypeId.Void);
_ = comptime passTypeInfo(TypeId.Void);
}
test "type info: extern fns with and without lib names" {
const S = struct {
extern fn bar1() void;
extern "cool" fn bar2() void;
};
const info = @typeInfo(S);
comptime {
for (info.Struct.decls) |decl| {
if (std.mem.eql(u8, decl.name, "bar1")) {
try expectEqual(decl.data.Fn.lib_name, null);
} else {
try expectEqualStrings("cool", decl.data.Fn.lib_name.?);
}
}
}
}
test "data field is a compile-time value" {
const S = struct {
const Bar = @as(isize, -1);
};
comptime try expectEqual(@typeInfo(S).Struct.decls[0].data.Var, isize);
}
test "sentinel of opaque pointer type" {
const c_void_info = @typeInfo(*c_void);
try expectEqual(c_void_info.Pointer.sentinel, null);
}
test "@typeInfo does not force declarations into existence" {
const S = struct {
x: i32,
fn doNotReferenceMe() void {
@compileError("test failed");
}
};
comptime try expectEqual(@typeInfo(S).Struct.fields.len, 1);
}
test "defaut value for a var-typed field" {
const S = struct { x: anytype };
try expectEqual(@typeInfo(S).Struct.fields[0].default_value, null);
}
fn add(a: i32, b: i32) i32 {
return a + b;
}
test "type info for async frames" {
switch (@typeInfo(@Frame(add))) {
.Frame => |frame| {
try expectEqual(frame.function, add);
},
else => unreachable,
}
}
test "type info: value is correctly copied" {
comptime {
var ptrInfo = @typeInfo([]u32);
ptrInfo.Pointer.size = .One;
try expectEqual(@typeInfo([]u32).Pointer.size, .Slice);
}
}
test "Declarations are returned in declaration order" {
const S = struct {
const a = 1;
const b = 2;
const c = 3;
const d = 4;
const e = 5;
};
const d = @typeInfo(S).Struct.decls;
try expect(std.mem.eql(u8, d[0].name, "a"));
try expect(std.mem.eql(u8, d[1].name, "b"));
try expect(std.mem.eql(u8, d[2].name, "c"));
try expect(std.mem.eql(u8, d[3].name, "d"));
try expect(std.mem.eql(u8, d[4].name, "e"));
}
test "Struct.is_tuple" {
try expect(@typeInfo(@TypeOf(.{0})).Struct.is_tuple);
try expect(!@typeInfo(@TypeOf(.{ .a = 0 })).Struct.is_tuple);
}
test "StructField.is_comptime" {
const info = @typeInfo(struct { x: u8 = 3, comptime y: u32 = 5 }).Struct;
try expect(!info.fields[0].is_comptime);
try expect(info.fields[1].is_comptime);
}
test "typeInfo resolves usingnamespace declarations" {
const A = struct {
pub const f1 = 42;
};
const B = struct {
const f0 = 42;
usingnamespace A;
};
try expectEqual(@typeInfo(B).Struct.decls.len, 2);
//a
} | test/behavior/type_info.zig |
const std = @import("std");
const utils = @import("utils");
const c = @import("c.zig");
const Direction = @import("common.zig").Direction;
const Script = @import("common.zig").Script;
const Language = @import("common.zig").Language;
const Font = @import("font.zig").Font;
pub const ContentType = enum(u2) {
invalid = c.HB_BUFFER_CONTENT_TYPE_INVALID,
unicode = c.HB_BUFFER_CONTENT_TYPE_UNICODE,
glyphs = c.HB_BUFFER_CONTENT_TYPE_GLYPHS,
};
pub const ClusterLevel = enum(u2) {
monotone_graphemes = c.HB_BUFFER_CLUSTER_LEVEL_MONOTONE_GRAPHEMES,
monotone_characters = c.HB_BUFFER_CLUSTER_LEVEL_MONOTONE_CHARACTERS,
characters = c.HB_BUFFER_CLUSTER_LEVEL_CHARACTERS,
};
pub const SerializeFormat = enum(u31) {
text = c.HB_BUFFER_SERIALIZE_FORMAT_TEXT,
json = c.HB_BUFFER_SERIALIZE_FORMAT_JSON,
invalid = c.HB_BUFFER_SERIALIZE_FORMAT_INVALID,
};
pub const GlyphInfo = extern struct {
codepoint: u32,
cluster: u32,
pub fn getFlags(self: GlyphInfo) GlyphFlags {
return GlyphFlags.from(@intCast(u2, hb_glyph_info_get_glyph_flags(&self)));
}
};
pub const Position = extern struct {
x_advance: i32,
y_advance: i32,
x_offset: i32,
y_offset: i32,
};
pub const GlyphFlags = packed struct {
unsafe_to_break: bool = false,
unsafe_to_concat: bool = false,
pub const Flag = enum(u2) {
unsafe_to_break = c.HB_GLYPH_FLAG_UNSAFE_TO_BREAK,
unsafe_to_concat = c.HB_GLYPH_FLAG_UNSAFE_TO_CONCAT,
};
pub fn from(bits: u2) GlyphFlags {
return utils.bitFieldsToStruct(GlyphFlags, Flag, bits);
}
pub fn cast(self: GlyphFlags) u2 {
return utils.structToBitFields(u2, Flag, self);
}
};
pub const SegmentProps = struct {
direction: Direction,
script: Script,
language: Language,
pub fn from(c_struct: c.hb_segment_properties_t) SegmentProps {
return .{
.direction = @intToEnum(Direction, c_struct.direction),
.script = @intToEnum(Script, c_struct.script),
.language = Language{ .handle = c_struct.language },
};
}
pub fn cast(self: SegmentProps) c.hb_segment_properties_t {
return .{
.reserved1 = undefined,
.reserved2 = undefined,
.direction = @enumToInt(self.direction),
.script = @enumToInt(self.script),
.language = self.language.handle,
};
}
pub fn compare(a: SegmentProps, b: SegmentProps) bool {
return c.hb_segment_properties_equal(&a.cast(), &b.cast()) > 0;
}
pub fn hash(self: SegmentProps) u32 {
return c.hb_segment_properties_hash(&self.cast());
}
pub fn overlay(self: SegmentProps, src: SegmentProps) void {
c.hb_segment_properties_overlay(&self.cast(), &src.cast());
}
};
pub const SerializeFlags = packed struct {
no_clusters: bool = false,
no_positions: bool = false,
no_glyph_names: bool = false,
glyph_extents: bool = false,
glyph_flags: bool = false,
no_advances: bool = false,
pub const Flag = enum(u6) {
no_clusters = c.HB_BUFFER_SERIALIZE_FLAG_NO_CLUSTERS,
no_positions = c.HB_BUFFER_SERIALIZE_FLAG_NO_POSITIONS,
no_glyph_names = c.HB_BUFFER_SERIALIZE_FLAG_NO_GLYPH_NAMES,
glyph_extents = c.HB_BUFFER_SERIALIZE_FLAG_GLYPH_EXTENTS,
glyph_flags = c.HB_BUFFER_SERIALIZE_FLAG_GLYPH_FLAGS,
no_advances = c.HB_BUFFER_SERIALIZE_FLAG_NO_ADVANCES,
};
pub fn from(bits: u6) SerializeFlags {
return utils.bitFieldsToStruct(SerializeFlags, Flag, bits);
}
pub fn cast(self: SerializeFlags) u6 {
return utils.structToBitFields(u6, Flag, self);
}
};
pub const DiffFlags = packed struct {
equal: bool = false,
content_type_mismatch: bool = false,
length_mismatch: bool = false,
notdef_present: bool = false,
dotted_circle_present: bool = false,
codepoint_mismatch: bool = false,
cluster_mismatch: bool = false,
glyph_flags_mismatch: bool = false,
position_mismatch: bool = false,
pub const Flag = enum(u8) {
equal = c.HB_BUFFER_DIFF_FLAG_EQUAL,
content_type_mismatch = c.HB_BUFFER_DIFF_FLAG_CONTENT_TYPE_MISMATCH,
length_mismatch = c.HB_BUFFER_DIFF_FLAG_LENGTH_MISMATCH,
notdef_present = c.HB_BUFFER_DIFF_FLAG_NOTDEF_PRESENT,
dotted_circle_present = c.HB_BUFFER_DIFF_FLAG_DOTTED_CIRCLE_PRESENT,
codepoint_mismatch = c.HB_BUFFER_DIFF_FLAG_CODEPOINT_MISMATCH,
cluster_mismatch = c.HB_BUFFER_DIFF_FLAG_CLUSTER_MISMATCH,
glyph_flags_mismatch = c.HB_BUFFER_DIFF_FLAG_GLYPH_FLAGS_MISMATCH,
position_mismatch = c.HB_BUFFER_DIFF_FLAG_POSITION_MISMATCH,
};
pub fn from(bits: u8) DiffFlags {
return utils.bitFieldsToStruct(DiffFlags, Flag, bits);
}
pub fn cast(self: DiffFlags) u8 {
return utils.structToBitFields(u8, Flag, self);
}
};
pub const Buffer = struct {
pub const Flags = packed struct {
bot: bool = false,
eot: bool = false,
preserve_default_ignorables: bool = false,
remove_default_ignorables: bool = false,
do_not_insert_dotted_circle: bool = false,
verify: bool = false,
produce_unsafe_to_concat: bool = false,
pub const Flag = enum(u7) {
bot = c.HB_BUFFER_FLAG_BOT,
eot = c.HB_BUFFER_FLAG_EOT,
preserve_default_ignorables = c.HB_BUFFER_FLAG_PRESERVE_DEFAULT_IGNORABLES,
remove_default_ignorables = c.HB_BUFFER_FLAG_REMOVE_DEFAULT_IGNORABLES,
do_not_insert_dotted_circle = c.HB_BUFFER_FLAG_DO_NOT_INSERT_DOTTED_CIRCLE,
verify = c.HB_BUFFER_FLAG_VERIFY,
produce_unsafe_to_concat = c.HB_BUFFER_FLAG_PRODUCE_UNSAFE_TO_CONCAT,
};
pub fn from(bits: u7) Flags {
return utils.bitFieldsToStruct(Flags, Flag, bits);
}
pub fn cast(self: Flags) u7 {
return utils.structToBitFields(u7, Flag, self);
}
};
handle: *c.hb_buffer_t,
pub fn init() ?Buffer {
var b = c.hb_buffer_create();
if (c.hb_buffer_allocation_successful(b) < 1)
return null;
return Buffer{ .handle = b.? };
}
pub fn initEmpty() Buffer {
return .{ .handle = c.hb_buffer_get_empty().? };
}
pub fn initSimilar(self: Buffer) ?Buffer {
var b = c.hb_buffer_create_similar(self.handle);
if (c.hb_buffer_allocation_successful(b) < 1)
return null;
return Buffer{ .handle = b.? };
}
pub fn reference(self: Buffer) Buffer {
return .{
.handle = c.hb_buffer_reference(self.handle).?,
};
}
pub fn deinit(self: Buffer) void {
c.hb_buffer_destroy(self.handle);
}
pub fn reset(self: Buffer) void {
c.hb_buffer_reset(self.handle);
}
pub fn clearContents(self: Buffer) void {
c.hb_buffer_clear_contents(self.handle);
}
pub fn preAllocate(self: Buffer, size: u32) error{OutOfMemory}!void {
if (c.hb_buffer_pre_allocate(self.handle, size) < 1)
return error.OutOfMemory;
}
pub fn allocationSuccessful(self: Buffer) bool {
return c.hb_buffer_allocation_successful(self.handle) > 0;
}
pub fn add(self: Buffer, codepoint: u32, cluster: u32) void {
c.hb_buffer_add(self.handle, codepoint, cluster);
}
pub fn addCodepoints(self: Buffer, text: []const u32, item_offset: u32, item_length: ?u31) void {
c.hb_buffer_add_codepoints(self.handle, &text[0], @intCast(c_int, text.len), item_offset, if (item_length) |l| l else @intCast(c_int, text.len));
}
pub fn addUTF32(self: Buffer, text: []const u32, item_offset: u32, item_length: ?u31) void {
c.hb_buffer_add_utf32(self.handle, &text[0], @intCast(c_int, text.len), item_offset, if (item_length) |l| l else @intCast(c_int, text.len));
}
pub fn addUTF16(self: Buffer, text: []const u16, item_offset: u32, item_length: ?u31) void {
c.hb_buffer_add_utf16(self.handle, &text[0], @intCast(c_int, text.len), item_offset, if (item_length) |l| l else @intCast(c_int, text.len));
}
pub fn addUTF8(self: Buffer, text: []const u8, item_offset: u32, item_length: ?u31) void {
c.hb_buffer_add_utf8(self.handle, &text[0], @intCast(c_int, text.len), item_offset, if (item_length) |l| l else @intCast(c_int, text.len));
}
pub fn addLatin1(self: Buffer, text: []const u8, item_offset: u32, item_length: ?u31) void {
c.hb_buffer_add_latin1(self.handle, &text[0], @intCast(c_int, text.len), item_offset, if (item_length) |l| l else @intCast(c_int, text.len));
}
pub fn append(self: Buffer, source: Buffer, start: u32, end: u32) void {
c.hb_buffer_append(self.handle, source.handle, start, end);
}
pub fn getContentType(self: Buffer) ContentType {
return @intToEnum(ContentType, c.hb_buffer_get_content_type(self.handle));
}
pub fn setContentType(self: Buffer, content_type: ContentType) void {
c.hb_buffer_set_content_type(self.handle, @enumToInt(content_type));
}
pub fn getDirection(self: Buffer) Direction {
return @intToEnum(Direction, c.hb_buffer_get_direction(self.handle));
}
pub fn setDirection(self: Buffer, direction: Direction) void {
c.hb_buffer_set_direction(self.handle, @enumToInt(direction));
}
pub fn getScript(self: Buffer) Script {
return @intToEnum(Script, c.hb_buffer_get_script(self.handle));
}
pub fn setScript(self: Buffer, script: Script) void {
c.hb_buffer_set_script(self.handle, @enumToInt(script));
}
pub fn getLanguage(self: Buffer) Language {
return Language{ .handle = c.hb_buffer_get_language(self.handle) };
}
pub fn setLanguage(self: Buffer, lang: Language) void {
c.hb_buffer_set_language(self.handle, lang.handle);
}
pub fn getFlags(self: Buffer) Flags {
return Flags.from(@intCast(u7, c.hb_buffer_get_flags(self.handle)));
}
pub fn setFlags(self: Buffer, flags: Flags) void {
c.hb_buffer_set_flags(self.handle, flags.cast());
}
pub fn getClusterLevel(self: Buffer) ClusterLevel {
return @intToEnum(ClusterLevel, c.hb_buffer_get_cluster_level(self.handle));
}
pub fn setClusterLevel(self: Buffer, level: ClusterLevel) void {
c.hb_buffer_set_cluster_level(self.handle, @enumToInt(level));
}
pub fn getLength(self: Buffer) u32 {
return c.hb_buffer_get_length(self.handle);
}
pub fn setLength(self: Buffer, new_len: u32) error{OutOfMemory}!void {
if (c.hb_buffer_set_length(self.handle, new_len) < 1)
return error.OutOfMemory;
}
pub fn getSegmentProps(self: Buffer) SegmentProps {
var props: c.hb_segment_properties_t = undefined;
c.hb_buffer_get_segment_properties(self.handle, &props);
return SegmentProps.from(props);
}
pub fn setSegmentProps(self: Buffer, props: SegmentProps) void {
c.hb_buffer_set_segment_properties(self.handle, &props.cast());
}
pub fn guessSegmentProps(self: Buffer) void {
c.hb_buffer_guess_segment_properties(self.handle);
}
pub fn getGlyphInfos(self: Buffer) []GlyphInfo {
return hb_buffer_get_glyph_infos(self.handle, null)[0..self.getLength()];
}
pub fn getGlyphPositions(self: Buffer) ?[]Position {
return if (hb_buffer_get_glyph_positions(self.handle, null)) |positions|
positions[0..self.getLength()]
else
null;
}
pub fn hasPositions(self: Buffer) bool {
return c.hb_buffer_has_positions(self.handle) > 0;
}
pub fn getInvisibleGlyph(self: Buffer) u32 {
return c.hb_buffer_get_invisible_glyph(self.handle);
}
pub fn setInvisibleGlyph(self: Buffer, codepoint: u32) void {
c.hb_buffer_set_invisible_glyph(self.handle, codepoint);
}
pub fn getGlyphNotFound(self: Buffer) u32 {
return c.hb_buffer_get_not_found_glyph(self.handle);
}
pub fn setGlyphNotFound(self: Buffer, codepoint: u32) void {
c.hb_buffer_set_not_found_glyph(self.handle, codepoint);
}
pub fn getReplacementCodepoint(self: Buffer) u32 {
return c.hb_buffer_get_replacement_codepoint(self.handle);
}
pub fn setReplacementCodepoint(self: Buffer, codepoint: u32) void {
c.hb_buffer_set_replacement_codepoint(self.handle, codepoint);
}
pub fn normalizeGlyphs(self: Buffer) void {
c.hb_buffer_normalize_glyphs(self.handle);
}
pub fn reverse(self: Buffer) void {
c.hb_buffer_reverse(self.handle);
}
pub fn reverseRange(self: Buffer, start: u32, end: u32) void {
c.hb_buffer_reverse_range(self.handle, start, end);
}
pub fn reverseClusters(self: Buffer) void {
c.hb_buffer_reverse_clusters(self.handle);
}
pub fn diff(self: Buffer, ref: Buffer, dottedcircle_glyph: u32, position_fuzz: u32) DiffFlags {
return DiffFlags.from(@intCast(u8, c.hb_buffer_diff(self.handle, ref.handle, dottedcircle_glyph, position_fuzz)));
}
};
pub extern fn hb_glyph_info_get_glyph_flags(info: [*c]const GlyphInfo) c.hb_glyph_flags_t;
pub extern fn hb_buffer_get_glyph_infos(buffer: ?*c.hb_buffer_t, length: [*c]c_uint) [*c]GlyphInfo;
pub extern fn hb_buffer_get_glyph_positions(buffer: ?*c.hb_buffer_t, length: [*c]c_uint) [*c]Position; | freetype/src/harfbuzz/buffer.zig |
const std = @import("std");
const root = @import("root");
pub const Cpu = @import("Cpu.zig");
pub const video = @import("video.zig");
pub const Video = video.Video;
const joypad = @import("joypad.zig");
pub const Mmu = @import("Mmu.zig");
const timer = @import("timer.zig");
pub const Timer = timer.Timer;
pub const Savestate = @import("Savestate.zig");
pub const Temportal = @import("Temportal.zig");
pub const MHz = 4194304;
const CYCLES_PER_MS = Fundude.MHz / 1000;
pub const profiling_call = std.builtin.CallOptions{
.modifier = if (@hasDecl(root, "is_profiling") and root.is_profiling) .never_inline else .auto,
};
const Fundude = @This();
video: video.Video = undefined,
cpu: Cpu = undefined,
mmu: Mmu = undefined,
inputs: joypad.Inputs = undefined,
timer: timer.Timer = undefined,
temportal: Temportal = .{},
breakpoint: u16 = 0xFFFF,
pub fn init(self: *Fundude, allocator: *std.mem.Allocator, args: struct {
cart: ?[]const u8 = null,
temportal_states: usize = 256,
}) !void {
if (args.cart) |cart| {
try self.mmu.load(cart);
}
try self.temportal.init(allocator, args.temportal_states);
self.temportal.save(self);
self.mmu.reset();
self.video.reset();
self.cpu.reset();
self.inputs.reset();
self.timer.reset();
self.breakpoint = 0xFFFF;
}
pub fn deinit(self: *Fundude, allocator: *std.mem.Allocator) void {
self.temportal.deinit(allocator);
self.* = .{};
}
// TODO: convert "catchup" to an enum
pub fn tick(self: *Fundude, catchup: bool) void {
@call(Fundude.profiling_call, self.cpu.tick, .{&self.mmu});
@call(Fundude.profiling_call, self.video.tick, .{ &self.mmu, catchup });
@call(Fundude.profiling_call, self.timer.tick, .{&self.mmu});
@call(Fundude.profiling_call, self.temportal.tick, .{self});
}
pub fn step(self: *Fundude) i8 {
self.tick(false);
var duration: i8 = 4;
while (self.cpu.remaining > 0) {
self.tick(false);
duration += 4;
}
return duration;
}
pub fn step_ms(self: *Fundude, ms: i64, is_profiling: bool) i32 {
const cycles = ms * CYCLES_PER_MS;
std.debug.assert(cycles < std.math.maxInt(i32));
return self.step_cycles(@truncate(i32, cycles), is_profiling);
}
pub fn step_cycles(self: *Fundude, cycles: i32, is_profiling: bool) i32 {
const target_cycles: i32 = cycles;
var track = target_cycles;
while (track >= 0) {
const catchup = track > 140_000 and !is_profiling;
self.tick(catchup);
track -= 4;
if (self.breakpoint == self.cpu.reg._16.get(.PC)) {
return target_cycles - track;
}
}
return target_cycles - track;
}
pub const dump = Savestate.dump;
pub const restore = Savestate.restore;
pub const validateSavestate = Savestate.validate;
pub const savestate_size = Savestate.size;
test {
std.testing.refAllDecls(@This());
} | src/main.zig |
const std = @import("std");
const testing = std.testing;
const allocator = std.testing.allocator;
pub const Radar = struct {
count: usize,
increases: usize,
window_size: usize,
window_data: std.ArrayList(usize),
window_pos: usize,
window_sum: usize,
pub fn init(window_size: usize) Radar {
var self = Radar{
.count = 0,
.increases = 0,
.window_size = window_size,
.window_data = std.ArrayList(usize).init(allocator),
.window_pos = 0,
.window_sum = 0,
};
return self;
}
pub fn deinit(self: *Radar) void {
self.window_data.deinit();
}
pub fn add_line(self: *Radar, line: []const u8) void {
self.count += 1;
const depth = std.fmt.parseInt(usize, line, 10) catch unreachable;
var last_sum = self.window_sum;
if (self.count <= self.window_size) {
self.window_data.append(depth) catch unreachable;
} else {
self.window_sum -= self.window_data.items[self.window_pos];
self.window_data.items[self.window_pos] = depth;
}
self.window_sum += depth;
self.window_pos = (self.window_pos + 1) % self.window_size;
if (self.count <= self.window_size) {
return;
}
if (last_sum < self.window_sum) {
self.increases += 1;
}
}
pub fn get_increases(self: *Radar) usize {
return self.increases;
}
};
test "sample part a" {
const data: []const u8 =
\\199
\\200
\\208
\\210
\\200
\\207
\\240
\\269
\\260
\\263
;
var radar = Radar.init(1);
defer radar.deinit();
var it = std.mem.split(u8, data, "\n");
while (it.next()) |line| {
radar.add_line(line);
}
const count = radar.get_increases();
try testing.expect(count == 7);
}
test "sample part b" {
const data: []const u8 =
\\199
\\200
\\208
\\210
\\200
\\207
\\240
\\269
\\260
\\263
;
var radar = Radar.init(3);
defer radar.deinit();
var it = std.mem.split(u8, data, "\n");
while (it.next()) |line| {
radar.add_line(line);
}
const count = radar.get_increases();
try testing.expect(count == 5);
} | 2021/p01/radar.zig |
const std = @import("std");
const vk = @import("vulkan");
const c = @import("c.zig");
const Allocator = std.mem.Allocator;
const required_device_extensions = [_][]const u8{vk.extension_info.khr_swapchain.name};
const BaseDispatch = vk.BaseWrapper(.{
.CreateInstance,
});
const InstanceDispatch = vk.InstanceWrapper(.{
.DestroyInstance,
.CreateDevice,
.DestroySurfaceKHR,
.EnumeratePhysicalDevices,
.GetPhysicalDeviceProperties,
.EnumerateDeviceExtensionProperties,
.GetPhysicalDeviceSurfaceFormatsKHR,
.GetPhysicalDeviceSurfacePresentModesKHR,
.GetPhysicalDeviceSurfaceCapabilitiesKHR,
.GetPhysicalDeviceQueueFamilyProperties,
.GetPhysicalDeviceSurfaceSupportKHR,
.GetPhysicalDeviceMemoryProperties,
.GetDeviceProcAddr,
});
const DeviceDispatch = vk.DeviceWrapper(.{
.DestroyDevice,
.GetDeviceQueue,
.CreateSemaphore,
.CreateFence,
.CreateImageView,
.DestroyImageView,
.DestroySemaphore,
.DestroyFence,
.GetSwapchainImagesKHR,
.CreateSwapchainKHR,
.DestroySwapchainKHR,
.AcquireNextImageKHR,
.DeviceWaitIdle,
.WaitForFences,
.ResetFences,
.QueueSubmit,
.QueuePresentKHR,
.CreateCommandPool,
.DestroyCommandPool,
.AllocateCommandBuffers,
.FreeCommandBuffers,
.QueueWaitIdle,
.CreateShaderModule,
.DestroyShaderModule,
.CreatePipelineLayout,
.DestroyPipelineLayout,
.CreateRenderPass,
.DestroyRenderPass,
.CreateGraphicsPipelines,
.DestroyPipeline,
.CreateFramebuffer,
.DestroyFramebuffer,
.BeginCommandBuffer,
.EndCommandBuffer,
.AllocateMemory,
.FreeMemory,
.CreateBuffer,
.DestroyBuffer,
.GetBufferMemoryRequirements,
.MapMemory,
.UnmapMemory,
.BindBufferMemory,
.CmdBeginRenderPass,
.CmdEndRenderPass,
.CmdBindPipeline,
.CmdDraw,
.CmdSetViewport,
.CmdSetScissor,
.CmdBindVertexBuffers,
.CmdCopyBuffer,
});
pub const GraphicsContext = struct {
vkb: BaseDispatch,
vki: InstanceDispatch,
vkd: DeviceDispatch,
instance: vk.Instance,
surface: vk.SurfaceKHR,
pdev: vk.PhysicalDevice,
props: vk.PhysicalDeviceProperties,
mem_props: vk.PhysicalDeviceMemoryProperties,
dev: vk.Device,
graphics_queue: Queue,
present_queue: Queue,
pub fn init(allocator: *Allocator, app_name: [*:0]const u8, window: *c.GLFWwindow) !GraphicsContext {
var self: GraphicsContext = undefined;
self.vkb = try BaseDispatch.load(c.glfwGetInstanceProcAddress);
var glfw_exts_count: u32 = 0;
const glfw_exts = c.glfwGetRequiredInstanceExtensions(&glfw_exts_count);
const app_info = vk.ApplicationInfo{
.p_application_name = app_name,
.application_version = vk.makeApiVersion(0, 0, 0, 0),
.p_engine_name = app_name,
.engine_version = vk.makeApiVersion(0, 0, 0, 0),
.api_version = vk.API_VERSION_1_2,
};
self.instance = try self.vkb.createInstance(.{
.flags = .{},
.p_application_info = &app_info,
.enabled_layer_count = 0,
.pp_enabled_layer_names = undefined,
.enabled_extension_count = glfw_exts_count,
.pp_enabled_extension_names = @ptrCast([*]const [*:0]const u8, glfw_exts),
}, null);
self.vki = try InstanceDispatch.load(self.instance, c.glfwGetInstanceProcAddress);
errdefer self.vki.destroyInstance(self.instance, null);
self.surface = try createSurface(self.instance, window);
errdefer self.vki.destroySurfaceKHR(self.instance, self.surface, null);
const candidate = try pickPhysicalDevice(self.vki, self.instance, allocator, self.surface);
self.pdev = candidate.pdev;
self.props = candidate.props;
self.dev = try initializeCandidate(self.vki, candidate);
self.vkd = try DeviceDispatch.load(self.dev, self.vki.dispatch.vkGetDeviceProcAddr);
errdefer self.vkd.destroyDevice(self.dev, null);
self.graphics_queue = Queue.init(self.vkd, self.dev, candidate.queues.graphics_family);
self.present_queue = Queue.init(self.vkd, self.dev, candidate.queues.graphics_family);
self.mem_props = self.vki.getPhysicalDeviceMemoryProperties(self.pdev);
return self;
}
pub fn deinit(self: GraphicsContext) void {
self.vkd.destroyDevice(self.dev, null);
self.vki.destroySurfaceKHR(self.instance, self.surface, null);
self.vki.destroyInstance(self.instance, null);
}
pub fn deviceName(self: GraphicsContext) []const u8 {
const len = std.mem.indexOfScalar(u8, &self.props.device_name, 0).?;
return self.props.device_name[0..len];
}
pub fn findMemoryTypeIndex(self: GraphicsContext, memory_type_bits: u32, flags: vk.MemoryPropertyFlags) !u32 {
for (self.mem_props.memory_types[0..self.mem_props.memory_type_count]) |mem_type, i| {
if (memory_type_bits & (@as(u32, 1) << @truncate(u5, i)) != 0 and mem_type.property_flags.contains(flags)) {
return @truncate(u32, i);
}
}
return error.NoSuitableMemoryType;
}
pub fn allocate(self: GraphicsContext, requirements: vk.MemoryRequirements, flags: vk.MemoryPropertyFlags) !vk.DeviceMemory {
return try self.vkd.allocateMemory(self.dev, .{
.allocation_size = requirements.size,
.memory_type_index = try self.findMemoryTypeIndex(requirements.memory_type_bits, flags),
}, null);
}
};
pub const Queue = struct {
handle: vk.Queue,
family: u32,
fn init(vkd: DeviceDispatch, dev: vk.Device, family: u32) Queue {
return .{
.handle = vkd.getDeviceQueue(dev, family, 0),
.family = family,
};
}
};
fn createSurface(instance: vk.Instance, window: *c.GLFWwindow) !vk.SurfaceKHR {
var surface: vk.SurfaceKHR = undefined;
if (c.glfwCreateWindowSurface(instance, window, null, &surface) != .success) {
return error.SurfaceInitFailed;
}
return surface;
}
fn initializeCandidate(vki: InstanceDispatch, candidate: DeviceCandidate) !vk.Device {
const priority = [_]f32{1};
const qci = [_]vk.DeviceQueueCreateInfo{
.{
.flags = .{},
.queue_family_index = candidate.queues.graphics_family,
.queue_count = 1,
.p_queue_priorities = &priority,
},
.{
.flags = .{},
.queue_family_index = candidate.queues.present_family,
.queue_count = 1,
.p_queue_priorities = &priority,
},
};
const queue_count: u32 = if (candidate.queues.graphics_family == candidate.queues.present_family)
1
else
2;
return try vki.createDevice(candidate.pdev, .{
.flags = .{},
.queue_create_info_count = queue_count,
.p_queue_create_infos = &qci,
.enabled_layer_count = 0,
.pp_enabled_layer_names = undefined,
.enabled_extension_count = required_device_extensions.len,
.pp_enabled_extension_names = @ptrCast([*]const [*:0]const u8, &required_device_extensions),
.p_enabled_features = null,
}, null);
}
const DeviceCandidate = struct {
pdev: vk.PhysicalDevice,
props: vk.PhysicalDeviceProperties,
queues: QueueAllocation,
};
const QueueAllocation = struct {
graphics_family: u32,
present_family: u32,
};
fn pickPhysicalDevice(
vki: InstanceDispatch,
instance: vk.Instance,
allocator: *Allocator,
surface: vk.SurfaceKHR,
) !DeviceCandidate {
var device_count: u32 = undefined;
_ = try vki.enumeratePhysicalDevices(instance, &device_count, null);
const pdevs = try allocator.alloc(vk.PhysicalDevice, device_count);
defer allocator.free(pdevs);
_ = try vki.enumeratePhysicalDevices(instance, &device_count, pdevs.ptr);
for (pdevs) |pdev| {
if (try checkSuitable(vki, pdev, allocator, surface)) |candidate| {
return candidate;
}
}
return error.NoSuitableDevice;
}
fn checkSuitable(
vki: InstanceDispatch,
pdev: vk.PhysicalDevice,
allocator: *Allocator,
surface: vk.SurfaceKHR,
) !?DeviceCandidate {
const props = vki.getPhysicalDeviceProperties(pdev);
if (!try checkExtensionSupport(vki, pdev, allocator)) {
return null;
}
if (!try checkSurfaceSupport(vki, pdev, surface)) {
return null;
}
if (try allocateQueues(vki, pdev, allocator, surface)) |allocation| {
return DeviceCandidate{
.pdev = pdev,
.props = props,
.queues = allocation,
};
}
return null;
}
fn allocateQueues(vki: InstanceDispatch, pdev: vk.PhysicalDevice, allocator: *Allocator, surface: vk.SurfaceKHR) !?QueueAllocation {
var family_count: u32 = undefined;
vki.getPhysicalDeviceQueueFamilyProperties(pdev, &family_count, null);
const families = try allocator.alloc(vk.QueueFamilyProperties, family_count);
defer allocator.free(families);
vki.getPhysicalDeviceQueueFamilyProperties(pdev, &family_count, families.ptr);
var graphics_family: ?u32 = null;
var present_family: ?u32 = null;
for (families) |properties, i| {
const family = @intCast(u32, i);
if (graphics_family == null and properties.queue_flags.graphics_bit) {
graphics_family = family;
}
if (present_family == null and (try vki.getPhysicalDeviceSurfaceSupportKHR(pdev, family, surface)) == vk.TRUE) {
present_family = family;
}
}
if (graphics_family != null and present_family != null) {
return QueueAllocation{
.graphics_family = graphics_family.?,
.present_family = present_family.?,
};
}
return null;
}
fn checkSurfaceSupport(vki: InstanceDispatch, pdev: vk.PhysicalDevice, surface: vk.SurfaceKHR) !bool {
var format_count: u32 = undefined;
_ = try vki.getPhysicalDeviceSurfaceFormatsKHR(pdev, surface, &format_count, null);
var present_mode_count: u32 = undefined;
_ = try vki.getPhysicalDeviceSurfacePresentModesKHR(pdev, surface, &present_mode_count, null);
return format_count > 0 and present_mode_count > 0;
}
fn checkExtensionSupport(
vki: InstanceDispatch,
pdev: vk.PhysicalDevice,
allocator: *Allocator,
) !bool {
var count: u32 = undefined;
_ = try vki.enumerateDeviceExtensionProperties(pdev, null, &count, null);
const propsv = try allocator.alloc(vk.ExtensionProperties, count);
defer allocator.free(propsv);
_ = try vki.enumerateDeviceExtensionProperties(pdev, null, &count, propsv.ptr);
for (required_device_extensions) |ext| {
for (propsv) |props| {
const len = std.mem.indexOfScalar(u8, &props.extension_name, 0).?;
const prop_ext_name = props.extension_name[0..len];
if (std.mem.eql(u8, ext, prop_ext_name)) {
break;
}
} else {
return false;
}
}
return true;
} | examples/graphics_context.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const FixBuf = @import("./fixbuf.zig").FixBuf;
const DynamicReply = @import("./reply.zig").DynamicReply;
const testing = std.testing;
/// A generic type that can capture attributes from a Redis reply.
pub fn WithAttribs(comptime T: type) type {
return struct {
/// Attributes are stored as an array of key-value pairs.
/// Each element of a pair is a DynamicReply.
attribs: [][2]DynamicReply,
data: T,
const Self = @This();
pub const Redis = struct {
pub const Parser = struct {
pub const HandlesAttributes = true;
pub fn parse(tag: u8, comptime rootParser: type, msg: anytype) !Self {
@compileError("WithAttribs requires an allocator. Use `sendAlloc`.");
}
pub fn destroy(self: Self, comptime rootParser: type, allocator: *Allocator) void {
rootParser.freeReply(self.attribs, allocator);
rootParser.freeReply(self.data, allocator);
}
pub fn parseAlloc(tag: u8, comptime rootParser: type, allocator: *Allocator, msg: anytype) !Self {
var itemTag = tag;
var res: Self = undefined;
if (itemTag == '|') {
// Here we lie to the root parser and claim we encountered a map type,
// otherwise the parser would also try to parse the actual reply along
// side the attribute.
// No error catching is done because DynamicReply parses correctly
// both errors and nil values, and it can't incur in a DecodingError.
res.attribs = try rootParser.parseAllocFromTag(
[][2]DynamicReply,
'%',
allocator,
msg,
);
itemTag = try msg.readByte();
} else {
res.attribs = &[0][2]DynamicReply{};
}
res.data = try rootParser.parseAllocFromTag(T, itemTag, allocator, msg);
return res;
}
};
};
};
}
test "WithAttribs" {
const parser = @import("../parser.zig").RESP3Parser;
const allocator = std.heap.page_allocator;
const res = try parser.parseAlloc(
WithAttribs([2]WithAttribs([]WithAttribs(i64))),
allocator,
MakeComplexListWithAttributes().inStream(),
);
testing.expectEqual(@as(usize, 2), res.attribs.len);
testing.expectEqualSlices(u8, "Ciao", res.attribs[0][0].data.String.string);
testing.expectEqualSlices(u8, "World", res.attribs[0][1].data.String.string);
testing.expectEqualSlices(u8, "Peach", res.attribs[1][0].data.String.string);
testing.expectEqual(@as(f64, 9.99), res.attribs[1][1].data.Double);
testing.expectEqual(@as(usize, 0), res.data[0].data[0].attribs.len);
testing.expectEqual(@as(i64, 20), res.data[0].data[0].data);
testing.expectEqual(@as(usize, 1), res.data[0].data[1].attribs.len);
testing.expectEqualSlices(u8, "ttl", res.data[0].data[1].attribs[0][0].data.String.string);
testing.expectEqual(@as(i64, 128), res.data[0].data[1].attribs[0][1].data.Number);
testing.expectEqual(@as(i64, 100), res.data[0].data[1].data);
testing.expectEqual(@as(usize, 0), res.data[1].attribs.len);
testing.expectEqual(@as(usize, 1), res.data[1].data[0].attribs.len);
testing.expectEqualSlices(u8, "Banana", res.data[1].data[0].attribs[0][0].data.String.string);
testing.expectEqual(true, res.data[1].data[0].attribs[0][1].data.Bool);
testing.expectEqual(@as(i64, 123), res.data[1].data[0].data);
testing.expectEqual(@as(usize, 0), res.data[1].data[1].attribs.len);
testing.expectEqual(@as(i64, 99), res.data[1].data[1].data);
}
//zig fmt: off
fn MakeComplexListWithAttributes() std.io.FixedBufferStream([]const u8) {
return std.io.fixedBufferStream((
"|2\r\n" ++
"+Ciao\r\n" ++
"+World\r\n" ++
"+Peach\r\n" ++
",9.99\r\n" ++
"*2\r\n" ++
"*2\r\n" ++
":20\r\n" ++
"|1\r\n" ++
"+ttl\r\n" ++
":128\r\n" ++
":100\r\n" ++
"*2\r\n" ++
"|1\r\n" ++
"+Banana\r\n" ++
"#t\r\n" ++
":123\r\n" ++
":99\r\n"
)[0..]);
}
//zig fmt: on
test "docs" {
@import("std").meta.refAllDecls(@This());
@import("std").meta.refAllDecls(WithAttribs(FixBuf(100)));
@import("std").meta.refAllDecls(WithAttribs([]u8));
@import("std").meta.refAllDecls(WithAttribs(usize));
} | src/types/attributes.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const AutoHashMap = std.AutoHashMap;
const PriorityQueue = std.PriorityQueue;
const StringHashMap = std.StringHashMap;
// Useful stdlib functions
const tokenize = std.mem.tokenize;
const split = std.mem.split;
const trim = std.mem.trim;
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;
const util = @import("util.zig");
const gpa = util.gpa;
const Loc = struct {
x: u32,
y: u32,
fn hash(self: Loc) u32 {
if (self.y == 0) return self.x;
var col = self.x / 2 - 1;
return 12 + 4 * self.y + col;
}
fn dist(a: Loc, b: Loc) u32 {
var x: u32 = undefined;
var y: u32 = undefined;
if (a.x > b.x) {
x = a.x - b.x;
} else {
x = b.x - a.x;
}
if (a.y > b.y) {
y = a.y - b.y;
} else {
y = b.y - a.y;
}
if (a.y > 0 and b.y > 0 and a.x != b.x) y *= 2;
return x + y;
}
fn asc(a: Loc, b: Loc) bool {
if (a.y == b.y) return a.x < b.x;
return a.y < b.y;
}
};
const LocGroup = [4]Loc;
const ArrayForm = [16]Loc;
const Map = struct {
AA: LocGroup,
BB: LocGroup,
CC: LocGroup,
DD: LocGroup,
fn hash(self: Map) u128 {
var self_array: ArrayForm = @bitCast(ArrayForm, self);
var f: u128 = 1;
var r: u128 = 0;
for (self_array) |val| {
r += (val.hash() * f);
f *= 32;
}
return r;
}
const heuristic_permutations = [_][4]u32{
[4]u32{ 1, 2, 3, 0 },
[4]u32{ 1, 2, 0, 3 },
[4]u32{ 1, 3, 2, 0 },
[4]u32{ 1, 3, 0, 2 },
[4]u32{ 1, 0, 2, 3 },
[4]u32{ 1, 0, 3, 2 },
[4]u32{ 2, 1, 3, 0 },
[4]u32{ 2, 1, 0, 3 },
[4]u32{ 2, 3, 1, 0 },
[4]u32{ 2, 3, 0, 1 },
[4]u32{ 2, 0, 1, 3 },
[4]u32{ 2, 0, 3, 1 },
[4]u32{ 3, 2, 1, 0 },
[4]u32{ 3, 2, 0, 1 },
[4]u32{ 3, 1, 2, 0 },
[4]u32{ 3, 1, 0, 2 },
[4]u32{ 3, 0, 2, 1 },
[4]u32{ 3, 0, 1, 2 },
[4]u32{ 0, 2, 3, 1 },
[4]u32{ 0, 2, 1, 3 },
[4]u32{ 0, 3, 2, 1 },
[4]u32{ 0, 3, 1, 2 },
[4]u32{ 0, 1, 2, 3 },
[4]u32{ 0, 1, 3, 2 },
};
fn locGroupDist(a: LocGroup, b: LocGroup, permutation: [4]u32) u32 {
var idx: u32 = 0;
var r: u32 = 0;
while (idx < 4) : (idx += 1) {
r += a[idx].dist(b[permutation[idx]]);
}
return r;
}
fn heuristicDist(self: Map, other: Map) u32 {
var a0: u32 = 999999;
var b0: u32 = 999999;
var c0: u32 = 999999;
var d0: u32 = 999999;
for (Map.heuristic_permutations) |perm| {
a0 = min(a0, Map.locGroupDist(self.AA, other.AA, perm));
b0 = min(b0, Map.locGroupDist(self.BB, other.BB, perm));
c0 = min(c0, Map.locGroupDist(self.CC, other.CC, perm));
d0 = min(d0, Map.locGroupDist(self.DD, other.DD, perm));
}
return a0 + b0 * 10 + c0 * 100 + d0 * 1000;
}
fn eql(self: Map, other: Map) bool {
return self.heuristicDist(other) == 0;
}
fn spaceAtHome(self: Map, dest_col: u32, node_idx: usize) u32 {
var self_array: ArrayForm = @bitCast(ArrayForm, self);
var result: u32 = 4;
for (self_array) |node, idx| {
if (idx == node_idx) continue;
if (node.x == dest_col) {
result = min(result, node.y - 1);
}
}
return result;
}
fn grid(self: Map) [5][11]u8 {
var result = std.mem.zeroes([5][11]u8);
for (result) |*line| {
std.mem.set(u8, line, ' ');
}
std.mem.set(u8, &result[0], '.');
var ridx: u32 = 2;
while (ridx < 10) : (ridx += 2) {
result[1][ridx] = '.';
result[2][ridx] = '.';
result[3][ridx] = '.';
result[4][ridx] = '.';
}
var self_array: ArrayForm = @bitCast(ArrayForm, self);
for (self_array) |node, idx| {
var dest_col = @divFloor(@intCast(u32, idx), 4);
var dest_char = @intCast(u8, dest_col + 'A');
result[node.y][node.x] = dest_char;
}
return result;
}
fn printState(self: Map) void {
var g = self.grid();
for (g) |line| {
print("{s}\n", .{line});
}
print("\n", .{});
}
};
const SearchState = struct {
state: Map,
cost: u32,
est: u32,
fn order(self: SearchState, other: SearchState) std.math.Order {
return std.math.order(self.est + self.cost, other.est + other.cost);
}
const NextStateIterator = struct {
const Self = @This();
states: ArrayList(SearchState),
idx: u32 = 0,
fn next(self: *Self) ?SearchState {
if (self.idx < self.states.items.len) {
self.idx += 1;
return self.states.items[self.idx - 1];
} else {
self.states.deinit();
return null;
}
}
};
fn addStatesMoveOut(self: SearchState, states: *ArrayList(SearchState), node_idx: usize) void {
var state_array: ArrayForm = @bitCast(ArrayForm, self.state);
var node = state_array[node_idx];
var dest_idx = @divFloor(@intCast(u32, node_idx), 4);
const cost_mult = std.math.pow(u32, 10, dest_idx);
var min_x: u32 = 0;
var max_x: u32 = 10;
for (state_array) |other, idx| {
if (idx == node_idx) continue;
if (other.y != 0) continue;
if (other.x < node.x) min_x = max(other.x + 1, min_x);
if (other.x > node.x) max_x = min(other.x - 1, max_x);
}
var new_state: ArrayForm = undefined;
std.mem.copy(Loc, &new_state, &state_array);
var new_x: u32 = min_x;
while (new_x <= max_x) : (new_x += 1) {
if (new_x == 2 or new_x == 4 or new_x == 6 or new_x == 8) continue;
new_state[node_idx].x = new_x;
new_state[node_idx].y = 0;
var xxx = @bitCast(Map, new_state);
var new_search = SearchState{
.state = xxx,
.cost = self.cost + cost_mult * node.dist(new_state[node_idx]),
.est = searchHeuristic(xxx),
};
states.append(new_search) catch unreachable;
}
}
fn nextStates(self: SearchState) NextStateIterator {
var states = ArrayList(SearchState).init(gpa);
var state_array: ArrayForm = @bitCast(ArrayForm, self.state);
main: for (state_array) |node, idx| {
var dest_idx = @divFloor(@intCast(u32, idx), 4);
var dest_col = dest_idx * 2 + 2;
switch (node.y) {
0 => {
var home_depth = self.state.spaceAtHome(dest_col, idx);
if (home_depth == 0) continue :main;
var ax = node.x;
var ay = @intCast(u32, dest_col);
if (ax > ay) std.mem.swap(u32, &ax, &ay);
for (state_array) |other_node, other_idx| {
if (idx == other_idx) continue;
if (other_node.y == 0 and other_node.x > ax and other_node.x < ay) continue :main;
var other_dest_idx = @divFloor(@intCast(u32, other_idx), 4);
if (other_node.x == dest_col and other_dest_idx != dest_idx) continue :main;
}
var new_state: ArrayForm = undefined;
std.mem.copy(Loc, &new_state, &state_array);
new_state[idx].x = dest_col;
new_state[idx].y = home_depth;
const cost_mult = std.math.pow(u32, 10, dest_idx);
var xxx = @bitCast(Map, new_state);
var new_search = SearchState{
.state = xxx,
.cost = self.cost + cost_mult * node.dist(new_state[idx]),
.est = searchHeuristic(xxx),
};
states.append(new_search) catch unreachable;
},
1,
2,
3,
4,
=> |depth| {
if (depth == 4 and node.x == dest_col) continue :main;
var local_depth = self.state.spaceAtHome(node.x, idx);
if (local_depth != depth) continue :main;
self.addStatesMoveOut(&states, idx);
},
else => unreachable,
}
}
return NextStateIterator{ .states = states };
}
};
// zig fmt: off
const dest = Map{
.AA = .{.{ .x = 2, .y = 1 }, .{ .x = 2, .y = 2 }, .{ .x = 2, .y = 3 }, .{ .x = 2, .y = 4 }},
.BB = .{.{ .x = 4, .y = 1 }, .{ .x = 4, .y = 2 }, .{ .x = 4, .y = 3 }, .{ .x = 4, .y = 4 }},
.CC = .{.{ .x = 6, .y = 1 }, .{ .x = 6, .y = 2 }, .{ .x = 6, .y = 3 }, .{ .x = 6, .y = 4 }},
.DD = .{.{ .x = 8, .y = 1 }, .{ .x = 8, .y = 2 }, .{ .x = 8, .y = 3 }, .{ .x = 8, .y = 4 }},
};
// zig fmt: on
fn searchHeuristic(s: Map) u32 {
// return 0;
var result = s.heuristicDist(dest);
{
var used = std.mem.zeroes([5]u32);
for (s.DD) |val| {
if (val.x != 8 or val.y == 0) continue;
used[val.y] = 1;
}
var idx: u32 = 4;
var flag: u32 = 0;
while (idx > 0) : (idx -= 1) {
if (used[idx] == 0) flag = 1;
result += flag * used[idx] * 2000 * idx;
}
}
{
var used = std.mem.zeroes([5]u32);
for (s.CC) |val| {
if (val.x != 6 or val.y == 0) continue;
used[val.y] = 1;
}
var idx: u32 = 4;
var flag: u32 = 0;
while (idx > 0) : (idx -= 1) {
if (used[idx] == 0) flag = 1;
result += flag * used[idx] * 200 * idx;
}
}
return result;
}
fn search(start: Map) u32 {
var queue = PriorityQueue(SearchState).init(gpa, SearchState.order);
var visited = AutoHashMap(u128, void).init(gpa);
var states_explored: u32 = 0;
defer queue.deinit();
defer visited.deinit();
var search_start = SearchState{
.state = start,
.cost = 0,
.est = searchHeuristic(start),
};
queue.add(search_start) catch unreachable;
while (queue.removeOrNull()) |state| {
if (state.state.eql(dest)) {
print("States explored: {} {}\n", .{ states_explored, queue.count() });
return state.cost;
}
var hash_val = state.state.hash();
if (visited.contains(hash_val)) continue;
visited.put(hash_val, {}) catch unreachable;
states_explored += 1;
var next_iterator = state.nextStates();
while (next_iterator.next()) |next_state| {
if (visited.contains(next_state.state.hash())) continue;
queue.add(next_state) catch unreachable;
}
if (states_explored % 50000 == 0) {
print("States explored: {} {}\n", .{ states_explored, queue.count() });
print("Next state: {} {}\n", .{ state.cost, state.est });
state.state.printState();
}
}
unreachable;
}
fn parseInput(input: []const u8) Map {
var idx_a: u32 = 0;
var idx_b: u32 = 0;
var idx_c: u32 = 0;
var idx_d: u32 = 0;
var idx: u32 = 0;
var pos_order = [_][2]u32{
[2]u32{ 0, 0 },
[2]u32{ 1, 0 },
[2]u32{ 2, 0 },
[2]u32{ 3, 0 },
[2]u32{ 4, 0 },
[2]u32{ 5, 0 },
[2]u32{ 6, 0 },
[2]u32{ 7, 0 },
[2]u32{ 8, 0 },
[2]u32{ 9, 0 },
[2]u32{ 10, 0 },
[2]u32{ 2, 1 },
[2]u32{ 4, 1 },
[2]u32{ 6, 1 },
[2]u32{ 8, 1 },
[2]u32{ 2, 2 },
[2]u32{ 4, 2 },
[2]u32{ 6, 2 },
[2]u32{ 8, 2 },
[2]u32{ 2, 3 },
[2]u32{ 4, 3 },
[2]u32{ 6, 3 },
[2]u32{ 8, 3 },
[2]u32{ 2, 4 },
[2]u32{ 4, 4 },
[2]u32{ 6, 4 },
[2]u32{ 8, 4 },
};
var result = std.mem.zeroes(Map);
for (input) |char| {
switch (char) {
'A' => {
result.AA[idx_a] = Loc{ .x = pos_order[idx][0], .y = pos_order[idx][1] };
idx_a += 1;
idx += 1;
},
'B' => {
result.BB[idx_b] = Loc{ .x = pos_order[idx][0], .y = pos_order[idx][1] };
idx_b += 1;
idx += 1;
},
'C' => {
result.CC[idx_c] = Loc{ .x = pos_order[idx][0], .y = pos_order[idx][1] };
idx_c += 1;
idx += 1;
},
'D' => {
result.DD[idx_d] = Loc{ .x = pos_order[idx][0], .y = pos_order[idx][1] };
idx_d += 1;
idx += 1;
},
'.' => {
idx += 1;
},
else => {},
}
}
return result;
}
pub fn main() !void {
{
var s2_str =
\\ #############
\\ #.D.......AC#
\\ ###C#A#.#.###
\\ #D#C#B#.#
\\ #D#B#A#D#
\\ #B#A#B#C#
\\ #########
;
var s2 = parseInput(s2_str);
s2.printState();
var search_start = SearchState{ .state = s2, .cost = 0, .est = searchHeuristic(s2) };
var next_iterator = search_start.nextStates();
while (next_iterator.next()) |val| {
print("{} {} {}: \n", .{ val.cost, val.est, val.state.hash() });
val.state.printState();
}
}
var start_str =
\\ #############
\\ #...........#
\\ ###C#A#D#D###
\\ #D#C#B#A#
\\ #D#B#A#C#
\\ #B#A#B#C#
\\ #########
;
var start = parseInput(start_str);
print("{} {}\n", .{ start.heuristicDist(dest), searchHeuristic(start) });
print("{}\n", .{search(start)});
} | src/day23.zig |
const GBA = @import("core.zig").GBA;
pub const OAM = struct {
pub const ObjMode = enum(u2) {
Normal,
SemiTransparent,
ObjWindow,
};
pub const FlipSettings = packed struct {
dummy: u3 = 0,
horizontalFlip: u1 = 0,
verticalFlip: u1 = 0,
};
pub const ObjectSize = enum {
Size8x8,
Size16x8,
Size8x16,
Size16x16,
Size32x8,
Size8x32,
Size32x32,
Size32x16,
Size16x32,
Size64x64,
Size64x32,
Size32x64,
};
pub const ObjectShape = enum(u2) {
Square,
Horizontal,
Vertical,
};
pub const Attribute = packed struct {
y: u8 = 0,
rotationScaling: bool = false,
doubleSizeOrVisible: bool = false,
mode: ObjMode = .Normal,
mosaic: bool = false,
paletteMode: GBA.PaletteMode = .Color16,
shape: ObjectShape = .Square,
x: u9 = 0,
flip: FlipSettings = FlipSettings{},
size: u2 = 0,
tileIndex: u10 = 0,
priority: u2 = 0,
palette: u4 = 0,
dummy: i16 = 0,
const Self = @This();
pub fn setSize(self: *Self, size: ObjectSize) void {
switch (size) {
.Size8x8 => {
self.shape = .Square;
self.size = 0;
},
.Size16x8 => {
self.shape = .Horizontal;
self.size = 0;
},
.Size8x16 => {
self.shape = .Vertical;
self.size = 0;
},
.Size16x16 => {
self.shape = .Square;
self.size = 1;
},
.Size32x8 => {
self.shape = .Horizontal;
self.size = 1;
},
.Size8x32 => {
self.shape = .Vertical;
self.size = 1;
},
.Size32x32 => {
self.shape = .Square;
self.size = 2;
},
.Size32x16 => {
self.shape = .Horizontal;
self.size = 2;
},
.Size16x32 => {
self.shape = .Vertical;
self.size = 2;
},
.Size64x64 => {
self.shape = .Square;
self.size = 3;
},
.Size64x32 => {
self.shape = .Horizontal;
self.size = 3;
},
.Size32x64 => {
self.shape = .Vertical;
self.size = 3;
},
}
}
pub fn setRotationParameterIndex(self: *Self, index: u5) callconv(.Inline) void {
self.flip = @bitCast(FlipSettings, index);
}
pub fn setTileIndex(self: *Self, tileIndex: i32) callconv(.Inline) void {
@setRuntimeSafety(false);
self.tileIndex = @intCast(u10, tileIndex);
}
pub fn setPosition(self: *Self, x: i32, y: i32) callconv(.Inline) void {
@setRuntimeSafety(false);
self.x = @intCast(u9, x);
self.y = @intCast(u8, y);
}
pub fn getAffine(self: Self) *Affine {
const affine_index = @bitCast(u5, self.flip);
return &affineBuffer[affine_index];
}
};
pub const Affine = packed struct {
fill0: [3]u16,
pa: i16,
fill1: [3]u16,
pb: i16,
fill2: [3]u16,
pc: i16,
fill3: [3]u16,
pd: i16,
const Self = @This();
pub fn setIdentity(self: *Self) void {
self.pa = 0x0100;
self.pb = 0;
self.pc = 0;
self.pd = 0x0100;
}
};
const OAMAttributePtr = @ptrCast([*]align(4) volatile Attribute, GBA.OAM);
const OAMAttribute = OAMAttributePtr[0..128];
var attributeBuffer: [128]Attribute = undefined;
var currentAttribute: usize = 0;
const affineBufferPtr = @ptrCast([*]align(4) Affine, &attributeBuffer);
const affineBuffer = affineBufferPtr[0..32];
pub fn init() void {
for (attributeBuffer) |*attribute| {
attribute.* = Attribute{};
}
}
pub fn allocate() *Attribute {
var result = &attributeBuffer[currentAttribute];
currentAttribute += 1;
return result;
}
pub fn update(count: usize) void {
var index: usize = 0;
while (index < count) : (index += 1) {
OAMAttribute[index] = attributeBuffer[index];
}
currentAttribute = 0;
}
}; | GBA/oam.zig |
const x86_64 = @import("../index.zig");
const bitjuggle = @import("bitjuggle");
const std = @import("std");
const formatWithoutFields = @import("../common.zig").formatWithoutFields;
/// The Extended Feature Enable Register.
pub const Efer = packed struct {
/// Enables the `syscall` and `sysret` instructions.
system_call_extensions: bool,
z_reserved1_7: u7,
/// Activates long mode, requires activating paging.
long_mode_enable: bool,
z_reserved9: bool,
/// Indicates that long mode is active.
long_mode_active: bool,
/// Enables the no-execute page-protection feature.
no_execute_enable: bool,
/// Enables SVM extensions.
secure_virtual_machine_enable: bool,
/// Enable certain limit checks in 64-bit mode.
long_mode_segment_limit: bool,
/// Enable the `fxsave` and `fxrstor` instructions to execute faster in 64-bit mode.
fast_fxsave_fxrstor: bool,
/// Changes how the `invlpg` instruction operates on TLB entries of upper-level entries.
translation_cache_extension: bool,
z_reserved16_31: u16,
z_reserved32_63: u32,
/// Read the current EFER flags.
pub fn read() Efer {
return Efer.fromU64(REGISTER.read());
}
/// Write the EFER flags, preserving reserved values.
///
/// Preserves the value of reserved fields.
pub fn write(self: Efer) void {
REGISTER.write(self.toU64() | (REGISTER.read() & ALL_RESERVED));
}
const REGISTER = Msr(0xC000_0080);
const ALL_RESERVED: u64 = blk: {
var flags = std.mem.zeroes(Efer);
flags.z_reserved1_7 = std.math.maxInt(u7);
flags.z_reserved9 = true;
flags.z_reserved16_31 = std.math.maxInt(u16);
flags.z_reserved32_63 = std.math.maxInt(u32);
break :blk @bitCast(u64, flags);
};
const ALL_NOT_RESERVED: u64 = ~ALL_RESERVED;
pub fn fromU64(value: u64) Efer {
return @bitCast(Efer, value & ALL_NOT_RESERVED);
}
pub fn toU64(self: Efer) u64 {
return @bitCast(u64, self) & ALL_NOT_RESERVED;
}
pub fn format(value: Efer, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
_ = fmt;
return formatWithoutFields(
value,
options,
writer,
&.{ "z_reserved1_7", "z_reserved9", "z_reserved16_31", "z_reserved32_63" },
);
}
test {
try std.testing.expectEqual(@as(usize, 64), @bitSizeOf(Efer));
try std.testing.expectEqual(@as(usize, 8), @sizeOf(Efer));
}
comptime {
std.testing.refAllDecls(@This());
}
};
/// FS.Base Model Specific Register.
pub const FsBase = struct {
const REGISTER = Msr(0xC000_0100);
/// Read the current FsBase register.
pub fn read() x86_64.VirtAddr {
// We use unchecked here as we assume that the write function did not write an invalid address
return x86_64.VirtAddr.initUnchecked(REGISTER.read());
}
/// Write a given virtual address to the FS.Base register.
pub fn write(addr: x86_64.VirtAddr) void {
REGISTER.write(addr.value);
}
comptime {
std.testing.refAllDecls(@This());
}
};
/// GS.Base Model Specific Register.
pub const GsBase = struct {
const REGISTER = Msr(0xC000_0101);
/// Read the current GsBase register.
pub fn read() x86_64.VirtAddr {
// We use unchecked here as we assume that the write function did not write an invalid address
return x86_64.VirtAddr.initUnchecked(REGISTER.read());
}
/// Write a given virtual address to the GS.Base register.
pub fn write(addr: x86_64.VirtAddr) void {
REGISTER.write(addr.value);
}
comptime {
std.testing.refAllDecls(@This());
}
};
/// KernelGsBase Model Specific Register.
pub const KernelGsBase = struct {
const REGISTER = Msr(0xC000_0102);
/// Read the current KernelGsBase register.
pub fn read() x86_64.VirtAddr {
// We use unchecked here as we assume that the write function did not write an invalid address
return x86_64.VirtAddr.initUnchecked(REGISTER.read());
}
/// Write a given virtual address to the KernelGsBase register.
pub fn write(addr: x86_64.VirtAddr) void {
REGISTER.write(addr.value);
}
comptime {
std.testing.refAllDecls(@This());
}
};
/// Syscall Register: STAR
pub const Star = struct {
sysretCsSelector: x86_64.structures.gdt.SegmentSelector,
sysretSsSelector: x86_64.structures.gdt.SegmentSelector,
syscallCsSelector: x86_64.structures.gdt.SegmentSelector,
syscallSsSelector: x86_64.structures.gdt.SegmentSelector,
const REGISTER = Msr(0xC000_0081);
/// Read the Ring 0 and Ring 3 segment bases.
pub fn read() Star {
const raw = readRaw();
return .{
.sysretCsSelector = .{ .value = raw[0] + 16 },
.sysretSsSelector = .{ .value = raw[0] + 8 },
.syscallCsSelector = .{ .value = raw[1] },
.syscallSsSelector = .{ .value = raw[1] + 8 },
};
}
/// Read the Ring 0 and Ring 3 segment bases.
/// The remaining fields are ignored because they are
/// not valid for long mode.
///
/// # Returns
/// - Item 0 (SYSRET): The CS selector is set to this field + 16. SS.Sel is set to
/// this field + 8. Because SYSRET always returns to CPL 3, the
/// RPL bits 1:0 should be initialized to 11b.
/// - Item 1 (SYSCALL): This field is copied directly into CS.Sel. SS.Sel is set to
/// this field + 8. Because SYSCALL always switches to CPL 0, the RPL bits
/// 33:32 should be initialized to 00b.
pub fn readRaw() [2]u16 {
const val = REGISTER.read();
return [2]u16{
bitjuggle.getBits(val, 48, 16),
bitjuggle.getBits(val, 32, 16),
};
}
pub const WriteError = error{
/// Sysret CS and SS is not offset by 8.
InvalidSysretOffset,
/// Syscall CS and SS is not offset by 8.
InvalidSyscallOffset,
/// Sysret's segment must be a Ring3 segment.
SysretNotRing3,
/// Syscall's segment must be a Ring0 segment.
SyscallNotRing0,
};
/// Write the Ring 0 and Ring 3 segment bases.
/// The remaining fields are ignored because they are
/// not valid for long mode.
/// This function will fail if the segment selectors are
/// not in the correct offset of each other or if the
/// segment selectors do not have correct privileges.
pub fn write(self: Star) WriteError!void {
if (self.sysretCsSelector.value - 16 != self.sysretSsSelector.value - 8) {
return WriteError.InvalidSysretOffset;
}
if (self.syscallCsSelector.value != self.syscallSsSelector.value - 8) {
return WriteError.InvalidSyscallOffset;
}
if (self.sysretSsSelector.getRpl() != .Ring3) {
return WriteError.SysretNotRing3;
}
if (self.syscallSsSelector.getRpl() != .Ring0) {
return WriteError.SyscallNotRing0;
}
writeRaw(self.sysretSsSelector.value - 8, self.syscallSsSelector.value);
}
/// Write the Ring 0 and Ring 3 segment bases.
/// The remaining fields are ignored because they are
/// not valid for long mode.
///
/// # Parameters
/// - sysret: The CS selector is set to this field + 16. SS.Sel is set to
/// this field + 8. Because SYSRET always returns to CPL 3, the
/// RPL bits 1:0 should be initialized to 11b.
/// - syscall: This field is copied directly into CS.Sel. SS.Sel is set to
/// this field + 8. Because SYSCALL always switches to CPL 0, the RPL bits
/// 33:32 should be initialized to 00b.
pub fn writeRaw(sysret: u16, syscall: u16) void {
var value: u64 = 0;
bitjuggle.setBits(&value, 48, 16, sysret);
bitjuggle.setBits(&value, 32, 16, syscall);
REGISTER.write(value);
}
comptime {
std.testing.refAllDecls(@This());
}
};
/// Syscall Register: LSTAR
pub const LStar = struct {
const REGISTER = Msr(0xC000_0082);
/// Read the current LStar register.
/// This holds the target RIP of a syscall.
pub fn read() x86_64.VirtAddr {
// We use unchecked here as we assume that the write function did not write an invalid address
return x86_64.VirtAddr.initUnchecked(REGISTER.read());
}
/// Write a given virtual address to the LStar register.
/// This holds the target RIP of a syscall.
pub fn write(addr: x86_64.VirtAddr) void {
REGISTER.write(addr.value);
}
comptime {
std.testing.refAllDecls(@This());
}
};
/// Syscall Register: SFMask
pub const SFMask = struct {
const REGISTER = Msr(0xC000_0084);
/// Read to the SFMask register.
/// The SFMASK register is used to specify which RFLAGS bits
/// are cleared during a SYSCALL. In long mode, SFMASK is used
/// to specify which RFLAGS bits are cleared when SYSCALL is
/// executed. If a bit in SFMASK is set to 1, the corresponding
/// bit in RFLAGS is cleared to 0. If a bit in SFMASK is cleared
/// to 0, the corresponding rFLAGS bit is not modified.
pub fn read() x86_64.registers.RFlags {
return x86_64.registers.RFlags.fromU64(REGISTER.read());
}
/// Write to the SFMask register.
/// The SFMASK register is used to specify which RFLAGS bits
/// are cleared during a SYSCALL. In long mode, SFMASK is used
/// to specify which RFLAGS bits are cleared when SYSCALL is
/// executed. If a bit in SFMASK is set to 1, the corresponding
/// bit in RFLAGS is cleared to 0. If a bit in SFMASK is cleared
/// to 0, the corresponding rFLAGS bit is not modified.
pub fn write(value: x86_64.registers.RFlags) void {
REGISTER.write(value.toU64());
}
comptime {
std.testing.refAllDecls(@This());
}
};
fn Msr(comptime register: u32) type {
return struct {
pub inline fn read() u64 {
var high: u32 = undefined;
var low: u32 = undefined;
asm volatile ("rdmsr"
: [low] "={eax}" (low),
[high] "={edx}" (high),
: [reg] "{ecx}" (register),
: "memory"
);
return (@as(u64, high) << 32) | @as(u64, low);
}
pub inline fn write(value: u64) void {
asm volatile ("wrmsr"
:
: [reg] "{ecx}" (register),
[low] "{eax}" (@truncate(u32, value)),
[high] "{edx}" (@truncate(u32, value >> 32)),
: "memory"
);
}
comptime {
std.testing.refAllDecls(@This());
}
};
}
comptime {
std.testing.refAllDecls(@This());
} | src/registers/model_specific.zig |
usingnamespace @import("root").preamble;
const log = lib.output.log.scoped(.{
.prefix = "kernel/debug",
.filter = .info,
});
pub const debug_allocator = &debug_allocator_state.allocator;
extern var __kernel_begin: u8;
extern var __kernel_end: u8;
var debug_info = std.dwarf.DwarfInfo{
.endian = os.platform.endian,
.debug_info = undefined,
.debug_abbrev = undefined,
.debug_str = undefined,
.debug_line = undefined,
.debug_ranges = undefined,
};
var inited_debug_info = false;
var debug_allocator_bytes: [16 * 1024 * 1024]u8 = undefined;
var debug_allocator_state = std.heap.FixedBufferAllocator.init(debug_allocator_bytes[0..]);
fn getSectionData(elf: [*]u8, shdr: []u8) []u8 {
const offset = @intCast(usize, std.mem.readIntLittle(u64, shdr[24..][0..8]));
const size = @intCast(usize, std.mem.readIntLittle(u64, shdr[32..][0..8]));
return elf[offset .. offset + size];
}
fn getSectionName(names: []const u8, shdr: []u8) ?[]const u8 {
const offset = @intCast(usize, std.mem.readIntLittle(u32, shdr[0..][0..4]));
const len = std.mem.indexOf(u8, names[offset..], "\x00") orelse return null;
return names[offset .. offset + len];
}
fn getShdr(elf: [*]u8, idx: u16) []u8 {
const sh_offset = std.mem.readIntLittle(u64, elf[40 .. 40 + 8]);
const sh_entsize = std.mem.readIntLittle(u16, elf[58 .. 58 + 2]);
const off = sh_offset + sh_entsize * @intCast(usize, idx);
return elf[off .. off + sh_entsize];
}
fn getSectionSlice(elf: [*]u8, section_name: []const u8) ![]u8 {
const sh_strndx = std.mem.readIntLittle(u16, elf[62 .. 62 + 2]);
const sh_num = std.mem.readIntLittle(u16, elf[60 .. 60 + 2]);
if (sh_strndx > sh_num)
return error.ShstrndxOutOfRange;
const section_names = getSectionData(elf, getShdr(elf, sh_strndx));
var i: u16 = 0;
while (i < sh_num) : (i += 1) {
const header = getShdr(elf, i);
if (std.mem.eql(u8, getSectionName(section_names, header) orelse continue, section_name)) {
const ret = getSectionData(elf, header);
log.write(.info, "Found section {s}: {*}, {d}", .{ section_name, ret.ptr, ret.len });
return ret;
}
}
return error.SectionNotFound;
}
fn attemptLoadDebug(elf: [*]u8) !void {
debug_info.debug_info = try getSectionSlice(elf, ".debug_info");
debug_info.debug_abbrev = try getSectionSlice(elf, ".debug_abbrev");
debug_info.debug_str = try getSectionSlice(elf, ".debug_str");
debug_info.debug_line = try getSectionSlice(elf, ".debug_line");
debug_info.debug_ranges = try getSectionSlice(elf, ".debug_ranges");
try std.dwarf.openDwarfDebugInfo(&debug_info, debug_allocator);
}
pub fn addDebugElf(elf: [*]u8) void {
if (inited_debug_info)
@panic("Double debug info init!");
attemptLoadDebug(elf) catch |err| {
log.write(.crit, "Failed to load debug info: {e}", .{err});
if (@errorReturnTrace()) |trace| {
dumpStackTrace(trace);
} else {
log.write(.crit, "No error trace.", .{});
}
return;
};
inited_debug_info = true;
log.write(.info, "Opened debug info!", .{});
}
fn printAddr(ip: usize) void {
if (ip < @ptrToInt(&__kernel_begin))
return;
if (ip > @ptrToInt(&__kernel_end))
return;
if (inited_debug_info) {
var compile_unit = debug_info.findCompileUnit(ip) catch |err| {
log.write(.warn, "Couldn't find the compile unit at 0x{X}: {s}", .{ ip, @errorName(err) });
return;
};
var line_info = debug_info.getLineNumberInfo(compile_unit.*, ip) catch |err| {
log.write(.warn, "Couldn't find the line info at 0x{X}: {s}", .{ ip, @errorName(err) });
return;
};
printInfo(line_info, ip, debug_info.getSymbolName(ip));
} else {
printInfo(null, ip, null);
}
}
fn printInfo(line_info: ?std.debug.LineInfo, ip: usize, symbol_name: ?[]const u8) void {
const l = log.start(null, "0x{X}: ", .{ip});
if (line_info) |li| {
log.cont(null, "{s}:{d}:{d} ", .{ li.file_name, li.line, li.column }, l);
} else {
log.cont(null, "<No line info> ", .{}, l);
}
if (symbol_name) |symname| {
log.finish(null, "{s}", .{symname}, l);
} else {
log.finish(null, "<No symbol>", .{}, l);
}
}
pub fn dumpFrame(bp: usize, ip: usize) void {
log.write(null, "Dumping ip=0x{X}, bp=0x{X}", .{ ip, bp });
printAddr(ip);
var it = std.debug.StackIterator.init(null, bp);
while (it.next()) |addr| {
printAddr(addr);
}
}
pub fn dumpStackTrace(trace: *std.builtin.StackTrace) void {
if (trace.index <= trace.instruction_addresses.len) {
for (trace.instruction_addresses[trace.index..]) |addr| {
printAddr(addr);
}
}
}
pub fn dumpCurrentTrace() void {
var it = std.debug.StackIterator.init(@returnAddress(), @frameAddress());
while (it.next()) |addr| {
printAddr(addr);
}
} | subprojects/flork/src/kernel/debug.zig |
const std = @import("std");
const os = std.os;
const mem = std.mem;
const kisa = @import("kisa");
const assert = std.debug.assert;
const testing = std.testing;
const Zigstr = @import("zigstr");
pub const Contents = Zigstr;
fn utf8IsTrailing(ch: u8) bool {
// Byte 2,3,4 are all of the form 10xxxxxx. Only the 1st byte is not allowed to start with 0b10.
return ch >> 6 == 0b10;
}
pub const Buffer = struct {
contents: Contents,
const Self = @This();
const Position = struct { line: u32, column: u32 };
pub fn initWithFile(ally: *mem.Allocator, file: std.fs.File) !Self {
const contents = file.readToEndAlloc(
ally,
std.math.maxInt(usize),
) catch |err| switch (err) {
error.WouldBlock => unreachable,
error.BrokenPipe => unreachable,
error.ConnectionResetByPeer => unreachable,
error.ConnectionTimedOut => unreachable,
error.FileTooBig,
error.SystemResources,
error.IsDir,
error.OutOfMemory,
error.OperationAborted,
error.NotOpenForReading,
error.AccessDenied,
error.InputOutput,
error.Unexpected,
=> |e| return e,
};
return Self{ .contents = try Contents.fromOwnedBytes(ally, contents) };
}
pub fn initWithText(ally: *mem.Allocator, text: []const u8) !Self {
return Self{ .contents = try Contents.fromBytes(ally, text) };
}
pub fn deinit(self: *Self) void {
self.contents.deinit();
}
/// Return the offset of the next code point.
pub fn nextCharOffset(self: Self, offset: usize) usize {
// -1 for maximum offset, another -1 so we can add +1 to it.
if (offset >= self.contents.bytes.items.len - 2) return offset;
var result = offset + 1;
while (utf8IsTrailing(self.contents.bytes.items[result]) and
result < self.contents.bytes.items.len - 1)
{
result += 1;
}
return result;
}
/// Return the offset of the previous code point.
pub fn prevCharOffset(self: Self, offset: usize) usize {
if (offset == 0) return 0;
var result = offset - 1;
while (utf8IsTrailing(self.contents.bytes.items[result]) and result > 0) result -= 1;
return result;
}
/// Return the offset of the first character of the current line.
pub fn beginningOfLineOffset(self: Self, offset: usize) usize {
if (offset == 0) return 0;
var result = offset - 1;
while (self.contents.bytes.items[result] != '\n' and result > 0)
result -= 1;
if (self.contents.bytes.items[result] != '\n') {
// The very first byte of the buffer is not a newline.
return 0;
} else {
return result + 1;
}
}
/// Return the offset of the ending newline character of the current line.
pub fn endOfLineOffset(self: Self, offset: usize) usize {
var result = offset;
while (self.contents.bytes.items[result] != '\n' and
result < self.contents.bytes.items.len - 1)
{
result += 1;
}
return result;
}
/// Return line and column given offset.
pub fn getPosFromOffset(self: Self, offset: usize) Position {
var line: u32 = 1;
var column: u32 = 1;
var off: usize = 0;
while (off < offset and off < self.contents.bytes.items.len - 1) : (off += 1) {
const ch = self.contents.bytes.items[off];
column += 1;
if (ch == '\n') {
line += 1;
column = 1;
}
}
return Position{ .line = line, .column = column };
}
/// Return offset given line and column.
pub fn getOffsetFromPos(self: Self, pos: Position) usize {
if (pos.line <= 0 or pos.column <= 0) return 0;
var lin: u32 = 1;
var col: u32 = 1;
var offset: usize = 0;
while (offset < self.contents.bytes.items.len - 1) : (offset += 1) {
const ch = self.contents.bytes.items[offset];
// If ch == '\n', this means that the column is bigger than the maximum column in the
// line.
if (lin == pos.line and (col == pos.column or ch == '\n')) break;
col += 1;
if (ch == '\n') {
lin += 1;
col = 1;
}
}
return offset;
}
/// Insert bytes at offset. If the offset is the length of the buffer, append to the end.
pub fn insert(self: *Self, offset: usize, bytes: []const u8) !void {
if (!std.unicode.utf8ValidateSlice(bytes)) return error.InvalidUtf8Sequence;
if (offset > self.contents.bytes.items.len) return error.OffsetTooBig;
if (offset == self.contents.bytes.items.len) {
try self.contents.bytes.appendSlice(bytes);
} else {
if (utf8IsTrailing(self.contents.bytes.items[offset]))
return error.InsertAtInvalidPlace;
try self.contents.bytes.insertSlice(offset, bytes);
}
}
// TODO: use grapheme instead of code point?
/// Remove bytes from start to end which are offsets in bytes pointing to the start of
/// the code point.
pub fn remove(self: *Self, start: usize, end: usize) !void {
if (start > end) return error.StartIsBiggerThanEnd;
if (start >= self.contents.bytes.items.len or end >= self.contents.bytes.items.len)
return error.StartOrEndBiggerThanBufferLength;
if (utf8IsTrailing(self.contents.bytes.items[start]) or
utf8IsTrailing(self.contents.bytes.items[end]))
return error.RemoveAtInvalidPlace;
const endlen = std.unicode.utf8ByteSequenceLength(self.contents.bytes.items[end]) catch {
return error.RemoveAtInvalidPlace;
};
if (start == end and endlen == 1) {
_ = self.contents.bytes.orderedRemove(start);
} else {
const newlen = self.contents.bytes.items.len + start - (end + endlen - 1) - 1;
std.mem.copy(
u8,
self.contents.bytes.items[start..newlen],
self.contents.bytes.items[end + endlen ..],
);
std.mem.set(u8, self.contents.bytes.items[newlen..], undefined);
self.contents.bytes.items.len = newlen;
}
}
pub fn slice(self: Self) []const u8 {
return self.contents.bytes.items;
}
};
const BP = Buffer.Position;
test "state: init text buffer with file descriptor" {
var file = try std.fs.cwd().openFile("kisarc.zzz", .{});
defer file.close();
var buffer = try Buffer.initWithFile(testing.allocator, file);
defer buffer.deinit();
}
test "state: init text buffer with text" {
var buffer = try Buffer.initWithText(testing.allocator, "Hello");
defer buffer.deinit();
}
test "state: nextCharOffset" {
var buffer = try Buffer.initWithText(testing.allocator, "Dobrý deň");
defer buffer.deinit();
try testing.expectEqual(@as(usize, 11), buffer.contents.bytes.items.len);
try testing.expectEqual(@as(usize, 1), buffer.nextCharOffset(0));
try testing.expectEqual(@as(usize, 2), buffer.nextCharOffset(1));
try testing.expectEqual(@as(usize, 3), buffer.nextCharOffset(2));
try testing.expectEqual(@as(usize, 4), buffer.nextCharOffset(3));
try testing.expectEqual(@as(usize, 6), buffer.nextCharOffset(4)); // ý, 2 bytes
try testing.expectEqual(@as(usize, 6), buffer.nextCharOffset(5)); // error condition
try testing.expectEqual(@as(usize, 7), buffer.nextCharOffset(6));
try testing.expectEqual(@as(usize, 8), buffer.nextCharOffset(7));
try testing.expectEqual(@as(usize, 9), buffer.nextCharOffset(8));
try testing.expectEqual(@as(usize, 9), buffer.nextCharOffset(9));
}
test "state: prevCharOffset" {
var buffer = try Buffer.initWithText(testing.allocator, "Dobrý deň");
defer buffer.deinit();
try testing.expectEqual(@as(usize, 11), buffer.contents.bytes.items.len);
try testing.expectEqual(@as(usize, 8), buffer.prevCharOffset(9));
try testing.expectEqual(@as(usize, 7), buffer.prevCharOffset(8));
try testing.expectEqual(@as(usize, 6), buffer.prevCharOffset(7));
try testing.expectEqual(@as(usize, 4), buffer.prevCharOffset(6)); // ý, 2 bytes
try testing.expectEqual(@as(usize, 4), buffer.prevCharOffset(5)); // error condition
try testing.expectEqual(@as(usize, 3), buffer.prevCharOffset(4));
try testing.expectEqual(@as(usize, 2), buffer.prevCharOffset(3));
try testing.expectEqual(@as(usize, 1), buffer.prevCharOffset(2));
try testing.expectEqual(@as(usize, 0), buffer.prevCharOffset(1));
try testing.expectEqual(@as(usize, 0), buffer.prevCharOffset(0));
}
test "state: beginningOfLineOffset" {
{
const text =
\\Hi
\\Hi
;
var buffer = try Buffer.initWithText(testing.allocator, text);
defer buffer.deinit();
try testing.expectEqual(@as(usize, 5), buffer.contents.bytes.items.len);
try testing.expectEqual(@as(usize, 0), buffer.beginningOfLineOffset(0));
try testing.expectEqual(@as(usize, 0), buffer.beginningOfLineOffset(1));
try testing.expectEqual(@as(usize, 0), buffer.beginningOfLineOffset(2));
try testing.expectEqual(@as(usize, 3), buffer.beginningOfLineOffset(3));
try testing.expectEqual(@as(usize, 3), buffer.beginningOfLineOffset(4));
}
{
const text =
\\
\\
\\Hi
\\
\\
;
var buffer = try Buffer.initWithText(testing.allocator, text);
defer buffer.deinit();
try testing.expectEqual(@as(usize, 6), buffer.contents.bytes.items.len);
try testing.expectEqual(@as(usize, 0), buffer.beginningOfLineOffset(0));
try testing.expectEqual(@as(usize, 1), buffer.beginningOfLineOffset(1));
try testing.expectEqual(@as(usize, 2), buffer.beginningOfLineOffset(2));
try testing.expectEqual(@as(usize, 2), buffer.beginningOfLineOffset(3));
try testing.expectEqual(@as(usize, 2), buffer.beginningOfLineOffset(4));
try testing.expectEqual(@as(usize, 5), buffer.beginningOfLineOffset(5));
}
}
test "state: endOfLineOffset" {
{
const text =
\\Hi
\\Hi
;
var buffer = try Buffer.initWithText(testing.allocator, text);
defer buffer.deinit();
try testing.expectEqual(@as(usize, 5), buffer.contents.bytes.items.len);
try testing.expectEqual(@as(usize, 2), buffer.endOfLineOffset(0));
try testing.expectEqual(@as(usize, 2), buffer.endOfLineOffset(1));
try testing.expectEqual(@as(usize, 2), buffer.endOfLineOffset(2));
try testing.expectEqual(@as(usize, 4), buffer.endOfLineOffset(3));
try testing.expectEqual(@as(usize, 4), buffer.endOfLineOffset(4));
}
{
const text =
\\
\\
\\Hi
\\
\\
;
var buffer = try Buffer.initWithText(testing.allocator, text);
defer buffer.deinit();
try testing.expectEqual(@as(usize, 6), buffer.contents.bytes.items.len);
try testing.expectEqual(@as(usize, 0), buffer.endOfLineOffset(0));
try testing.expectEqual(@as(usize, 1), buffer.endOfLineOffset(1));
try testing.expectEqual(@as(usize, 4), buffer.endOfLineOffset(2));
try testing.expectEqual(@as(usize, 4), buffer.endOfLineOffset(3));
try testing.expectEqual(@as(usize, 4), buffer.endOfLineOffset(4));
try testing.expectEqual(@as(usize, 5), buffer.endOfLineOffset(5));
}
}
test "state: getPosFromOffset" {
const text =
\\
\\
\\Hi
\\
\\
;
var buffer = try Buffer.initWithText(testing.allocator, text);
defer buffer.deinit();
try testing.expectEqual(@as(usize, 6), buffer.contents.bytes.items.len);
try testing.expectEqual(BP{ .line = 1, .column = 1 }, buffer.getPosFromOffset(0));
try testing.expectEqual(BP{ .line = 2, .column = 1 }, buffer.getPosFromOffset(1));
try testing.expectEqual(BP{ .line = 3, .column = 1 }, buffer.getPosFromOffset(2));
try testing.expectEqual(BP{ .line = 3, .column = 2 }, buffer.getPosFromOffset(3));
try testing.expectEqual(BP{ .line = 3, .column = 3 }, buffer.getPosFromOffset(4));
try testing.expectEqual(BP{ .line = 4, .column = 1 }, buffer.getPosFromOffset(5));
try testing.expectEqual(BP{ .line = 4, .column = 1 }, buffer.getPosFromOffset(999));
}
test "state: getOffsetFromPos" {
const text =
\\
\\
\\Hi
\\
\\
;
var buffer = try Buffer.initWithText(testing.allocator, text);
defer buffer.deinit();
try testing.expectEqual(@as(usize, 6), buffer.contents.bytes.items.len);
try testing.expectEqual(@as(usize, 0), buffer.getOffsetFromPos(BP{ .line = 1, .column = 1 }));
try testing.expectEqual(@as(usize, 1), buffer.getOffsetFromPos(BP{ .line = 2, .column = 1 }));
try testing.expectEqual(@as(usize, 2), buffer.getOffsetFromPos(BP{ .line = 3, .column = 1 }));
try testing.expectEqual(@as(usize, 3), buffer.getOffsetFromPos(BP{ .line = 3, .column = 2 }));
try testing.expectEqual(@as(usize, 4), buffer.getOffsetFromPos(BP{ .line = 3, .column = 3 }));
try testing.expectEqual(@as(usize, 5), buffer.getOffsetFromPos(BP{ .line = 4, .column = 1 }));
// Get the very last offset.
try testing.expectEqual(@as(usize, 5), buffer.getOffsetFromPos(BP{ .line = 999, .column = 999 }));
// Incorrect data lower than minimum, get the very first offset.
try testing.expectEqual(@as(usize, 0), buffer.getOffsetFromPos(BP{ .line = 0, .column = 0 }));
// Line contains only a single newline, column is bigger than the line has.
try testing.expectEqual(@as(usize, 0), buffer.getOffsetFromPos(BP{ .line = 1, .column = 999 }));
// Line has several characters, column is bigger than the line has.
try testing.expectEqual(@as(usize, 4), buffer.getOffsetFromPos(BP{ .line = 3, .column = 999 }));
}
test "state: insert" {
{
const text = "ý";
var buffer = try Buffer.initWithText(testing.allocator, text);
defer buffer.deinit();
try testing.expectError(error.OffsetTooBig, buffer.insert(3, "u"));
try testing.expectError(error.InsertAtInvalidPlace, buffer.insert(1, "u"));
try testing.expectError(error.InvalidUtf8Sequence, buffer.insert(0, &[_]u8{0b1011_1111}));
}
{
const text = "";
var buffer = try Buffer.initWithText(testing.allocator, text);
defer buffer.deinit();
try buffer.insert(0, "a");
try testing.expectEqualStrings("a", buffer.slice());
try buffer.insert(0, "b");
try testing.expectEqualStrings("ba", buffer.slice());
try buffer.insert(1, "ee");
try testing.expectEqualStrings("beea", buffer.slice());
try buffer.insert(1, "ý");
try testing.expectEqualStrings("býeea", buffer.slice());
try buffer.insert(1, "c");
try testing.expectEqualStrings("bcýeea", buffer.slice());
}
}
test "state: remove" {
{
const text = "ý01234567";
var buffer = try Buffer.initWithText(testing.allocator, text);
defer buffer.deinit();
try testing.expectEqual(@as(usize, 10), buffer.contents.bytes.items.len);
try testing.expectError(error.StartIsBiggerThanEnd, buffer.remove(2, 0));
try testing.expectError(error.StartOrEndBiggerThanBufferLength, buffer.remove(0, 10));
try testing.expectError(error.StartOrEndBiggerThanBufferLength, buffer.remove(10, 10));
try testing.expectError(error.RemoveAtInvalidPlace, buffer.remove(1, 1));
try testing.expectError(error.RemoveAtInvalidPlace, buffer.remove(0, 1));
try testing.expectError(error.RemoveAtInvalidPlace, buffer.remove(1, 2));
}
{
const text = "0123456789";
var buffer = try Buffer.initWithText(testing.allocator, text);
defer buffer.deinit();
try buffer.remove(0, 0);
try testing.expectEqualStrings("123456789", buffer.slice());
}
{
const text = "0123456789";
var buffer = try Buffer.initWithText(testing.allocator, text);
defer buffer.deinit();
try buffer.remove(1, 1);
try testing.expectEqualStrings("023456789", buffer.slice());
}
{
const text = "0123456789";
var buffer = try Buffer.initWithText(testing.allocator, text);
defer buffer.deinit();
try testing.expectEqual(@as(usize, 10), buffer.contents.bytes.items.len);
try buffer.remove(0, 9);
try testing.expectEqualStrings("", buffer.slice());
}
{
const text = "0123456789";
var buffer = try Buffer.initWithText(testing.allocator, text);
defer buffer.deinit();
try testing.expectEqual(@as(usize, 10), buffer.contents.bytes.items.len);
try buffer.remove(0, 5);
try testing.expectEqualStrings("6789", buffer.slice());
}
{
const text = "0123456789";
var buffer = try Buffer.initWithText(testing.allocator, text);
defer buffer.deinit();
try testing.expectEqual(@as(usize, 10), buffer.contents.bytes.items.len);
try buffer.remove(5, 9);
try testing.expectEqualStrings("01234", buffer.slice());
}
{
const text = "0123456789";
var buffer = try Buffer.initWithText(testing.allocator, text);
defer buffer.deinit();
try testing.expectEqual(@as(usize, 10), buffer.contents.bytes.items.len);
try buffer.remove(2, 7);
try testing.expectEqualStrings("0189", buffer.slice());
}
{
const text = "0ý1234567";
var buffer = try Buffer.initWithText(testing.allocator, text);
defer buffer.deinit();
try testing.expectEqual(@as(usize, 10), buffer.contents.bytes.items.len);
try buffer.remove(0, 3);
try testing.expectEqualStrings("234567", buffer.slice());
}
{
const text = "0ý1234567";
var buffer = try Buffer.initWithText(testing.allocator, text);
defer buffer.deinit();
try testing.expectEqual(@as(usize, 10), buffer.contents.bytes.items.len);
try buffer.remove(0, 1);
try testing.expectEqualStrings("1234567", buffer.slice());
}
{
const text = "0ý1234567";
var buffer = try Buffer.initWithText(testing.allocator, text);
defer buffer.deinit();
try testing.expectEqual(@as(usize, 10), buffer.contents.bytes.items.len);
try buffer.remove(0, 0);
try testing.expectEqualStrings("ý1234567", buffer.slice());
}
{
const text = "0ý1234567";
var buffer = try Buffer.initWithText(testing.allocator, text);
defer buffer.deinit();
try testing.expectEqual(@as(usize, 10), buffer.contents.bytes.items.len);
try buffer.remove(1, 1);
try testing.expectEqualStrings("01234567", buffer.slice());
}
{
const text = "0ý1234567";
var buffer = try Buffer.initWithText(testing.allocator, text);
defer buffer.deinit();
try testing.expectEqual(@as(usize, 10), buffer.contents.bytes.items.len);
try buffer.remove(1, 3);
try testing.expectEqualStrings("0234567", buffer.slice());
}
{
const text = "0ý1234567";
var buffer = try Buffer.initWithText(testing.allocator, text);
defer buffer.deinit();
try testing.expectEqual(@as(usize, 10), buffer.contents.bytes.items.len);
try buffer.remove(3, 3);
try testing.expectEqualStrings("0ý234567", buffer.slice());
}
{
const text = "0ý1234567";
var buffer = try Buffer.initWithText(testing.allocator, text);
defer buffer.deinit();
try testing.expectEqual(@as(usize, 10), buffer.contents.bytes.items.len);
try buffer.remove(3, 4);
try testing.expectEqualStrings("0ý34567", buffer.slice());
}
} | src/text_buffer_array.zig |
test "redeclaration" {
try expectError(
\\let i = 0
\\let i = 1
,
\\redeclaration of 'i'
);
}
test "unexpected token" {
try expectError(
\\if (a b
,
\\expected ')', found 'Identifier'
);
}
test "unexpected arg count" {
try expectError(
\\const foo = fn (a, b) a + b
\\foo(1)
,
\\expected 2 args, got 1
);
}
test "extra cases after catch-all" {
try expectError(
\\match (1)
\\ let val => ()
\\ 1 => ()
\\
,
\\additional cases after catch-all case
);
}
test "extra handlers after catch-all" {
try expectError(
\\const foo = fn() ()
\\try
\\ foo()
\\catch
\\ 2
\\catch (1)
\\ 3
\\
,
\\additional handlers after catch-all handler
);
}
test "invalid tag unwrap" {
try expectError(
\\let foo = @bar[2]
\\let @foo[baz] = foo
,
\\invalid tag
);
}
test "missing capture" {
try expectError(
\\let error = [2]
,
\\expected a capture
);
try expectError(
\\let @foo = [2]
,
\\expected a capture
);
}
test "break outside loop" {
try expectError(
\\break
,
\\break outside of loop
);
}
test "invalid type" {
try expectError(
\\foo
,
\\use of undeclared identifier
);
}
test "invalid map" {
try expectError(
\\let y = {1}
,
\\expected a key
);
}
test "index out of bounds" {
try expectError(
\\let y = [0, 0, 0]
\\y[y["len"]] = true
,
\\index out of bounds
);
}
test "invalid type" {
try expectError(
\\1 + true
,
\\expected a number
);
}
const std = @import("std");
const mem = std.mem;
const warn = std.debug.warn;
const testing = std.testing;
const bog = @import("bog");
const Vm = bog.Vm;
const Errors = bog.Errors;
fn expectError(source: []const u8, expected: []const u8) !void {
var vm = Vm.init(std.testing.allocator, .{});
defer vm.deinit();
_ = vm.run(source) catch |e| switch (e) {
else => @panic("test failure"),
error.TokenizeError, error.ParseError, error.CompileError, error.RuntimeError => {
const result = vm.errors.list.items[0].msg;
try std.testing.expectEqualStrings(expected, result.data);
return;
},
};
@panic("test failed: expected error");
} | tests/error.zig |
const std = @import("std");
const math = std.math;
const assert = std.debug.assert;
const glfw = @import("glfw");
const gpu = @import("gpu");
const zgpu = @import("zgpu");
const c = zgpu.cimgui;
const zm = @import("zmath");
const zmesh = @import("zmesh");
const zbt = @import("zbullet");
const wgsl = @import("bullet_physics_test_wgsl.zig");
const content_dir = @import("build_options").content_dir;
const window_title = "zig-gamedev: bullet physics test (wgpu)";
const Vertex = extern struct {
position: [3]f32,
normal: [3]f32,
};
const FrameUniforms = struct {
world_to_clip: zm.Mat,
camera_position: [3]f32,
};
const DrawUniforms = struct {
object_to_world: zm.Mat,
basecolor_roughness: [4]f32,
};
const Mesh = struct {
index_offset: u32,
vertex_offset: u32,
num_indices: u32,
num_vertices: u32,
};
const Entity = struct {
body: *const zbt.Body,
basecolor_roughness: [4]f32,
size: [3]f32,
mesh_index: u32,
};
const Camera = struct {
position: [3]f32,
forward: [3]f32 = .{ 0, 0, 0 },
pitch: f32,
yaw: f32,
};
const mesh_index_cube: u32 = 0;
const mesh_index_sphere: u32 = 1;
const mesh_index_world: u32 = 2;
var shape_cube: *const zbt.Shape = undefined;
var shape_sphere: *const zbt.Shape = undefined;
var shape_world: *const zbt.Shape = undefined;
const default_linear_damping: f32 = 0.1;
const default_angular_damping: f32 = 0.1;
const safe_uniform_size = 256;
const camera_fovy: f32 = math.pi / @as(f32, 3.0);
const DemoState = struct {
gctx: *zgpu.GraphicsContext,
mesh_pipe: zgpu.RenderPipelineHandle = .{},
physics_debug_pipe: zgpu.RenderPipelineHandle = .{},
vertex_buf: zgpu.BufferHandle,
index_buf: zgpu.BufferHandle,
physics_debug_buf: zgpu.BufferHandle,
depth_tex: zgpu.TextureHandle,
depth_texv: zgpu.TextureViewHandle,
uniform_bg: zgpu.BindGroupHandle,
meshes: std.ArrayList(Mesh),
entities: std.ArrayList(Entity),
keyboard_delay: f32 = 1.0,
current_scene_index: i32 = initial_scene,
physics: struct {
world: *const zbt.World,
shapes: std.ArrayList(*const zbt.Shape),
debug: *zbt.DebugDrawer,
},
camera: Camera,
mouse: struct {
cursor: glfw.Window.CursorPos = .{ .xpos = 0.0, .ypos = 0.0 },
} = .{},
pick: struct {
body: ?*const zbt.Body = null,
p2p: *const zbt.Point2PointConstraint,
saved_linear_damping: f32 = 0.0,
saved_angular_damping: f32 = 0.0,
distance: f32 = 0.0,
} = .{},
};
fn init(allocator: std.mem.Allocator, window: glfw.Window) !*DemoState {
const gctx = try zgpu.GraphicsContext.init(allocator, window);
var arena_state = std.heap.ArenaAllocator.init(allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
const uniform_bgl = gctx.createBindGroupLayout(&.{
zgpu.bglBuffer(0, .{ .vertex = true, .fragment = true }, .uniform, true, 0),
});
defer gctx.releaseResource(uniform_bgl);
//
// Create meshes.
//
zmesh.init(arena);
defer zmesh.deinit();
var meshes = std.ArrayList(Mesh).init(allocator);
var indices = std.ArrayList(u32).init(arena);
var positions = std.ArrayList([3]f32).init(arena);
var normals = std.ArrayList([3]f32).init(arena);
try initMeshes(arena, &meshes, &indices, &positions, &normals);
const total_num_vertices = @intCast(u32, positions.items.len);
const total_num_indices = @intCast(u32, indices.items.len);
// Create a vertex buffer.
const vertex_buf = gctx.createBuffer(.{
.usage = .{ .copy_dst = true, .vertex = true },
.size = total_num_vertices * @sizeOf(Vertex),
});
{
var vertex_data = std.ArrayList(Vertex).init(arena);
defer vertex_data.deinit();
try vertex_data.resize(total_num_vertices);
for (positions.items) |_, i| {
vertex_data.items[i].position = positions.items[i];
vertex_data.items[i].normal = normals.items[i];
}
gctx.queue.writeBuffer(gctx.lookupResource(vertex_buf).?, 0, Vertex, vertex_data.items);
}
// Create an index buffer.
const index_buf = gctx.createBuffer(.{
.usage = .{ .copy_dst = true, .index = true },
.size = total_num_indices * @sizeOf(u32),
});
gctx.queue.writeBuffer(gctx.lookupResource(index_buf).?, 0, u32, indices.items);
const physics_debug_buf = gctx.createBuffer(.{
.usage = .{ .copy_dst = true, .vertex = true },
.size = 1024 * @sizeOf(zbt.DebugDrawer.Vertex),
});
//
// Create textures.
//
const depth = createDepthTexture(gctx);
//
// Create bind groups.
//
const uniform_bg = gctx.createBindGroup(uniform_bgl, &[_]zgpu.BindGroupEntryInfo{.{
.binding = 0,
.buffer_handle = gctx.uniforms.buffer,
.offset = 0,
.size = safe_uniform_size,
}});
//
// Init physics.
//
const physics_world = zbt.World.init(.{});
var physics_debug = try allocator.create(zbt.DebugDrawer);
physics_debug.* = zbt.DebugDrawer.init(allocator);
physics_world.debugSetDrawer(&physics_debug.getDebugDraw());
physics_world.debugSetMode(zbt.DebugMode.user_only);
var physics_shapes = std.ArrayList(*const zbt.Shape).init(allocator);
var entities = std.ArrayList(Entity).init(allocator);
var camera: Camera = undefined;
scene_setup_table[initial_scene](physics_world, &physics_shapes, &entities, &camera);
const demo = try allocator.create(DemoState);
demo.* = .{
.gctx = gctx,
.vertex_buf = vertex_buf,
.index_buf = index_buf,
.physics_debug_buf = physics_debug_buf,
.depth_tex = depth.tex,
.depth_texv = depth.texv,
.uniform_bg = uniform_bg,
.meshes = meshes,
.entities = entities,
.camera = camera,
.physics = .{
.world = physics_world,
.shapes = physics_shapes,
.debug = physics_debug,
},
.pick = .{
.p2p = zbt.Point2PointConstraint.allocate(),
},
};
//
// Create pipelines.
//
const common_depth_state = gpu.DepthStencilState{
.format = .depth32_float,
.depth_write_enabled = true,
.depth_compare = .less,
};
const pos_norm_attribs = [_]gpu.VertexAttribute{
.{ .format = .float32x3, .offset = 0, .shader_location = 0 },
.{ .format = .float32x3, .offset = @offsetOf(Vertex, "normal"), .shader_location = 1 },
};
zgpu.util.createRenderPipelineSimple(
allocator,
gctx,
&.{ uniform_bgl, uniform_bgl },
wgsl.mesh_vs,
wgsl.mesh_fs,
@sizeOf(Vertex),
pos_norm_attribs[0..],
.{ .front_face = .cw, .cull_mode = .none },
zgpu.GraphicsContext.swapchain_format,
common_depth_state,
&demo.mesh_pipe,
);
const pos_color_attribs = [_]gpu.VertexAttribute{
.{ .format = .float32x3, .offset = 0, .shader_location = 0 },
.{ .format = .uint32, .offset = @offsetOf(zbt.DebugDrawer.Vertex, "color"), .shader_location = 1 },
};
zgpu.util.createRenderPipelineSimple(
allocator,
gctx,
&.{uniform_bgl},
wgsl.physics_debug_vs,
wgsl.physics_debug_fs,
@sizeOf(zbt.DebugDrawer.Vertex),
pos_color_attribs[0..],
.{ .topology = .line_list },
zgpu.GraphicsContext.swapchain_format,
common_depth_state,
&demo.physics_debug_pipe,
);
return demo;
}
fn deinit(allocator: std.mem.Allocator, demo: *DemoState) void {
if (demo.pick.p2p.isCreated()) {
demo.physics.world.removeConstraint(demo.pick.p2p.asConstraint());
demo.pick.p2p.destroy();
}
demo.pick.p2p.deallocate();
cleanupScene(demo.physics.world, &demo.physics.shapes, &demo.entities);
shape_cube.deinit();
shape_sphere.deinit();
shape_world.deinit();
demo.physics.shapes.deinit();
demo.physics.debug.deinit();
allocator.destroy(demo.physics.debug);
demo.physics.world.deinit();
demo.entities.deinit();
demo.meshes.deinit();
demo.gctx.deinit(allocator);
allocator.destroy(demo);
}
fn update(demo: *DemoState) void {
zgpu.gui.newFrame(demo.gctx.swapchain_descriptor.width, demo.gctx.swapchain_descriptor.height);
const dt = demo.gctx.stats.delta_time;
_ = demo.physics.world.stepSimulation(dt, .{});
if (c.igBegin("Demo Settings", null, c.ImGuiWindowFlags_NoMove | c.ImGuiWindowFlags_NoResize)) {
c.igBulletText(
"Average : %.3f ms/frame (%.1f fps)",
demo.gctx.stats.average_cpu_time,
demo.gctx.stats.fps,
);
c.igBulletText("Left Mouse Button + drag : pick up and move object");
c.igBulletText("Right Mouse Button + drag : rotate camera");
c.igBulletText("W, A, S, D : move camera");
c.igBulletText("Space : shoot");
}
// Scene selection.
{
c.igSpacing();
c.igSpacing();
comptime var str: [:0]const u8 = "";
comptime var i: u32 = 0;
inline while (i < scene_setup_table.len) : (i += 1) {
str = str ++ "Scene " ++ std.fmt.comptimePrint("{}", .{i}) ++ "\x00";
}
str = str ++ "\x00";
_ = c.igCombo_Str("##", &demo.current_scene_index, str.ptr, -1);
c.igSameLine(0.0, 0.0);
if (c.igButton(" Setup Scene ", .{ .x = 0, .y = 0 })) {
cleanupScene(demo.physics.world, &demo.physics.shapes, &demo.entities);
scene_setup_table[@intCast(usize, demo.current_scene_index)](
demo.physics.world,
&demo.physics.shapes,
&demo.entities,
&demo.camera,
);
}
c.igSpacing();
}
c.igEnd();
const window = demo.gctx.window;
// Handle camera rotation with mouse.
{
const cursor = window.getCursorPos() catch unreachable;
const delta_x = @floatCast(f32, cursor.xpos - demo.mouse.cursor.xpos);
const delta_y = @floatCast(f32, cursor.ypos - demo.mouse.cursor.ypos);
demo.mouse.cursor.xpos = cursor.xpos;
demo.mouse.cursor.ypos = cursor.ypos;
if (window.getMouseButton(.right) == .press) {
demo.camera.pitch += 0.0025 * delta_y;
demo.camera.yaw += 0.0025 * delta_x;
demo.camera.pitch = math.min(demo.camera.pitch, 0.48 * math.pi);
demo.camera.pitch = math.max(demo.camera.pitch, -0.48 * math.pi);
demo.camera.yaw = zm.modAngle(demo.camera.yaw);
}
}
// Handle camera movement with 'WASD' keys.
{
const speed = zm.f32x4s(5.0);
const delta_time = zm.f32x4s(demo.gctx.stats.delta_time);
const transform = zm.mul(zm.rotationX(demo.camera.pitch), zm.rotationY(demo.camera.yaw));
var forward = zm.normalize3(zm.mul(zm.f32x4(0.0, 0.0, 1.0, 0.0), transform));
zm.storeArr3(&demo.camera.forward, forward);
const right = speed * delta_time * zm.normalize3(zm.cross3(zm.f32x4(0.0, 1.0, 0.0, 0.0), forward));
forward = speed * delta_time * forward;
var cam_pos = zm.loadArr3(demo.camera.position);
if (window.getKey(.w) == .press) {
cam_pos += forward;
} else if (window.getKey(.s) == .press) {
cam_pos -= forward;
}
if (window.getKey(.d) == .press) {
cam_pos += right;
} else if (window.getKey(.a) == .press) {
cam_pos -= right;
}
zm.storeArr3(&demo.camera.position, cam_pos);
}
objectPicking(demo);
// Shooting.
{
demo.keyboard_delay += dt;
if (window.getKey(.space) == .press and demo.keyboard_delay >= 0.5) {
demo.keyboard_delay = 0.0;
const transform = zm.translationV(zm.loadArr3(demo.camera.position));
const impulse = zm.f32x4s(80.0) * zm.loadArr3(demo.camera.forward);
const body = zbt.Body.init(
1.0,
&zm.mat43ToArr(transform),
shape_sphere,
);
body.applyCentralImpulse(zm.arr3Ptr(&impulse));
createEntity(demo.physics.world, body, .{ 0.0, 0.8, 0.0, 0.2 }, 1.0, &demo.entities);
}
}
}
fn draw(demo: *DemoState) void {
const gctx = demo.gctx;
const fb_width = gctx.swapchain_descriptor.width;
const fb_height = gctx.swapchain_descriptor.height;
const cam_world_to_view = zm.lookToLh(
zm.loadArr3(demo.camera.position),
zm.loadArr3(demo.camera.forward),
zm.f32x4(0.0, 1.0, 0.0, 0.0),
);
const cam_view_to_clip = zm.perspectiveFovLh(
camera_fovy,
@intToFloat(f32, fb_width) / @intToFloat(f32, fb_height),
0.01,
200.0,
);
const cam_world_to_clip = zm.mul(cam_world_to_view, cam_view_to_clip);
const swapchain_texv = gctx.swapchain.getCurrentTextureView();
defer swapchain_texv.release();
const commands = commands: {
const encoder = gctx.device.createCommandEncoder(null);
defer encoder.release();
// Main pass.
pass: {
const vb_info = gctx.lookupResourceInfo(demo.vertex_buf) orelse break :pass;
const ib_info = gctx.lookupResourceInfo(demo.index_buf) orelse break :pass;
const mesh_pipe = gctx.lookupResource(demo.mesh_pipe) orelse break :pass;
const uniform_bg = gctx.lookupResource(demo.uniform_bg) orelse break :pass;
const depth_texv = gctx.lookupResource(demo.depth_texv) orelse break :pass;
const pass = zgpu.util.beginRenderPassSimple(encoder, .clear, swapchain_texv, null, depth_texv, 1.0);
defer zgpu.util.endRelease(pass);
pass.setVertexBuffer(0, vb_info.gpuobj.?, 0, vb_info.size);
pass.setIndexBuffer(ib_info.gpuobj.?, .uint32, 0, ib_info.size);
pass.setPipeline(mesh_pipe);
{
const mem = gctx.uniformsAllocate(FrameUniforms, 1);
mem.slice[0] = .{
.world_to_clip = zm.transpose(cam_world_to_clip),
.camera_position = demo.camera.position,
};
pass.setBindGroup(0, uniform_bg, &.{mem.offset});
}
const num_bodies = demo.physics.world.getNumBodies();
var body_index: i32 = 0;
while (body_index < num_bodies) : (body_index += 1) {
const body = demo.physics.world.getBody(body_index);
const entity = &demo.entities.items[@intCast(usize, body.getUserIndex(0))];
// Get transform matrix from the physics simulator.
const transform = object_to_world: {
var transform: [12]f32 = undefined;
body.getGraphicsWorldTransform(&transform);
break :object_to_world zm.loadMat43(transform[0..]);
};
const object_to_world = zm.mul(zm.scalingV(zm.loadArr3(entity.size)), transform);
const mem = gctx.uniformsAllocate(DrawUniforms, 1);
mem.slice[0] = .{
.object_to_world = zm.transpose(object_to_world),
.basecolor_roughness = entity.basecolor_roughness,
};
pass.setBindGroup(1, uniform_bg, &.{mem.offset});
pass.drawIndexed(
demo.meshes.items[entity.mesh_index].num_indices,
1,
demo.meshes.items[entity.mesh_index].index_offset,
@intCast(i32, demo.meshes.items[entity.mesh_index].vertex_offset),
0,
);
}
}
// Physics debug pass.
pass: {
demo.physics.world.debugDrawAll();
const num_vertices = @intCast(u32, demo.physics.debug.lines.items.len);
if (num_vertices == 0) break :pass;
var vb_info = gctx.lookupResourceInfo(demo.physics_debug_buf) orelse break :pass;
const physics_debug_pipe = gctx.lookupResource(demo.physics_debug_pipe) orelse break :pass;
const uniform_bg = gctx.lookupResource(demo.uniform_bg) orelse break :pass;
const depth_texv = gctx.lookupResource(demo.depth_texv) orelse break :pass;
// Resize `physics_debug_buf` if it is too small.
if (num_vertices * @sizeOf(zbt.DebugDrawer.Vertex) > vb_info.size) {
gctx.destroyResource(demo.physics_debug_buf);
demo.physics_debug_buf = gctx.createBuffer(.{
.usage = .{ .copy_dst = true, .vertex = true },
.size = (2 * num_vertices) * @sizeOf(zbt.DebugDrawer.Vertex),
});
vb_info = gctx.lookupResourceInfo(demo.physics_debug_buf) orelse break :pass;
}
gctx.queue.writeBuffer(vb_info.gpuobj.?, 0, zbt.DebugDrawer.Vertex, demo.physics.debug.lines.items);
demo.physics.debug.lines.clearRetainingCapacity();
const pass = zgpu.util.beginRenderPassSimple(encoder, .load, swapchain_texv, null, depth_texv, null);
defer zgpu.util.endRelease(pass);
pass.setVertexBuffer(0, vb_info.gpuobj.?, 0, num_vertices * @sizeOf(zbt.DebugDrawer.Vertex));
pass.setPipeline(physics_debug_pipe);
{
const mem = gctx.uniformsAllocate(zm.Mat, 1);
mem.slice[0] = zm.transpose(cam_world_to_clip);
pass.setBindGroup(0, uniform_bg, &.{mem.offset});
}
pass.draw(num_vertices, 1, 0, 0);
}
// Gui pass.
{
const pass = zgpu.util.beginRenderPassSimple(encoder, .load, swapchain_texv, null, null, null);
defer zgpu.util.endRelease(pass);
zgpu.gui.draw(pass);
}
break :commands encoder.finish(null);
};
defer commands.release();
gctx.submit(&.{commands});
if (gctx.present() == .swap_chain_resized) {
// Release old depth texture.
gctx.releaseResource(demo.depth_texv);
gctx.destroyResource(demo.depth_tex);
// Create a new depth texture to match the new window size.
const depth = createDepthTexture(gctx);
demo.depth_tex = depth.tex;
demo.depth_texv = depth.texv;
}
}
fn createDepthTexture(gctx: *zgpu.GraphicsContext) struct {
tex: zgpu.TextureHandle,
texv: zgpu.TextureViewHandle,
} {
const tex = gctx.createTexture(.{
.usage = .{ .render_attachment = true },
.dimension = .dimension_2d,
.size = .{
.width = gctx.swapchain_descriptor.width,
.height = gctx.swapchain_descriptor.height,
.depth_or_array_layers = 1,
},
.format = .depth32_float,
.mip_level_count = 1,
.sample_count = 1,
});
const texv = gctx.createTextureView(tex, .{});
return .{ .tex = tex, .texv = texv };
}
const initial_scene = 0;
const scene_setup_table: [2]fn (
world: *const zbt.World,
shapes: *std.ArrayList(*const zbt.Shape),
entities: *std.ArrayList(Entity),
camera: *Camera,
) void = .{
setupScene0,
setupScene1,
};
fn setupScene0(
world: *const zbt.World,
shapes: *std.ArrayList(*const zbt.Shape),
entities: *std.ArrayList(Entity),
camera: *Camera,
) void {
assert(shapes.items.len == 0 and entities.items.len == 0);
const world_body = zbt.Body.init(0.0, &zm.mat43ToArr(zm.identity()), shape_world);
createEntity(world, world_body, .{ 0.25, 0.25, 0.25, 0.125 }, 0.0, entities);
{
const box_body = zbt.Body.init(10.0, &zm.mat43ToArr(zm.translation(0.0, 5.0, 5.0)), shape_cube);
createEntity(world, box_body, .{ 0.8, 0.0, 0.0, 0.25 }, 1.05, entities);
}
{
const shape = zbt.BoxShape.init(&.{ 0.5, 1.0, 2.0 });
shapes.append(shape.asShape()) catch unreachable;
const box_body = zbt.Body.init(15.0, &zm.mat43ToArr(zm.translation(-5.0, 5.0, 5.0)), shape.asShape());
createEntity(world, box_body, .{ 1.0, 0.9, 0.0, 0.75 }, 0.55, entities);
}
camera.* = .{
.position = .{ 0.0, 3.0, 0.0 },
.pitch = math.pi * 0.05,
.yaw = 0.0,
};
}
fn setupScene1(
world: *const zbt.World,
shapes: *std.ArrayList(*const zbt.Shape),
entities: *std.ArrayList(Entity),
camera: *Camera,
) void {
assert(shapes.items.len == 0 and entities.items.len == 0);
const world_body = zbt.Body.init(0.0, &zm.mat43ToArr(zm.identity()), shape_world);
createEntity(world, world_body, .{ 0.25, 0.25, 0.25, 0.125 }, 0.0, entities);
var i: u32 = 0;
while (i < 10) : (i += 1) {
const box_body = zbt.Body.init(
5.0,
&zm.mat43ToArr(zm.translation(0.0, 5.0 + @intToFloat(f32, i) * 2.05, 10.0)),
shape_cube,
);
createEntity(world, box_body, .{ 0.8, 0.0, 0.0, 0.25 }, 1.05, entities);
}
camera.* = .{
.position = .{ 0.0, 3.0, 0.0 },
.pitch = math.pi * 0.05,
.yaw = 0.0,
};
}
fn cleanupScene(
world: *const zbt.World,
shapes: *std.ArrayList(*const zbt.Shape),
entities: *std.ArrayList(Entity),
) void {
var i = world.getNumBodies() - 1;
while (i >= 0) : (i -= 1) {
const body = world.getBody(i);
world.removeBody(body);
body.deinit();
}
for (shapes.items) |shape| shape.deinit();
shapes.clearRetainingCapacity();
entities.clearRetainingCapacity();
}
fn createEntity(
world: *const zbt.World,
body: *const zbt.Body,
basecolor_roughness: [4]f32,
swept_sphere_radius: f32,
entities: *std.ArrayList(Entity),
) void {
const shape = body.getShape();
const shape_type = shape.getType();
const mesh_index = switch (shape_type) {
.box => mesh_index_cube,
.sphere => mesh_index_sphere,
.trimesh => mesh_index_world,
else => unreachable,
};
const mesh_size = switch (shape_type) {
.box => mesh_size: {
var half_extents: [3]f32 = undefined;
@ptrCast(*const zbt.BoxShape, shape).getHalfExtentsWithMargin(&half_extents);
break :mesh_size half_extents;
},
.sphere => mesh_size: {
const r = @ptrCast(*const zbt.SphereShape, shape).getRadius();
break :mesh_size [3]f32{ r, r, r };
},
else => [3]f32{ 1.0, 1.0, 1.0 },
};
const entity_index = @intCast(i32, entities.items.len);
entities.append(.{
.body = body,
.basecolor_roughness = basecolor_roughness,
.size = mesh_size,
.mesh_index = mesh_index,
}) catch unreachable;
body.setUserIndex(0, entity_index);
if (swept_sphere_radius != 0.0) {
body.setCcdSweptSphereRadius(swept_sphere_radius);
body.setCcdMotionThreshold(1e-7);
}
body.setDamping(default_linear_damping, default_angular_damping);
body.setActivationState(.deactivation_disabled);
world.addBody(body);
}
fn appendMesh(
mesh: zmesh.Shape,
all_meshes: *std.ArrayList(Mesh),
all_indices: *std.ArrayList(u32),
all_positions: *std.ArrayList([3]f32),
all_normals: *std.ArrayList([3]f32),
) !u32 {
const mesh_index = @intCast(u32, all_meshes.items.len);
try all_meshes.append(.{
.index_offset = @intCast(u32, all_indices.items.len),
.vertex_offset = @intCast(u32, all_positions.items.len),
.num_indices = @intCast(u32, mesh.indices.len),
.num_vertices = @intCast(u32, mesh.positions.len),
});
try all_indices.appendSlice(mesh.indices);
try all_positions.appendSlice(mesh.positions);
try all_normals.appendSlice(mesh.normals.?);
return mesh_index;
}
fn initMeshes(
arena: std.mem.Allocator,
all_meshes: *std.ArrayList(Mesh),
all_indices: *std.ArrayList(u32),
all_positions: *std.ArrayList([3]f32),
all_normals: *std.ArrayList([3]f32),
) !void {
// Cube mesh.
{
var mesh = zmesh.Shape.initCube();
defer mesh.deinit();
mesh.translate(-0.5, -0.5, -0.5);
mesh.scale(2.0, 2.0, 2.0);
mesh.unweld();
mesh.computeNormals();
const mesh_index = try appendMesh(mesh, all_meshes, all_indices, all_positions, all_normals);
assert(mesh_index == mesh_index_cube);
shape_cube = zbt.BoxShape.init(&.{ 1.0, 1.0, 1.0 }).asShape();
}
// Parametric sphere.
{
var mesh = zmesh.Shape.initParametricSphere(8, 8);
defer mesh.deinit();
mesh.unweld();
mesh.computeNormals();
const mesh_index = try appendMesh(mesh, all_meshes, all_indices, all_positions, all_normals);
assert(mesh_index == mesh_index_sphere);
shape_sphere = zbt.SphereShape.init(1.0).asShape();
}
// World mesh.
{
const mesh_index = @intCast(u32, all_meshes.items.len);
const index_offset = @intCast(u32, all_indices.items.len);
const vertex_offset = @intCast(u32, all_positions.items.len);
var indices = std.ArrayList(u32).init(arena);
defer indices.deinit();
var positions = std.ArrayList([3]f32).init(arena);
defer positions.deinit();
var normals = std.ArrayList([3]f32).init(arena);
defer normals.deinit();
const data = try zmesh.io.parseAndLoadFile(content_dir ++ "world.gltf");
defer zmesh.io.cgltf.free(data);
try zmesh.io.appendMeshPrimitive(data, 0, 0, &indices, &positions, &normals, null, null);
// "Unweld" mesh, this creates un-optimized mesh with duplicated vertices.
// We need it for wireframes and facet look.
for (indices.items) |ind, i| {
try all_positions.append(positions.items[ind]);
try all_normals.append(normals.items[ind]);
try all_indices.append(@intCast(u32, i));
}
try all_meshes.append(.{
.index_offset = index_offset,
.vertex_offset = vertex_offset,
.num_indices = @intCast(u32, all_indices.items.len) - index_offset,
.num_vertices = @intCast(u32, all_positions.items.len) - vertex_offset,
});
assert(mesh_index == mesh_index_world);
const trimesh = zbt.TriangleMeshShape.init();
trimesh.addIndexVertexArray(
@intCast(u32, indices.items.len / 3),
indices.items.ptr,
@sizeOf([3]u32),
@intCast(u32, positions.items.len),
positions.items.ptr,
@sizeOf([3]f32),
);
trimesh.finish();
shape_world = trimesh.asShape();
}
}
fn objectPicking(demo: *DemoState) void {
const window = demo.gctx.window;
const mouse_button_is_down = window.getMouseButton(.left) == .press and !c.igGetIO().?.*.WantCaptureMouse;
const ray_from = zm.loadArr3(demo.camera.position);
const ray_to = ray_to: {
const cursor = window.getCursorPos() catch unreachable;
const mousex = @floatCast(f32, cursor.xpos);
const mousey = @floatCast(f32, cursor.ypos);
const far_plane = zm.f32x4s(10_000.0);
const tanfov = zm.f32x4s(@tan(0.5 * camera_fovy));
const winsize = window.getSize() catch unreachable;
const width = @intToFloat(f32, winsize.width);
const height = @intToFloat(f32, winsize.height);
const aspect = zm.f32x4s(width / height);
const ray_forward = zm.loadArr3(demo.camera.forward) * far_plane;
const hor = zm.normalize3(zm.cross3(zm.f32x4(0, 1, 0, 0), ray_forward)) *
zm.f32x4s(2.0) * far_plane * tanfov * aspect;
const vert = zm.normalize3(zm.cross3(hor, ray_forward)) *
zm.f32x4s(2.0) * far_plane * tanfov;
const ray_to_center = ray_from + ray_forward;
const dhor = zm.f32x4s(1.0 / width) * hor;
const dvert = zm.f32x4s(1.0 / height) * vert;
var ray_to = ray_to_center + zm.f32x4s(-0.5) * hor + zm.f32x4s(-0.5) * vert;
ray_to += dhor * zm.f32x4s(mousex);
ray_to += dvert * zm.f32x4s(mousey);
break :ray_to ray_to;
};
if (!demo.pick.p2p.isCreated() and mouse_button_is_down) {
var result: zbt.RayCastResult = undefined;
const is_hit = demo.physics.world.rayTestClosest(
zm.arr3Ptr(&ray_from),
zm.arr3Ptr(&ray_to),
.{ .default = true },
zbt.CollisionFilter.all,
.{ .use_gjk_convex_test = true },
&result,
);
if (is_hit) if (result.body) |body| if (!body.isStaticOrKinematic()) {
demo.pick.body = body;
demo.pick.saved_linear_damping = body.getLinearDamping();
demo.pick.saved_angular_damping = body.getAngularDamping();
body.setDamping(0.4, 0.4);
const pivot_a = zm.mul(
zm.loadArr3w(result.hit_point_world, 1.0),
loadInvCenterOfMassTransform(body),
);
demo.pick.p2p.create1(body, zm.arr3Ptr(&pivot_a));
demo.pick.p2p.setImpulseClamp(30.0);
demo.pick.p2p.setDebugDrawSize(0.15);
demo.physics.world.addConstraint(demo.pick.p2p.asConstraint(), true);
demo.pick.distance = zm.length3(zm.loadArr3(result.hit_point_world) - ray_from)[0];
};
} else if (demo.pick.p2p.isCreated() and mouse_button_is_down) {
const to = ray_from + zm.normalize3(ray_to) * zm.f32x4s(demo.pick.distance);
demo.pick.p2p.setPivotB(zm.arr3Ptr(&to));
const trans_a = loadCenterOfMassTransform(demo.pick.p2p.getBodyA());
const trans_b = loadCenterOfMassTransform(demo.pick.p2p.getBodyB());
const pivot_a = loadPivotA(demo.pick.p2p);
const pivot_b = loadPivotB(demo.pick.p2p);
const position_a = zm.mul(pivot_a, trans_a);
const position_b = zm.mul(pivot_b, trans_b);
demo.physics.world.debugDrawLine2(
zm.arr3Ptr(&position_a),
zm.arr3Ptr(&position_b),
&.{ 1.0, 1.0, 0.0 },
&.{ 1.0, 0.0, 0.0 },
);
demo.physics.world.debugDrawSphere(zm.arr3Ptr(&position_a), 0.05, &.{ 0.0, 1.0, 0.0 });
}
if (!mouse_button_is_down and demo.pick.p2p.isCreated()) {
demo.physics.world.removeConstraint(demo.pick.p2p.asConstraint());
demo.pick.p2p.destroy();
demo.pick.body.?.setDamping(demo.pick.saved_linear_damping, demo.pick.saved_angular_damping);
demo.pick.body = null;
}
}
fn loadCenterOfMassTransform(body: *const zbt.Body) zm.Mat {
var transform: [12]f32 = undefined;
body.getCenterOfMassTransform(&transform);
return zm.loadMat43(transform[0..]);
}
fn loadInvCenterOfMassTransform(body: *const zbt.Body) zm.Mat {
var transform: [12]f32 = undefined;
body.getInvCenterOfMassTransform(&transform);
return zm.loadMat43(transform[0..]);
}
fn loadPivotA(p2p: *const zbt.Point2PointConstraint) zm.Vec {
var pivot: [3]f32 = undefined;
p2p.getPivotA(&pivot);
return zm.loadArr3w(pivot, 1.0);
}
fn loadPivotB(p2p: *const zbt.Point2PointConstraint) zm.Vec {
var pivot: [3]f32 = undefined;
p2p.getPivotB(&pivot);
return zm.loadArr3w(pivot, 1.0);
}
pub fn main() !void {
try glfw.init(.{});
defer glfw.terminate();
zgpu.checkSystem(content_dir) catch {
// In case of error zgpu.checkSystem() will print error message.
return;
};
const window = try glfw.Window.create(1600, 1000, window_title, null, null, .{
.client_api = .no_api,
.cocoa_retina_framebuffer = true,
});
defer window.destroy();
try window.setSizeLimits(.{ .width = 400, .height = 400 }, .{ .width = null, .height = null });
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
// Init zbullet library.
zbt.init(allocator);
defer zbt.deinit();
const demo = try init(allocator, window);
defer deinit(allocator, demo);
zgpu.gui.init(window, demo.gctx.device, content_dir, "Roboto-Medium.ttf", 25.0);
defer zgpu.gui.deinit();
while (!window.shouldClose()) {
try glfw.pollEvents();
update(demo);
draw(demo);
}
} | samples/bullet_physics_test_wgpu/src/bullet_physics_test_wgpu.zig |
const std = @import("std");
const builtin = @import("builtin");
const IsWasm = builtin.target.isWasm();
const stdx = @import("stdx");
const graphics = @import("graphics");
const Color = graphics.Color;
const ui = @import("ui");
const Row = ui.widgets.Row;
const Text = ui.widgets.Text;
const Padding = ui.widgets.Padding;
const Center = ui.widgets.Center;
const TextField = ui.widgets.TextField;
const helper = @import("helper.zig");
const log = stdx.log.scoped(.main);
pub const App = struct {
tc_field: ui.WidgetRef(TextField),
tf_field: ui.WidgetRef(TextField),
const Self = @This();
pub fn build(self: *Self, c: *ui.BuildContext) ui.FrameId {
const S = struct {
fn onChangeTc(self_: *Self, text: []const u8) void {
const tc = std.fmt.parseFloat(f32, text) catch return;
self_.tf_field.getWidget().setValueFmt("{d:.2}", .{ tc * 9/5 + 32 });
}
fn onChangeTf(self_: *Self, text: []const u8) void {
const tf = std.fmt.parseFloat(f32, text) catch return;
self_.tc_field.getWidget().setValueFmt("{d:.2}", .{ (tf - 32) * 5 / 9 });
}
};
return c.decl(Center, .{
.child = c.decl(Row, .{
.expand = false,
.children = c.list(.{
c.decl(TextField, .{
.bind = &self.tc_field,
.width = 200,
.onChangeEnd = c.funcExt(self, S.onChangeTc),
}),
c.decl(Padding, .{
.child = c.decl(Text, .{
.text = "Celsius =",
.color = Color.White,
}),
}),
c.decl(TextField, .{
.bind = &self.tf_field,
.width = 200,
.onChangeEnd = c.funcExt(self, S.onChangeTf),
}),
c.decl(Padding, .{
.child = c.decl(Text, .{
.text = "Fahrenheit",
.color = Color.White,
}),
}),
}),
}),
});
}
};
var app: helper.App = undefined;
pub fn main() !void {
// This is the app loop for desktop. For web/wasm see wasm exports below.
app.init("Converter");
defer app.deinit();
app.runEventLoop(update);
}
fn update(delta_ms: f32) void {
const S = struct {
fn buildRoot(_: void, c: *ui.BuildContext) ui.FrameId {
return c.decl(App, .{});
}
};
const ui_width = @intToFloat(f32, app.win.getWidth());
const ui_height = @intToFloat(f32, app.win.getHeight());
app.ui_mod.updateAndRender(delta_ms, {}, S.buildRoot, ui_width, ui_height) catch unreachable;
}
pub usingnamespace if (IsWasm) struct {
export fn wasmInit() *const u8 {
return helper.wasmInit(&app, "Converter");
}
export fn wasmUpdate(cur_time_ms: f64, input_buffer_len: u32) *const u8 {
return helper.wasmUpdate(cur_time_ms, input_buffer_len, &app, update);
}
/// Not that useful since it's a long lived process in the browser.
export fn wasmDeinit() void {
app.deinit();
stdx.wasm.deinit();
}
} else struct {}; | ui/examples/converter.zig |
const std = @import("std");
const json = std.json;
const person_module = @import("person.zig");
const date_module = @import("date.zig");
const notes_module = @import("notes.zig");
const util = @import("util.zig");
const logger = std.log.scoped(.ft);
const ArrayListUnmanaged = std.ArrayListUnmanaged;
const Allocator = std.mem.Allocator;
const Date = date_module.Date;
const Person = person_module.Person;
pub const Family = struct {
id: Id,
// families are meant to be purely social,
// family trees handle blood connections
father_id: ?Person.Id = null,
mother_id: ?Person.Id = null,
marriage_date: ?Date = null,
divorce_date: ?Date = null,
children_ids: ChildrenIds = .{},
pub const Id = i64;
pub const FromJsonError = error {
bad_type, bad_field, bad_field_val,
allocator_required,
};
pub fn deinit(this: *Family, ator: Allocator) void {
this.children_ids.deinit(ator);
}
pub fn addChild(this: *Family, child_id: Person.Id, ator: Allocator) !void {
try this.children_ids.addChild(child_id, ator);
}
pub fn hasChild(self: Family, candidate: Person.Id) bool {
return self.children_ids.hasChild(candidate);
// for (self.children_ids.items) |child_id| {
// if (child_id == candidate)
// return true;
// }
// return false;
}
pub fn readFromJson(
this: *Family,
json_family: json.Value,
allocator: ?Allocator,
) !void {
switch (json_family) {
json.Value.Object => |map| {
inline for (@typeInfo(Family).Struct.fields) |field| {
if (map.get(field.name)) |val| {
switch (field.field_type) {
Id => {
switch (val) {
json.Value.Integer => |int| {
this.id = int;
},
else => {
logger.err(
"in Family.readFromJson()" ++
" j_family.get(\"id\")" ++
" is not of type {s}"
, .{"json.Integer"}
);
return FromJsonError.bad_field;
},
}
},
?Person.Id => {
switch (val) {
json.Value.Integer => |int| {
@field(this, field.name) = int;
},
json.Value.Null => {
@field(this, field.name) = null;
},
else => {
logger.err(
"in Family.readFromJson()" ++
" j_family.get(\"{s}\")" ++
" is of neither type {s} nor {s}"
, .{field.name, "json.Integer", "json.Null"}
);
return FromJsonError.bad_field;
},
}
},
?Date => {
switch (val) {
.Null => {
@field(this, field.name) = null;
},
else => {
var field_ptr = &@field(this, field.name);
if (null == field_ptr.*) {
field_ptr.* = .{};
errdefer field_ptr.* = null;
try field_ptr.*.?.readFromJson(val);
} else {
try field_ptr.*.?.readFromJson(val);
}
},
}
},
ChildrenIds => {
try @field(this, field.name).readFromJson(val, allocator);
},
else => {
@compileError("Family.readFromJson() nonexhaustive switch on field_type");
},
}
}
}
},
else => {
logger.err(
"in Family.readFromJson() j_family is not of type {s}"
, .{"json.ObjectMap"}
);
return FromJsonError.bad_type;
},
}
}
pub fn readFromJsonSourceStr(
this: *Family,
source_str: []const u8,
ator: Allocator,
) !void {
var parser = json.Parser.init(ator, false); // strings are copied in readFromJson
defer parser.deinit();
var tree = try parser.parse(source_str);
defer tree.deinit();
try this.readFromJson(tree.root, ator);
}
// pub fn toJson(self: Family, ator: Allocator) json.ObjectMap {
// var res = json.ObjectMap.init(ator);
// errdefer res.deinit();
// inline for (@typeInfo(Family).Struct.fields) |field| {
// res.put(
// field.name,
// if (@hasDecl(@TypeOf(@field(self, field.name)), "toJson")) {
// @field(self, field.name).toJson();
// } else {
// @field(self, field.name);
// }
// );
// }
// return res;
// }
pub fn toJson(
self: Family,
ator: Allocator,
comptime settings: util.ToJsonSettings,
) util.ToJsonError!util.ToJsonResult {
return util.toJson(
self, ator,
.{.allow_overload=false, .apply_arena=settings.apply_arena},
);
}
pub const ParentEnum = enum {
father, mother,
pub fn asText(comptime self: ParentEnum) switch (self) {
.father => @TypeOf("father"),
.mother => @TypeOf("mother"),
} {
return switch (self) {
.father => "father",
.mother => "mother",
};
}
};
};
pub const ChildrenIds = struct {
data: ArrayListUnmanaged(Person.Id) = .{},
pub const FromJsonError = error {
bad_field, bad_field_val, allocator_required,
};
pub fn readFromJson(
this: *ChildrenIds,
json_children: json.Value,
allocator: ?Allocator,
) !void {
switch (json_children) {
json.Value.Array => |arr| {
if (arr.items.len > 0) {
if (allocator) |ator| {
try copyFromJsonArr(
&this.data,
arr,
ator,
);
} else {
logger.err(
"in Family.readFromJson() allocator required"
, .{}
);
return FromJsonError.allocator_required;
}
} else {
return;
}
},
else => {
logger.err(
"in Family.readFromJson()" ++
" j_family.get(\"{s}\")" ++
" is not of type {s}"
, .{"children_ids", "json.Array"}
);
return FromJsonError.bad_field;
},
}
}
fn copyFromJsonArr(
dest: *ArrayListUnmanaged(Person.Id),
source: json.Array,
ator: Allocator,
) !void {
var last_read_id: ?Person.Id = null;
try dest.ensureUnusedCapacity(ator, source.items.len);
errdefer dest.shrinkAndFree(ator, dest.items.len);
for (source.items) |item| {
switch (item) {
json.Value.Integer => |int| {
dest.appendAssumeCapacity(int);
last_read_id = int;
},
else => {
if (last_read_id) |lri| {
logger.err(
"in Family.readFromJson() (children_ids)" ++
" last successfully read id is {d}"
, .{lri}
);
} else {
logger.err(
"in Family.readFromJson() (children_ids)" ++
" no id could be read"
, .{}
);
}
return FromJsonError.bad_field_val;
},
}
}
}
pub fn toJson(
self: ChildrenIds,
ator: Allocator,
comptime settings: util.ToJsonSettings,
) util.ToJsonError!util.ToJsonResult {
return util.toJson(self.data.items, ator, settings);
}
pub fn deinit(this: *ChildrenIds, ator: Allocator) void {
this.data.deinit(ator);
}
pub fn addChild(this: *ChildrenIds, child_id: Person.Id, ator: Allocator) !void {
try this.data.append(ator, child_id);
}
pub fn hasChild(self: ChildrenIds, candidate: Person.Id) bool {
for (self.data.items) |child_id| {
if (child_id == candidate)
return true;
}
return false;
}
// pub fn equal(
// self: ChildrenIds,
// other: ChildrenIds,
// comptime settings: util.EqualSettings,
// ) bool {
// if (self.data.count() != other.data.count()) {
// return false;
// }
// for (self.data)
// }
};
const testing = std.testing;
const tator = testing.allocator;
const expect = testing.expect;
const expectEqual = testing.expectEqual;
const expectError = testing.expectError;
const father_source =
\\{
\\ "id": 1,
\\ "name": {
\\ "normal_form": "Father",
\\ "short_form": "Daddy",
\\ "patronymic_male_form": "Fathersson",
\\ "patronymic_female_form": "Fathersdaughter"
\\ },
\\ "surname": {"male_form": "Ivanov", "female_form": "Ivanova"},
\\ "patronymic": "Fathersson",
\\ "sex": "male",
\\ "birth_date": {"day": 3, "month": 2, "year": 2000},
\\ "death_date": null,
\\ "notes": ""
\\}
;
const mother_source =
\\{
\\ "id": 2,
\\ "name": {"normal_form": "Mother", "short_form": "Mommy"},
\\ "surname": {"male_form": "Petrov", "female_form": "Petrova"},
\\ "patronymic": "Fathersdaughter",
\\ "sex": "female",
\\ "birth_date": {"day": 2, "month": 3, "year": 2000},
\\ "death_date": null,
\\ "notes": ""
\\}
;
const son_source =
\\{
\\ "id": 3,
\\ "name": "Son",
\\ "surname": {"male_form": "Ivanov", "female_form": "Ivanova"},
\\ "patronymic": "Fathersson",
\\ "sex": "male",
\\ "birth_date": {"day": 4, "month": 5, "year": 2020},
\\ "death_date": null,
\\ "notes": ""
\\}
;
const daughter_source =
\\{
\\ "id": 4,
\\ "name": "Daughter",
\\ "surname": {"male_form": "Ivanov", "female_form": "Ivanova"},
\\ "patronymic": "Fathersdaughter",
\\ "sex": "female",
\\ "birth_date": {"day": 4, "month": 5, "year": 2020},
\\ "death_date": null,
\\ "notes": ""
\\}
;
const family_source =
\\{
\\ "id": 0,
\\ "father_id": 1,
\\ "mother_id": 2,
\\ "children_ids": [3, 4],
\\ "marriage_date": {"day": null, "month": 1, "year": 2018}
\\}
;
test "basic" {
{
var father = Person{.id=-1};
try father.readFromJsonSourceStr(father_source, tator, .copy);
defer father.deinit(testing.allocator);
var mother = Person{.id=-1};
try mother.readFromJsonSourceStr(mother_source, tator, .copy);
defer mother.deinit(testing.allocator);
var family = Family{.id=undefined};
defer family.deinit(tator);
try family.readFromJsonSourceStr(family_source, tator);
try expectEqual(family.marriage_date.?.day, null);
try expectEqual(family.marriage_date.?.month, 1);
try expectEqual(family.marriage_date.?.year, 2018);
try expectEqual(family.divorce_date, null);
try expectEqual(family.father_id, 1);
try expectEqual(family.mother_id, 2);
try expectEqual(family.children_ids.data.items.len, 2);
try expectEqual(family.children_ids.data.items[0], 3);
try expectEqual(family.children_ids.data.items[1], 4);
}
}
fn testError(src: []const u8, expected_error: anyerror) !void {
var fam = Family{.id=undefined};
defer fam.deinit(tator);
try expectError(expected_error, fam.readFromJsonSourceStr(src, tator));
}
const bad_type_src =
\\"family"
;
const bad_field_src_id =
\\{
\\ "id": "family"
\\}
;
const bad_field_src_father_id =
\\{
\\ "father_id": "father"
\\}
;
const bad_field_src_mother_id =
\\{
\\ "mother_id": "mother"
\\}
;
const bad_field_src_children_ids =
\\{
\\ "children_ids": true
\\}
;
const bad_field_sources = [_][]const u8{
bad_field_src_id,
bad_field_src_father_id,
bad_field_src_mother_id,
bad_field_src_children_ids,
};
const bad_field_val_src =
\\{
\\ "children_ids": [3, 4, "kid"]
\\}
;
fn testAllocatorRequired(src: []const u8) !void {
var parser = json.Parser.init(tator, false); // strings are copied in readFromJson
defer parser.deinit();
var tree = try parser.parse(src);
defer tree.deinit();
var fam = Family{.id=undefined};
defer fam.deinit(tator);
try expectError(anyerror.allocator_required, fam.readFromJson(tree.root, null));
}
test "errors" {
try testError(bad_type_src, anyerror.bad_type);
for (bad_field_sources) |bf_src| {
try testError(bf_src, anyerror.bad_field);
}
try testError(bad_field_val_src, anyerror.bad_field_val);
try testAllocatorRequired(bad_field_val_src);
}
test "add child" {
{
var father = Person{.id=undefined};
try father.readFromJsonSourceStr(father_source, tator, .copy);
defer father.deinit(testing.allocator);
var mother = Person{.id=undefined};
try mother.readFromJsonSourceStr(mother_source, tator, .copy);
defer mother.deinit(testing.allocator);
var family = Family{
.id = undefined,
.father_id = father.id,
.mother_id = mother.id,
};
defer family.deinit(tator);
var son = Person{.id=undefined};
try son.readFromJsonSourceStr(son_source, tator, .copy);
defer son.deinit(tator);
var daughter = Person{.id=undefined};
try daughter.readFromJsonSourceStr(daughter_source, tator, .copy);
defer daughter.deinit(tator);
try expect(!family.hasChild(3));
try expect(!family.hasChild(4));
try family.addChild(son.id, tator);
try family.addChild(daughter.id, tator);
try expectEqual(family.children_ids.data.items[0], 3);
try expectEqual(family.children_ids.data.items[1], 4);
try expect(family.hasChild(3));
try expect(family.hasChild(4));
}
}
test "to json" {
var family = Family{.id = undefined};
defer family.deinit(tator);
try family.readFromJsonSourceStr(family_source, tator);
var j_family = try family.toJson(tator, .{});
defer j_family.deinit();
var ylimaf = Family{.id = undefined};
defer ylimaf.deinit(tator);
try ylimaf.readFromJson(j_family.value, tator);
try expect(util.equal(family, ylimaf, .{}));
}
fn strCopyAlloc(from: []const u8, ator: Allocator) ![]u8 {
var res = try ator.alloc(u8, from.len);
for (from) |c, i| {
res[i] = c;
}
return res;
}
fn strEqual(lhs: []const u8, rhs: []const u8) bool {
if (lhs.len != rhs.len)
return false;
for (lhs) |c, i| {
if (c != rhs[i])
return false;
}
return true;
} | src/family.zig |
const aoc = @import("../aoc.zig");
const std = @import("std");
const Arena = std.heap.ArenaAllocator;
const Defab = std.StringHashMap([]const u8);
const DefabOrder = std.ArrayList([]const u8);
const Fab = aoc.StringMultimap([]const u8);
const MoleculeSet = std.StringHashMap(void);
pub fn run(problem: *aoc.Problem) !aoc.Solution {
var fab = Fab.init(problem.allocator);
defer fab.deinit();
var defab = Defab.init(problem.allocator);
defer defab.deinit();
var defab_order = DefabOrder.init(problem.allocator);
defer defab_order.deinit();
var medicine: []const u8 = undefined;
while (problem.line()) |line| {
if (line.len > 20) {
medicine = line;
break;
}
var tokens = std.mem.tokenize(u8, line, " ");
const key = tokens.next().?;
_ = tokens.next().?;
const value = tokens.next().?;
try fab.put(key, value);
try defab.putNoClobber(value, key);
try defab_order.append(value);
}
std.sort.sort([]const u8, defab_order.items, {}, compareLengths);
const uniquePossibilities = blk: {
var arena = Arena.init(problem.allocator);
defer arena.deinit();
var possibilities = MoleculeSet.init(problem.allocator);
defer possibilities.deinit();
var idx: usize = 0;
var end_idx: usize = undefined;
while (idx < medicine.len) : (idx = end_idx) {
end_idx = nextAtom(medicine, idx) orelse unreachable;
const key = medicine[idx..end_idx];
const values = fab.get(key) orelse continue;
for (values) |replacement| {
_ = try possibilities.put(try replaceString(&arena, medicine, idx, end_idx, replacement), {});
}
}
break :blk possibilities.count();
};
const fastestFabrication = blk: {
var replacements: usize = 0;
var buf: [512]u8 = undefined;
std.mem.copy(u8, &buf, medicine);
var buf_slice = buf[0..medicine.len];
outer: while (!std.mem.eql(u8, buf_slice, "e")) {
for (defab_order.items) |key| {
const count = std.mem.count(u8, buf_slice, key);
if (count != 0) {
replacements += count;
const value = defab.get(key).?;
_ = std.mem.replace(u8, buf_slice, key, value, &buf);
buf_slice.len -= (key.len - value.len) * count;
continue :outer;
}
}
unreachable;
}
break :blk replacements;
};
return problem.solution(uniquePossibilities, fastestFabrication);
}
fn nextAtom(molecule: []const u8, idx: usize) ?usize {
if (idx == molecule.len) {
return null;
}
const range: usize = if (idx == molecule.len - 1 or molecule[idx + 1] < 'a') 1 else 2;
return idx + range;
}
fn replaceString(arena: *Arena, molecule: []const u8, idx: usize, end_idx: usize, replacement: []const u8) ![]u8 {
return std.fmt.allocPrint(arena.allocator(), "{s}{s}{s}", .{
molecule[0..idx], replacement, molecule[end_idx..]
});
}
fn compareLengths(_: void, a: []const u8, b: []const u8) bool {
return a.len > b.len;
} | src/main/zig/2015/day19.zig |
const c = @import("c.zig");
pub const Error = error{
CannotOpenResource,
UnknownFileFormat,
InvalidFileFormat,
InvalidVersion,
LowerModuleVersion,
InvalidArgument,
UnimplementedFeature,
InvalidTable,
InvalidOffset,
ArrayTooLarge,
MissingModule,
MissingProperty,
InvalidGlyphIndex,
InvalidCharacterCode,
InvalidGlyphFormat,
CannotRenderGlyph,
InvalidOutline,
InvalidComposite,
TooManyHints,
InvalidPixelSize,
InvalidHandle,
InvalidLibraryHandle,
InvalidDriverHandle,
InvalidFaceHandle,
InvalidSizeHandle,
InvalidSlotHandle,
InvalidCharMapHandle,
InvalidCacheHandle,
InvalidStreamHandle,
TooManyDrivers,
TooManyExtensions,
OutOfMemory,
UnlistedObject,
CannotOpenStream,
InvalidStreamSeek,
InvalidStreamSkip,
InvalidStreamRead,
InvalidStreamOperation,
InvalidFrameOperation,
NestedFrameAccess,
InvalidFrameRead,
RasterUninitialized,
RasterCorrupted,
RasterOverflow,
RasterNegativeHeight,
TooManyCaches,
InvalidOpcode,
TooFewArguments,
StackOverflow,
CodeOverflow,
BadArgument,
DivideByZero,
InvalidReference,
DebugOpCode,
ENDFInExecStream,
NestedDEFS,
InvalidCodeRange,
ExecutionTooLong,
TooManyFunctionDefs,
TooManyInstructionDefs,
TableMissing,
HorizHeaderMissing,
LocationsMissing,
NameTableMissing,
CMapTableMissing,
HmtxTableMissing,
PostTableMissing,
InvalidHorizMetrics,
InvalidCharMapFormat,
InvalidPPem,
InvalidVertMetrics,
CouldNotFindContext,
InvalidPostTableFormat,
InvalidPostTable,
Syntax,
StackUnderflow,
Ignore,
NoUnicodeGlyphName,
MissingStartfontField,
MissingFontField,
MissingSizeField,
MissingFontboundingboxField,
MissingCharsField,
MissingStartcharField,
MissingEncodingField,
MissingBbxField,
BbxTooBig,
CorruptedFontHeader,
CorruptedFontGlyphs,
};
pub fn intToError(err: c_int) Error!void {
return switch (err) {
c.FT_Err_Ok => {},
c.FT_Err_Cannot_Open_Resource => Error.CannotOpenResource,
c.FT_Err_Unknown_File_Format => Error.UnknownFileFormat,
c.FT_Err_Invalid_File_Format => Error.InvalidFileFormat,
c.FT_Err_Invalid_Version => Error.InvalidVersion,
c.FT_Err_Lower_Module_Version => Error.LowerModuleVersion,
c.FT_Err_Invalid_Argument => Error.InvalidArgument,
c.FT_Err_Unimplemented_Feature => Error.UnimplementedFeature,
c.FT_Err_Invalid_Table => Error.InvalidTable,
c.FT_Err_Invalid_Offset => Error.InvalidOffset,
c.FT_Err_Array_Too_Large => Error.ArrayTooLarge,
c.FT_Err_Missing_Module => Error.MissingModule,
c.FT_Err_Missing_Property => Error.MissingProperty,
c.FT_Err_Invalid_Glyph_Index => Error.InvalidGlyphIndex,
c.FT_Err_Invalid_Character_Code => Error.InvalidCharacterCode,
c.FT_Err_Invalid_Glyph_Format => Error.InvalidGlyphFormat,
c.FT_Err_Cannot_Render_Glyph => Error.CannotRenderGlyph,
c.FT_Err_Invalid_Outline => Error.InvalidOutline,
c.FT_Err_Invalid_Composite => Error.InvalidComposite,
c.FT_Err_Too_Many_Hints => Error.TooManyHints,
c.FT_Err_Invalid_Pixel_Size => Error.InvalidPixelSize,
c.FT_Err_Invalid_Handle => Error.InvalidHandle,
c.FT_Err_Invalid_Library_Handle => Error.InvalidLibraryHandle,
c.FT_Err_Invalid_Driver_Handle => Error.InvalidDriverHandle,
c.FT_Err_Invalid_Face_Handle => Error.InvalidFaceHandle,
c.FT_Err_Invalid_Size_Handle => Error.InvalidSizeHandle,
c.FT_Err_Invalid_Slot_Handle => Error.InvalidSlotHandle,
c.FT_Err_Invalid_CharMap_Handle => Error.InvalidCharMapHandle,
c.FT_Err_Invalid_Cache_Handle => Error.InvalidCacheHandle,
c.FT_Err_Invalid_Stream_Handle => Error.InvalidStreamHandle,
c.FT_Err_Too_Many_Drivers => Error.TooManyDrivers,
c.FT_Err_Too_Many_Extensions => Error.TooManyExtensions,
c.FT_Err_Out_Of_Memory => Error.OutOfMemory,
c.FT_Err_Unlisted_Object => Error.UnlistedObject,
c.FT_Err_Cannot_Open_Stream => Error.CannotOpenStream,
c.FT_Err_Invalid_Stream_Seek => Error.InvalidStreamSeek,
c.FT_Err_Invalid_Stream_Skip => Error.InvalidStreamSkip,
c.FT_Err_Invalid_Stream_Read => Error.InvalidStreamRead,
c.FT_Err_Invalid_Stream_Operation => Error.InvalidStreamOperation,
c.FT_Err_Invalid_Frame_Operation => Error.InvalidFrameOperation,
c.FT_Err_Nested_Frame_Access => Error.NestedFrameAccess,
c.FT_Err_Invalid_Frame_Read => Error.InvalidFrameRead,
c.FT_Err_Raster_Uninitialized => Error.RasterUninitialized,
c.FT_Err_Raster_Corrupted => Error.RasterCorrupted,
c.FT_Err_Raster_Overflow => Error.RasterOverflow,
c.FT_Err_Raster_Negative_Height => Error.RasterNegativeHeight,
c.FT_Err_Too_Many_Caches => Error.TooManyCaches,
c.FT_Err_Invalid_Opcode => Error.InvalidOpcode,
c.FT_Err_Too_Few_Arguments => Error.TooFewArguments,
c.FT_Err_Stack_Overflow => Error.StackOverflow,
c.FT_Err_Code_Overflow => Error.CodeOverflow,
c.FT_Err_Bad_Argument => Error.BadArgument,
c.FT_Err_Divide_By_Zero => Error.DivideByZero,
c.FT_Err_Invalid_Reference => Error.InvalidReference,
c.FT_Err_Debug_OpCode => Error.DebugOpCode,
c.FT_Err_ENDF_In_Exec_Stream => Error.ENDFInExecStream,
c.FT_Err_Nested_DEFS => Error.NestedDEFS,
c.FT_Err_Invalid_CodeRange => Error.InvalidCodeRange,
c.FT_Err_Execution_Too_Long => Error.ExecutionTooLong,
c.FT_Err_Too_Many_Function_Defs => Error.TooManyFunctionDefs,
c.FT_Err_Too_Many_Instruction_Defs => Error.TooManyInstructionDefs,
c.FT_Err_Table_Missing => Error.TableMissing,
c.FT_Err_Horiz_Header_Missing => Error.HorizHeaderMissing,
c.FT_Err_Locations_Missing => Error.LocationsMissing,
c.FT_Err_Name_Table_Missing => Error.NameTableMissing,
c.FT_Err_CMap_Table_Missing => Error.CMapTableMissing,
c.FT_Err_Hmtx_Table_Missing => Error.HmtxTableMissing,
c.FT_Err_Post_Table_Missing => Error.PostTableMissing,
c.FT_Err_Invalid_Horiz_Metrics => Error.InvalidHorizMetrics,
c.FT_Err_Invalid_CharMap_Format => Error.InvalidCharMapFormat,
c.FT_Err_Invalid_PPem => Error.InvalidPPem,
c.FT_Err_Invalid_Vert_Metrics => Error.InvalidVertMetrics,
c.FT_Err_Could_Not_Find_Context => Error.CouldNotFindContext,
c.FT_Err_Invalid_Post_Table_Format => Error.InvalidPostTableFormat,
c.FT_Err_Invalid_Post_Table => Error.InvalidPostTable,
c.FT_Err_Syntax_Error => Error.Syntax,
c.FT_Err_Stack_Underflow => Error.StackUnderflow,
c.FT_Err_Ignore => Error.Ignore,
c.FT_Err_No_Unicode_Glyph_Name => Error.NoUnicodeGlyphName,
c.FT_Err_Missing_Startfont_Field => Error.MissingStartfontField,
c.FT_Err_Missing_Font_Field => Error.MissingFontField,
c.FT_Err_Missing_Size_Field => Error.MissingSizeField,
c.FT_Err_Missing_Fontboundingbox_Field => Error.MissingFontboundingboxField,
c.FT_Err_Missing_Chars_Field => Error.MissingCharsField,
c.FT_Err_Missing_Startchar_Field => Error.MissingStartcharField,
c.FT_Err_Missing_Encoding_Field => Error.MissingEncodingField,
c.FT_Err_Missing_Bbx_Field => Error.MissingBbxField,
c.FT_Err_Bbx_Too_Big => Error.BbxTooBig,
c.FT_Err_Corrupted_Font_Header => Error.CorruptedFontHeader,
c.FT_Err_Corrupted_Font_Glyphs => Error.CorruptedFontGlyphs,
else => unreachable,
};
}
pub fn errorToInt(err: Error) c_int {
return switch (err) {
Error.CannotOpenResource => c.FT_Err_Cannot_Open_Resource,
Error.UnknownFileFormat => c.FT_Err_Unknown_File_Format,
Error.InvalidFileFormat => c.FT_Err_Invalid_File_Format,
Error.InvalidVersion => c.FT_Err_Invalid_Version,
Error.LowerModuleVersion => c.FT_Err_Lower_Module_Version,
Error.InvalidArgument => c.FT_Err_Invalid_Argument,
Error.UnimplementedFeature => c.FT_Err_Unimplemented_Feature,
Error.InvalidTable => c.FT_Err_Invalid_Table,
Error.InvalidOffset => c.FT_Err_Invalid_Offset,
Error.ArrayTooLarge => c.FT_Err_Array_Too_Large,
Error.MissingModule => c.FT_Err_Missing_Module,
Error.MissingProperty => c.FT_Err_Missing_Property,
Error.InvalidGlyphIndex => c.FT_Err_Invalid_Glyph_Index,
Error.InvalidCharacterCode => c.FT_Err_Invalid_Character_Code,
Error.InvalidGlyphFormat => c.FT_Err_Invalid_Glyph_Format,
Error.CannotRenderGlyph => c.FT_Err_Cannot_Render_Glyph,
Error.InvalidOutline => c.FT_Err_Invalid_Outline,
Error.InvalidComposite => c.FT_Err_Invalid_Composite,
Error.TooManyHints => c.FT_Err_Too_Many_Hints,
Error.InvalidPixelSize => c.FT_Err_Invalid_Pixel_Size,
Error.InvalidHandle => c.FT_Err_Invalid_Handle,
Error.InvalidLibraryHandle => c.FT_Err_Invalid_Library_Handle,
Error.InvalidDriverHandle => c.FT_Err_Invalid_Driver_Handle,
Error.InvalidFaceHandle => c.FT_Err_Invalid_Face_Handle,
Error.InvalidSizeHandle => c.FT_Err_Invalid_Size_Handle,
Error.InvalidSlotHandle => c.FT_Err_Invalid_Slot_Handle,
Error.InvalidCharMapHandle => c.FT_Err_Invalid_CharMap_Handle,
Error.InvalidCacheHandle => c.FT_Err_Invalid_Cache_Handle,
Error.InvalidStreamHandle => c.FT_Err_Invalid_Stream_Handle,
Error.TooManyDrivers => c.FT_Err_Too_Many_Drivers,
Error.TooManyExtensions => c.FT_Err_Too_Many_Extensions,
Error.OutOfMemory => c.FT_Err_Out_Of_Memory,
Error.UnlistedObject => c.FT_Err_Unlisted_Object,
Error.CannotOpenStream => c.FT_Err_Cannot_Open_Stream,
Error.InvalidStreamSeek => c.FT_Err_Invalid_Stream_Seek,
Error.InvalidStreamSkip => c.FT_Err_Invalid_Stream_Skip,
Error.InvalidStreamRead => c.FT_Err_Invalid_Stream_Read,
Error.InvalidStreamOperation => c.FT_Err_Invalid_Stream_Operation,
Error.InvalidFrameOperation => c.FT_Err_Invalid_Frame_Operation,
Error.NestedFrameAccess => c.FT_Err_Nested_Frame_Access,
Error.InvalidFrameRead => c.FT_Err_Invalid_Frame_Read,
Error.RasterUninitialized => c.FT_Err_Raster_Uninitialized,
Error.RasterCorrupted => c.FT_Err_Raster_Corrupted,
Error.RasterOverflow => c.FT_Err_Raster_Overflow,
Error.RasterNegativeHeight => c.FT_Err_Raster_Negative_Height,
Error.TooManyCaches => c.FT_Err_Too_Many_Caches,
Error.InvalidOpcode => c.FT_Err_Invalid_Opcode,
Error.TooFewArguments => c.FT_Err_Too_Few_Arguments,
Error.StackOverflow => c.FT_Err_Stack_Overflow,
Error.CodeOverflow => c.FT_Err_Code_Overflow,
Error.BadArgument => c.FT_Err_Bad_Argument,
Error.DivideByZero => c.FT_Err_Divide_By_Zero,
Error.InvalidReference => c.FT_Err_Invalid_Reference,
Error.DebugOpCode => c.FT_Err_Debug_OpCode,
Error.ENDFInExecStream => c.FT_Err_ENDF_In_Exec_Stream,
Error.NestedDEFS => c.FT_Err_Nested_DEFS,
Error.InvalidCodeRange => c.FT_Err_Invalid_CodeRange,
Error.ExecutionTooLong => c.FT_Err_Execution_Too_Long,
Error.TooManyFunctionDefs => c.FT_Err_Too_Many_Function_Defs,
Error.TooManyInstructionDefs => c.FT_Err_Too_Many_Instruction_Defs,
Error.TableMissing => c.FT_Err_Table_Missing,
Error.HorizHeaderMissing => c.FT_Err_Horiz_Header_Missing,
Error.LocationsMissing => c.FT_Err_Locations_Missing,
Error.NameTableMissing => c.FT_Err_Name_Table_Missing,
Error.CMapTableMissing => c.FT_Err_CMap_Table_Missing,
Error.HmtxTableMissing => c.FT_Err_Hmtx_Table_Missing,
Error.PostTableMissing => c.FT_Err_Post_Table_Missing,
Error.InvalidHorizMetrics => c.FT_Err_Invalid_Horiz_Metrics,
Error.InvalidCharMapFormat => c.FT_Err_Invalid_CharMap_Format,
Error.InvalidPPem => c.FT_Err_Invalid_PPem,
Error.InvalidVertMetrics => c.FT_Err_Invalid_Vert_Metrics,
Error.CouldNotFindContext => c.FT_Err_Could_Not_Find_Context,
Error.InvalidPostTableFormat => c.FT_Err_Invalid_Post_Table_Format,
Error.InvalidPostTable => c.FT_Err_Invalid_Post_Table,
Error.Syntax => c.FT_Err_Syntax_Error,
Error.StackUnderflow => c.FT_Err_Stack_Underflow,
Error.Ignore => c.FT_Err_Ignore,
Error.NoUnicodeGlyphName => c.FT_Err_No_Unicode_Glyph_Name,
Error.MissingStartfontField => c.FT_Err_Missing_Startfont_Field,
Error.MissingFontField => c.FT_Err_Missing_Font_Field,
Error.MissingSizeField => c.FT_Err_Missing_Size_Field,
Error.MissingFontboundingboxField => c.FT_Err_Missing_Fontboundingbox_Field,
Error.MissingCharsField => c.FT_Err_Missing_Chars_Field,
Error.MissingStartcharField => c.FT_Err_Missing_Startchar_Field,
Error.MissingEncodingField => c.FT_Err_Missing_Encoding_Field,
Error.MissingBbxField => c.FT_Err_Missing_Bbx_Field,
Error.BbxTooBig => c.FT_Err_Bbx_Too_Big,
Error.CorruptedFontHeader => c.FT_Err_Corrupted_Font_Header,
Error.CorruptedFontGlyphs => c.FT_Err_Corrupted_Font_Glyphs,
};
}
test "error convertion" {
const expectError = @import("std").testing.expectError;
try intToError(c.FT_Err_Ok);
try expectError(Error.OutOfMemory, intToError(c.FT_Err_Out_Of_Memory));
} | freetype/src/error.zig |
const std = @import("std");
const image_info = @import("image_info.zig");
const dbg = std.log.debug;
pub const magic = 0x2badb002;
/// Multiboot specification: https://www.gnu.org/software/grub/manual/multiboot/multiboot.html
pub const MultibootInfo = packed struct {
pub const MemoryMapEntry = packed struct {
pub const Type = extern enum(u32) {
available_ram = 1,
available_ram_acpi_information = 3,
hibernation_ram = 4,
defective_ram = 5,
_, // Reserved
};
entry_size: u32, // WARNING: _entry_size does not include size of _entry_size itself!
area_base_address: u64,
area_length: u64,
area_type: Type,
fn is_in_kernel_image_range(raw_address: u32) bool {
return image_info.start_virtual_address() <= raw_address and raw_address < image_info.end_virtual_address();
}
pub fn access_if_available(self: *const MemoryMapEntry, comptime T: type) ?[]T {
if (self.area_type != .available_ram) {
return null;
}
if (self.area_base_address >= 0xFFFFFFFF) {
// Outside of 32-bit address range!
return null;
}
const raw_start_address = @intCast(u32, self.area_base_address);
// Bootloader will happily report RAM used by the kernel itself as if it was entirely free memory.
// So we must check for this and limit the memory range as needed.
const start_address = if(is_in_kernel_image_range(raw_start_address))
image_info.end_virtual_address()
else
raw_start_address;
const raw_end_address = @intCast(u32, std.math.min(0xFFFFFFFF, raw_start_address + self.area_length));
const end_address = if(is_in_kernel_image_range(raw_end_address))
image_info.start_virtual_address() - 1
else
raw_end_address;
return @intToPtr([*]allowzero T, @intCast(u32, start_address & 0xFFFFFFFF))[0..(@intCast(usize, end_address - start_address))];
}
};
pub const MemoryMapEntryIterator = struct {
remaining_items: [*]const MemoryMapEntry,
remaining_length: u32,
pub fn next(self: *MemoryMapEntryIterator) ?*const MemoryMapEntry {
if (self.remaining_length == 0) {
return null;
}
const result = &self.remaining_items[0];
const entry_total_size = result.entry_size + 4;
self.remaining_length -= entry_total_size;
self.remaining_items = @intToPtr([*]const MemoryMapEntry, @ptrToInt(self.remaining_items) + entry_total_size);
return result;
}
};
// flags
unused_0: u6, // Unused: mem_*, boot_device, cmdline, mods_*(Initramfs) and syms
_is_memory_map_present: bool,
unused_1: u25, // Unused: drives_*, config_table, boot_loader_name, apm_table, vbe_*, framebuffer_*, and remaining bits
// mem_*, boot_device, cmdline, mods_*, syms
unused_2: [10]u32,
// mmap_length
memory_map_length: u32,
// mmap_addr
memory_map_address: [*]const MemoryMapEntry,
// drives_*, config_table, boot_loader_name, apm_table, vbe_*, framebuffer_*
unused_3: [18]u32,
pub fn memory_map(self: *const MultibootInfo) MemoryMapEntryIterator {
return .{ .remaining_items = self.memory_map_address, .remaining_length = self.memory_map_length };
}
}; | kernel/multiboot.zig |
const std = @import("std");
const input = @import("input.zig");
pub fn run(stdout: anytype) anyerror!void {
var input_ = try input.readFile("inputs/day17");
defer input_.deinit();
var part1_result: i64 = undefined;
var part2_result: usize = undefined;
try solve(&input_, &part1_result, &part2_result);
try stdout.print("17a: {}\n", .{ part1_result });
std.debug.assert(part1_result == 10011);
try stdout.print("17b: {}\n", .{ part2_result });
std.debug.assert(part2_result == 2994);
}
fn solve(input_: anytype, part1_result: *i64, part2_result: *usize) !void {
var min: Vector = undefined;
var max: Vector = undefined;
try parseInput(input_, &min, &max);
part1_result.* = 0;
part2_result.* = 0;
var initial_vel_x: i64 = max.x;
while (initial_vel_x > 0) : (initial_vel_x -= 1) {
var initial_vel_y: i64 = try std.math.absInt(min.y);
while (initial_vel_y >= min.y) : (initial_vel_y -= 1) {
var pos = Vector { .x = 0, .y = 0 };
var vel = Vector { .x = initial_vel_x, .y = initial_vel_y };
var y_highest: i64 = pos.y;
while (true) {
switch (step(&pos, &vel, min, max)) {
.traveling => y_highest = std.math.max(y_highest, pos.y),
.hit => {
part1_result.* = std.math.max(part1_result.*, y_highest);
part2_result.* += 1;
break;
},
.missed => break,
}
}
}
}
}
const Vector = struct {
x: i64,
y: i64,
};
fn parseInput(input_: anytype, min: *Vector, max: *Vector) !void {
const line = (try input_.next()) orelse return error.InvalidInput;
if (!std.mem.startsWith(u8, line, "target area: ")) {
return error.InvalidInput;
}
var line_parts = std.mem.split(u8, line[("target area: ".len)..], ", ");
const x_s = line_parts.next() orelse return error.InvalidInput;
if (!std.mem.startsWith(u8, x_s, "x=")) {
return error.InvalidInput;
}
var x_start: i64 = undefined;
var x_end: i64 = undefined;
try parseRange(x_s[("x=".len)..], &x_start, &x_end);
min.x = std.math.min(x_start, x_end);
max.x = std.math.max(x_start, x_end);
const y_s = line_parts.next() orelse return error.InvalidInput;
if (!std.mem.startsWith(u8, y_s, "y=")) {
return error.InvalidInput;
}
var y_start: i64 = undefined;
var y_end: i64 = undefined;
try parseRange(y_s[("y=".len)..], &y_start, &y_end);
min.y = std.math.min(y_start, y_end);
max.y = std.math.max(y_start, y_end);
}
fn parseRange(s: []const u8, start: *i64, end: *i64) !void {
var s_parts = std.mem.split(u8, s, "..");
const start_s = s_parts.next() orelse return error.InvalidInput;
start.* = try std.fmt.parseInt(i64, start_s, 10);
const end_s = s_parts.next() orelse return error.InvalidInput;
end.* = try std.fmt.parseInt(i64, end_s, 10);
}
const StepResult = enum {
traveling,
hit,
missed,
};
fn step(pos: *Vector, vel: *Vector, min: Vector, max: Vector) StepResult {
pos.x += vel.x;
pos.y += vel.y;
if (vel.x > 0) {
vel.x -= 1;
}
else if (vel.x < 0) {
vel.x += 1;
}
vel.y -= 1;
if (pos.x >= min.x and pos.x <= max.x and pos.y >= min.y and pos.y <= max.y) {
return .hit;
}
if (pos.x > max.x or pos.y < min.y) {
return .missed;
}
return .traveling;
}
test "day 17 example 1" {
const input_ =
\\target area: x=20..30, y=-10..-5
;
var part1_result: i64 = undefined;
var part2_result: usize = undefined;
try solve(&input.readString(input_), &part1_result, &part2_result);
try std.testing.expectEqual(@as(i64, 45), part1_result);
try std.testing.expectEqual(@as(usize, 112), part2_result);
} | src/day17.zig |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.