Unnamed: 0
int64
0
0
repo_id
stringlengths
5
186
file_path
stringlengths
15
223
content
stringlengths
1
32.8M
0
repos
repos/zigmkv/README.md
# zigmkv A work in progress Matroska/webm (mkv) parser in Zig. For now it contains elements database, can decode mkv files to element tree, but it does not yet handle parse frame content and calculate proper timecodes. Main idea was to evaluate Zig as a general purpose programming language. Tested with zig version 0.8.0. ``` $ zig build $ zig-out/bin/zigmkv l2dump < some_file.mkv open 0x1a45dfa3 (EBML) type=Type.master size=35 open 0x4286 (EBMLVersion) type=Type.uinteger size=1 number 1 close 0x4286 (EBMLVersion) type=Type.uinteger open 0x42f7 (EBMLReadVersion) type=Type.uinteger size=1 number 1 close 0x42f7 (EBMLReadVersion) type=Type.uinteger open 0x42f2 (EBMLMaxIDLength) type=Type.uinteger size=1 number 4 close 0x42f2 (EBMLMaxIDLength) type=Type.uinteger ... ```
0
repos
repos/zigmkv/build.zig
const Builder = @import("std").build.Builder; pub fn build(b: *Builder) void { const mode = b.standardReleaseOptions(); const exe = b.addExecutable("zigmkv", "src/main.zig"); exe.setBuildMode(mode); exe.install(); const run_cmd = exe.run(); run_cmd.step.dependOn(b.getInstallStep()); const run_step = b.step("run", "Run the app"); run_step.dependOn(&run_cmd.step); }
0
repos/zigmkv
repos/zigmkv/src/tool_l2dump.zig
const std = @import("std"); const warn = std.debug.print; const mkv = @import("mkv.zig"); const L2Dump = struct { indent: usize, f: std.fs.File, const Self = @This(); fn print(self: *Self, comptime format: []const u8, args: anytype) anyerror!void { try self.f.writer().print(format, args); } fn handler(self : *Self, ev: mkv.L2Parser.Event) anyerror!void { if (ev == .unknown_or_void_chunk) { return; } var ugly_counter = self.indent; // Zig should have better syntax for repeating while(ugly_counter>0):(ugly_counter-=1) { try self.print(" ", .{}); } switch(ev) { .element_begins => |x| { try self.print("open 0x{x} ({s}) type={} size={}\n", .{x.id.id, x.id.get_name(), x.typ, x.size}); self.indent += 1; }, .number => |x|{ try self.print("number {}\n", .{x}); }, .signed_number => |x|{ try self.print("signed_number {}\n", .{x}); }, .binary_chunk => |x|{ try self.print("binary chunk len={}\n", .{x.len}); }, .unknown_or_void_chunk => unreachable, .string_chunk => |x|{ try self.print("string {s}\n", .{x}); }, .utf8_chunk => |x|{ try self.print("utf8 {s}\n", .{x}); }, .float => |x| { try self.print("float {}\n", .{x}); }, .element_ends => |x| { try self.print("close 0x{x} ({s}) type={}\n", .{x.id.id, x.id.get_name(), x.typ}); self.indent -= 1; }, } } }; var pool : [4096]u8 = undefined; pub fn tool(argv:[][]const u8) anyerror!void { if (argv.len > 0) { warn("Usage: zigmkv l2dump < input_file.mkv\n", .{}); std.process.exit(1); } var si = std.io.getStdIn(); var buf : [256]u8 = undefined; var m = mkv.L2Parser.new(); var l2dump = L2Dump { .indent = 0, .f = std.io.getStdOut(), }; while(true) { var ret = si.read(buf[0..]) catch |e| { if (e == error.WouldBlock) { //std.time.sleep(50*1000*1000); // fails on WASI continue; } return e; }; if (ret == 0) break; const b = buf[0..ret]; try m.push_bytes(b, &l2dump, L2Dump.handler); } try l2dump.print("OK\n", .{}); }
0
repos/zigmkv
repos/zigmkv/src/main.zig
const std = @import("std"); const warn = std.debug.print; var pool : [4096]u8 = undefined; pub fn main() anyerror!void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const alloc = gpa.allocator(); const argv = try std.process.argsAlloc(alloc); defer std.process.argsFree(alloc, argv); if (argv.len<2) { warn("Usage: zigmkv {{help|<subtool_name>}} ...\n", .{}); std.process.exit(1); } if (std.mem.eql(u8, argv[1], "help")) { warn("Tools:\n", .{}); warn(" zigmkv l2dump\n" , .{}); warn("Use --help option after tool name for further help.\n", .{}); } else if (std.mem.eql(u8, argv[1], "l2dump")) { try @import("tool_l2dump.zig").tool(argv[2..]); } else { warn("Unknown tool name `{s}`\n", .{argv[1]}); std.process.exit(1); } }
0
repos/zigmkv
repos/zigmkv/src/mkv.zig
/// Parser of Block / SimpleBlock content pub const BufferParser = @import("mkv/bufparse.zig"); /// Mid-level Matroska parser. Returns event stream for tag opening, closure and interpreted data. /// Does not bother with extracting frames from SimpleBlocks. pub const L2Parser = @import("mkv/l2.zig"); /// Wrapper for Matroska element ID. Allows getting type and name from ID. /// Contains Matroska EBML elements database inside. pub const id = @import("mkv/id.zig"); /// Lowest-level EBML parser. Contains no ID database. /// Handler decides whether to interpret a thing as a master element pub const L1Parser = @import("mkv/l1.zig"); /// Functions for working with EBML's VLN (Variable Length Numbers) pub const vln = @import("mkv/vln.zig");
0
repos/zigmkv/src
repos/zigmkv/src/mkv/bufparse.zig
/// Maximum number of laced frames const MAXLACE = 64; const std = @import("std"); const mkv = @import("../mkv.zig"); pub const Flags = struct { keyframe: bool, invisible: bool, discardable: bool, }; pub const Event = union(enum) { track_number: u64, /// Relative to recent `Timestamp` element content relative_timecode: i16, flags : Flags, frame_start, frame_chunk: []const u8, frame_end, buffer_end, }; const LacingMode = enum { none, xiph, ebml, fixed, }; const Lace = [MAXLACE]u32; const StreamingFrames = struct { lace: Lace, current_frame: u8, position_inside_current_frame: u32, }; const State = union(enum) { reading_track_number: mkv.vln.EbmlVlnReader, reading_timecode, reading_flags, reading_lacing, streaming_frames : StreamingFrames, }; const Self = @This(); state: State, pub fn new() Self { return Self { .state = State { .reading_track_number = mkv.vln.EbmlVlnReader.new(), }, }; } test "basic" { const q = Self.new(); const e = Event { .track_number = 3 }; _ = e; _ = q; }
0
repos/zigmkv/src
repos/zigmkv/src/mkv/database.zig
// This file is codegenerated. Run `./database.py --help` for info. const mkv = @import("../mkv.zig"); const IdInfo = mkv.id.IdInfo; const Id = mkv.id.Id; pub const database = [_]IdInfo { IdInfo { .id=0x1A45DFA3, .typ=.master , .name="EBML" ,.importance=.important }, IdInfo { .id=0x4286 , .typ=.uinteger, .name="EBMLVersion" ,.importance=.default }, IdInfo { .id=0x42F7 , .typ=.uinteger, .name="EBMLReadVersion" ,.importance=.important }, IdInfo { .id=0x42F2 , .typ=.uinteger, .name="EBMLMaxIDLength" ,.importance=.default }, IdInfo { .id=0x42F3 , .typ=.uinteger, .name="EBMLMaxSizeLength" ,.importance=.default }, IdInfo { .id=0x4282 , .typ=.string , .name="DocType" ,.importance=.important }, IdInfo { .id=0x4287 , .typ=.uinteger, .name="DocTypeVersion" ,.importance=.default }, IdInfo { .id=0x4285 , .typ=.uinteger, .name="DocTypeReadVersion" ,.importance=.important }, IdInfo { .id=0x4281 , .typ=.master , .name="DocTypeExtension" ,.importance=.default }, IdInfo { .id=0x4283 , .typ=.string , .name="DocTypeExtensionName" ,.importance=.default }, IdInfo { .id=0x4284 , .typ=.uinteger, .name="DocTypeExtensionVersion" ,.importance=.default }, IdInfo { .id=0xEC , .typ=.binary , .name="Void" ,.importance=.default }, IdInfo { .id=0xBF , .typ=.binary , .name="CRC32" ,.importance=.default }, IdInfo { .id=0x18538067, .typ=.master , .name="Segment" ,.importance=.important }, IdInfo { .id=0x114D9B74, .typ=.master , .name="SeekHead" ,.importance=.default }, IdInfo { .id=0x4DBB , .typ=.master , .name="Seek" ,.importance=.default }, IdInfo { .id=0x53AB , .typ=.binary , .name="SeekID" ,.importance=.default }, IdInfo { .id=0x53AC , .typ=.uinteger, .name="SeekPosition" ,.importance=.default }, IdInfo { .id=0x1549A966, .typ=.master , .name="Info" ,.importance=.important }, IdInfo { .id=0x73A4 , .typ=.binary , .name="SegmentUUID" ,.importance=.default }, IdInfo { .id=0x7384 , .typ=.utf8 , .name="SegmentFilename" ,.importance=.default }, IdInfo { .id=0x3CB923 , .typ=.binary , .name="PrevUUID" ,.importance=.default }, IdInfo { .id=0x3C83AB , .typ=.utf8 , .name="PrevFilename" ,.importance=.default }, IdInfo { .id=0x3EB923 , .typ=.binary , .name="NextUUID" ,.importance=.default }, IdInfo { .id=0x3E83BB , .typ=.utf8 , .name="NextFilename" ,.importance=.default }, IdInfo { .id=0x4444 , .typ=.binary , .name="SegmentFamily" ,.importance=.default }, IdInfo { .id=0x6924 , .typ=.master , .name="ChapterTranslate" ,.importance=.default }, IdInfo { .id=0x69FC , .typ=.uinteger, .name="ChapterTranslateEditionUID" ,.importance=.default }, IdInfo { .id=0x69BF , .typ=.uinteger, .name="ChapterTranslateCodec" ,.importance=.default }, IdInfo { .id=0x69A5 , .typ=.binary , .name="ChapterTranslateID" ,.importance=.default }, IdInfo { .id=0x2AD7B1 , .typ=.uinteger, .name="TimestampScale" ,.importance=.important }, IdInfo { .id=0x4489 , .typ=.float , .name="Duration" ,.importance=.default }, IdInfo { .id=0x4461 , .typ=.date , .name="DateUTC" ,.importance=.default }, IdInfo { .id=0x7BA9 , .typ=.utf8 , .name="Title" ,.importance=.default }, IdInfo { .id=0x4D80 , .typ=.utf8 , .name="MuxingApp" ,.importance=.default }, IdInfo { .id=0x5741 , .typ=.utf8 , .name="WritingApp" ,.importance=.default }, IdInfo { .id=0x1F43B675, .typ=.master , .name="Cluster" ,.importance=.hot }, IdInfo { .id=0xE7 , .typ=.uinteger, .name="Timestamp" ,.importance=.hot }, IdInfo { .id=0x5854 , .typ=.master , .name="SilentTracks" ,.importance=.default }, IdInfo { .id=0x58D7 , .typ=.uinteger, .name="SilentTrackNumber" ,.importance=.default }, IdInfo { .id=0xA7 , .typ=.uinteger, .name="Position" ,.importance=.default }, IdInfo { .id=0xAB , .typ=.uinteger, .name="PrevSize" ,.importance=.default }, IdInfo { .id=0xA3 , .typ=.binary , .name="SimpleBlock" ,.importance=.hot }, IdInfo { .id=0xA0 , .typ=.master , .name="BlockGroup" ,.importance=.important }, IdInfo { .id=0xA1 , .typ=.binary , .name="Block" ,.importance=.important }, IdInfo { .id=0xA2 , .typ=.binary , .name="BlockVirtual" ,.importance=.default }, IdInfo { .id=0x75A1 , .typ=.master , .name="BlockAdditions" ,.importance=.default }, IdInfo { .id=0xA6 , .typ=.master , .name="BlockMore" ,.importance=.default }, IdInfo { .id=0xEE , .typ=.uinteger, .name="BlockAddID" ,.importance=.default }, IdInfo { .id=0xA5 , .typ=.binary , .name="BlockAdditional" ,.importance=.default }, IdInfo { .id=0x9B , .typ=.uinteger, .name="BlockDuration" ,.importance=.important }, IdInfo { .id=0xFA , .typ=.uinteger, .name="ReferencePriority" ,.importance=.default }, IdInfo { .id=0xFB , .typ=.integer , .name="ReferenceBlock" ,.importance=.default }, IdInfo { .id=0xFD , .typ=.integer , .name="ReferenceVirtual" ,.importance=.default }, IdInfo { .id=0xA4 , .typ=.binary , .name="CodecState" ,.importance=.default }, IdInfo { .id=0x75A2 , .typ=.integer , .name="DiscardPadding" ,.importance=.default }, IdInfo { .id=0x8E , .typ=.master , .name="Slices" ,.importance=.default }, IdInfo { .id=0xE8 , .typ=.master , .name="TimeSlice" ,.importance=.default }, IdInfo { .id=0xCC , .typ=.uinteger, .name="LaceNumber" ,.importance=.default }, IdInfo { .id=0xCD , .typ=.uinteger, .name="FrameNumber" ,.importance=.default }, IdInfo { .id=0xCB , .typ=.uinteger, .name="BlockAdditionID" ,.importance=.default }, IdInfo { .id=0xCE , .typ=.uinteger, .name="Delay" ,.importance=.default }, IdInfo { .id=0xCF , .typ=.uinteger, .name="SliceDuration" ,.importance=.default }, IdInfo { .id=0xC8 , .typ=.master , .name="ReferenceFrame" ,.importance=.default }, IdInfo { .id=0xC9 , .typ=.uinteger, .name="ReferenceOffset" ,.importance=.default }, IdInfo { .id=0xCA , .typ=.uinteger, .name="ReferenceTimestamp" ,.importance=.default }, IdInfo { .id=0xAF , .typ=.binary , .name="EncryptedBlock" ,.importance=.default }, IdInfo { .id=0x1654AE6B, .typ=.master , .name="Tracks" ,.importance=.important }, IdInfo { .id=0xAE , .typ=.master , .name="TrackEntry" ,.importance=.important }, IdInfo { .id=0xD7 , .typ=.uinteger, .name="TrackNumber" ,.importance=.important }, IdInfo { .id=0x73C5 , .typ=.uinteger, .name="TrackUID" ,.importance=.default }, IdInfo { .id=0x83 , .typ=.uinteger, .name="TrackType" ,.importance=.important }, IdInfo { .id=0xB9 , .typ=.uinteger, .name="FlagEnabled" ,.importance=.default }, IdInfo { .id=0x88 , .typ=.uinteger, .name="FlagDefault" ,.importance=.default }, IdInfo { .id=0x55AA , .typ=.uinteger, .name="FlagForced" ,.importance=.default }, IdInfo { .id=0x55AB , .typ=.uinteger, .name="FlagHearingImpaired" ,.importance=.default }, IdInfo { .id=0x55AC , .typ=.uinteger, .name="FlagVisualImpaired" ,.importance=.default }, IdInfo { .id=0x55AD , .typ=.uinteger, .name="FlagTextDescriptions" ,.importance=.default }, IdInfo { .id=0x55AE , .typ=.uinteger, .name="FlagOriginal" ,.importance=.default }, IdInfo { .id=0x55AF , .typ=.uinteger, .name="FlagCommentary" ,.importance=.default }, IdInfo { .id=0x9C , .typ=.uinteger, .name="FlagLacing" ,.importance=.default }, IdInfo { .id=0x6DE7 , .typ=.uinteger, .name="MinCache" ,.importance=.default }, IdInfo { .id=0x6DF8 , .typ=.uinteger, .name="MaxCache" ,.importance=.default }, IdInfo { .id=0x23E383 , .typ=.uinteger, .name="DefaultDuration" ,.importance=.default }, IdInfo { .id=0x234E7A , .typ=.uinteger, .name="DefaultDecodedFieldDuration" ,.importance=.default }, IdInfo { .id=0x23314F , .typ=.float , .name="TrackTimestampScale" ,.importance=.default }, IdInfo { .id=0x537F , .typ=.integer , .name="TrackOffset" ,.importance=.default }, IdInfo { .id=0x55EE , .typ=.uinteger, .name="MaxBlockAdditionID" ,.importance=.default }, IdInfo { .id=0x41E4 , .typ=.master , .name="BlockAdditionMapping" ,.importance=.default }, IdInfo { .id=0x41F0 , .typ=.uinteger, .name="BlockAddIDValue" ,.importance=.default }, IdInfo { .id=0x41A4 , .typ=.string , .name="BlockAddIDName" ,.importance=.default }, IdInfo { .id=0x41E7 , .typ=.uinteger, .name="BlockAddIDType" ,.importance=.default }, IdInfo { .id=0x41ED , .typ=.binary , .name="BlockAddIDExtraData" ,.importance=.default }, IdInfo { .id=0x536E , .typ=.utf8 , .name="Name" ,.importance=.default }, IdInfo { .id=0x22B59C , .typ=.string , .name="Language" ,.importance=.default }, IdInfo { .id=0x22B59D , .typ=.string , .name="LanguageBCP47" ,.importance=.default }, IdInfo { .id=0x86 , .typ=.string , .name="CodecID" ,.importance=.important }, IdInfo { .id=0x63A2 , .typ=.binary , .name="CodecPrivate" ,.importance=.important }, IdInfo { .id=0x258688 , .typ=.utf8 , .name="CodecName" ,.importance=.default }, IdInfo { .id=0x7446 , .typ=.uinteger, .name="AttachmentLink" ,.importance=.default }, IdInfo { .id=0x3A9697 , .typ=.utf8 , .name="CodecSettings" ,.importance=.default }, IdInfo { .id=0x3B4040 , .typ=.string , .name="CodecInfoURL" ,.importance=.default }, IdInfo { .id=0x26B240 , .typ=.string , .name="CodecDownloadURL" ,.importance=.default }, IdInfo { .id=0xAA , .typ=.uinteger, .name="CodecDecodeAll" ,.importance=.default }, IdInfo { .id=0x6FAB , .typ=.uinteger, .name="TrackOverlay" ,.importance=.default }, IdInfo { .id=0x56AA , .typ=.uinteger, .name="CodecDelay" ,.importance=.default }, IdInfo { .id=0x56BB , .typ=.uinteger, .name="SeekPreRoll" ,.importance=.default }, IdInfo { .id=0x6624 , .typ=.master , .name="TrackTranslate" ,.importance=.default }, IdInfo { .id=0x66FC , .typ=.uinteger, .name="TrackTranslateEditionUID" ,.importance=.default }, IdInfo { .id=0x66BF , .typ=.uinteger, .name="TrackTranslateCodec" ,.importance=.default }, IdInfo { .id=0x66A5 , .typ=.binary , .name="TrackTranslateTrackID" ,.importance=.default }, IdInfo { .id=0xE0 , .typ=.master , .name="Video" ,.importance=.important }, IdInfo { .id=0x9A , .typ=.uinteger, .name="FlagInterlaced" ,.importance=.default }, IdInfo { .id=0x9D , .typ=.uinteger, .name="FieldOrder" ,.importance=.default }, IdInfo { .id=0x53B8 , .typ=.uinteger, .name="StereoMode" ,.importance=.default }, IdInfo { .id=0x53C0 , .typ=.uinteger, .name="AlphaMode" ,.importance=.default }, IdInfo { .id=0x53B9 , .typ=.uinteger, .name="OldStereoMode" ,.importance=.default }, IdInfo { .id=0xB0 , .typ=.uinteger, .name="PixelWidth" ,.importance=.important }, IdInfo { .id=0xBA , .typ=.uinteger, .name="PixelHeight" ,.importance=.important }, IdInfo { .id=0x54AA , .typ=.uinteger, .name="PixelCropBottom" ,.importance=.default }, IdInfo { .id=0x54BB , .typ=.uinteger, .name="PixelCropTop" ,.importance=.default }, IdInfo { .id=0x54CC , .typ=.uinteger, .name="PixelCropLeft" ,.importance=.default }, IdInfo { .id=0x54DD , .typ=.uinteger, .name="PixelCropRight" ,.importance=.default }, IdInfo { .id=0x54B0 , .typ=.uinteger, .name="DisplayWidth" ,.importance=.default }, IdInfo { .id=0x54BA , .typ=.uinteger, .name="DisplayHeight" ,.importance=.default }, IdInfo { .id=0x54B2 , .typ=.uinteger, .name="DisplayUnit" ,.importance=.default }, IdInfo { .id=0x54B3 , .typ=.uinteger, .name="AspectRatioType" ,.importance=.default }, IdInfo { .id=0x2EB524 , .typ=.binary , .name="UncompressedFourCC" ,.importance=.default }, IdInfo { .id=0x2FB523 , .typ=.float , .name="GammaValue" ,.importance=.default }, IdInfo { .id=0x2383E3 , .typ=.float , .name="FrameRate" ,.importance=.default }, IdInfo { .id=0x55B0 , .typ=.master , .name="Colour" ,.importance=.default }, IdInfo { .id=0x55B1 , .typ=.uinteger, .name="MatrixCoefficients" ,.importance=.default }, IdInfo { .id=0x55B2 , .typ=.uinteger, .name="BitsPerChannel" ,.importance=.default }, IdInfo { .id=0x55B3 , .typ=.uinteger, .name="ChromaSubsamplingHorz" ,.importance=.default }, IdInfo { .id=0x55B4 , .typ=.uinteger, .name="ChromaSubsamplingVert" ,.importance=.default }, IdInfo { .id=0x55B5 , .typ=.uinteger, .name="CbSubsamplingHorz" ,.importance=.default }, IdInfo { .id=0x55B6 , .typ=.uinteger, .name="CbSubsamplingVert" ,.importance=.default }, IdInfo { .id=0x55B7 , .typ=.uinteger, .name="ChromaSitingHorz" ,.importance=.default }, IdInfo { .id=0x55B8 , .typ=.uinteger, .name="ChromaSitingVert" ,.importance=.default }, IdInfo { .id=0x55B9 , .typ=.uinteger, .name="Range" ,.importance=.default }, IdInfo { .id=0x55BA , .typ=.uinteger, .name="TransferCharacteristics" ,.importance=.default }, IdInfo { .id=0x55BB , .typ=.uinteger, .name="Primaries" ,.importance=.default }, IdInfo { .id=0x55BC , .typ=.uinteger, .name="MaxCLL" ,.importance=.default }, IdInfo { .id=0x55BD , .typ=.uinteger, .name="MaxFALL" ,.importance=.default }, IdInfo { .id=0x55D0 , .typ=.master , .name="MasteringMetadata" ,.importance=.default }, IdInfo { .id=0x55D1 , .typ=.float , .name="PrimaryRChromaticityX" ,.importance=.default }, IdInfo { .id=0x55D2 , .typ=.float , .name="PrimaryRChromaticityY" ,.importance=.default }, IdInfo { .id=0x55D3 , .typ=.float , .name="PrimaryGChromaticityX" ,.importance=.default }, IdInfo { .id=0x55D4 , .typ=.float , .name="PrimaryGChromaticityY" ,.importance=.default }, IdInfo { .id=0x55D5 , .typ=.float , .name="PrimaryBChromaticityX" ,.importance=.default }, IdInfo { .id=0x55D6 , .typ=.float , .name="PrimaryBChromaticityY" ,.importance=.default }, IdInfo { .id=0x55D7 , .typ=.float , .name="WhitePointChromaticityX" ,.importance=.default }, IdInfo { .id=0x55D8 , .typ=.float , .name="WhitePointChromaticityY" ,.importance=.default }, IdInfo { .id=0x55D9 , .typ=.float , .name="LuminanceMax" ,.importance=.default }, IdInfo { .id=0x55DA , .typ=.float , .name="LuminanceMin" ,.importance=.default }, IdInfo { .id=0x7670 , .typ=.master , .name="Projection" ,.importance=.default }, IdInfo { .id=0x7671 , .typ=.uinteger, .name="ProjectionType" ,.importance=.default }, IdInfo { .id=0x7672 , .typ=.binary , .name="ProjectionPrivate" ,.importance=.default }, IdInfo { .id=0x7673 , .typ=.float , .name="ProjectionPoseYaw" ,.importance=.default }, IdInfo { .id=0x7674 , .typ=.float , .name="ProjectionPosePitch" ,.importance=.default }, IdInfo { .id=0x7675 , .typ=.float , .name="ProjectionPoseRoll" ,.importance=.default }, IdInfo { .id=0xE1 , .typ=.master , .name="Audio" ,.importance=.important }, IdInfo { .id=0xB5 , .typ=.float , .name="SamplingFrequency" ,.importance=.important }, IdInfo { .id=0x78B5 , .typ=.float , .name="OutputSamplingFrequency" ,.importance=.default }, IdInfo { .id=0x9F , .typ=.uinteger, .name="Channels" ,.importance=.important }, IdInfo { .id=0x7D7B , .typ=.binary , .name="ChannelPositions" ,.importance=.default }, IdInfo { .id=0x6264 , .typ=.uinteger, .name="BitDepth" ,.importance=.default }, IdInfo { .id=0x92F1 , .typ=.uinteger, .name="Emphasis" ,.importance=.default }, IdInfo { .id=0xE2 , .typ=.master , .name="TrackOperation" ,.importance=.default }, IdInfo { .id=0xE3 , .typ=.master , .name="TrackCombinePlanes" ,.importance=.default }, IdInfo { .id=0xE4 , .typ=.master , .name="TrackPlane" ,.importance=.default }, IdInfo { .id=0xE5 , .typ=.uinteger, .name="TrackPlaneUID" ,.importance=.default }, IdInfo { .id=0xE6 , .typ=.uinteger, .name="TrackPlaneType" ,.importance=.default }, IdInfo { .id=0xE9 , .typ=.master , .name="TrackJoinBlocks" ,.importance=.default }, IdInfo { .id=0xED , .typ=.uinteger, .name="TrackJoinUID" ,.importance=.default }, IdInfo { .id=0xC0 , .typ=.uinteger, .name="TrickTrackUID" ,.importance=.default }, IdInfo { .id=0xC1 , .typ=.binary , .name="TrickTrackSegmentUID" ,.importance=.default }, IdInfo { .id=0xC6 , .typ=.uinteger, .name="TrickTrackFlag" ,.importance=.default }, IdInfo { .id=0xC7 , .typ=.uinteger, .name="TrickMasterTrackUID" ,.importance=.default }, IdInfo { .id=0xC4 , .typ=.binary , .name="TrickMasterTrackSegmentUID" ,.importance=.default }, IdInfo { .id=0x6D80 , .typ=.master , .name="ContentEncodings" ,.importance=.default }, IdInfo { .id=0x6240 , .typ=.master , .name="ContentEncoding" ,.importance=.default }, IdInfo { .id=0x5031 , .typ=.uinteger, .name="ContentEncodingOrder" ,.importance=.default }, IdInfo { .id=0x5032 , .typ=.uinteger, .name="ContentEncodingScope" ,.importance=.default }, IdInfo { .id=0x5033 , .typ=.uinteger, .name="ContentEncodingType" ,.importance=.default }, IdInfo { .id=0x5034 , .typ=.master , .name="ContentCompression" ,.importance=.important }, IdInfo { .id=0x4254 , .typ=.uinteger, .name="ContentCompAlgo" ,.importance=.default }, IdInfo { .id=0x4255 , .typ=.binary , .name="ContentCompSettings" ,.importance=.default }, IdInfo { .id=0x5035 , .typ=.master , .name="ContentEncryption" ,.importance=.default }, IdInfo { .id=0x47E1 , .typ=.uinteger, .name="ContentEncAlgo" ,.importance=.default }, IdInfo { .id=0x47E2 , .typ=.binary , .name="ContentEncKeyID" ,.importance=.default }, IdInfo { .id=0x47E7 , .typ=.master , .name="ContentEncAESSettings" ,.importance=.default }, IdInfo { .id=0x47E8 , .typ=.uinteger, .name="AESSettingsCipherMode" ,.importance=.default }, IdInfo { .id=0x47E3 , .typ=.binary , .name="ContentSignature" ,.importance=.default }, IdInfo { .id=0x47E4 , .typ=.binary , .name="ContentSigKeyID" ,.importance=.default }, IdInfo { .id=0x47E5 , .typ=.uinteger, .name="ContentSigAlgo" ,.importance=.default }, IdInfo { .id=0x47E6 , .typ=.uinteger, .name="ContentSigHashAlgo" ,.importance=.default }, IdInfo { .id=0x1C53BB6B, .typ=.master , .name="Cues" ,.importance=.default }, IdInfo { .id=0xBB , .typ=.master , .name="CuePoint" ,.importance=.default }, IdInfo { .id=0xB3 , .typ=.uinteger, .name="CueTime" ,.importance=.default }, IdInfo { .id=0xB7 , .typ=.master , .name="CueTrackPositions" ,.importance=.default }, IdInfo { .id=0xF7 , .typ=.uinteger, .name="CueTrack" ,.importance=.default }, IdInfo { .id=0xF1 , .typ=.uinteger, .name="CueClusterPosition" ,.importance=.default }, IdInfo { .id=0xF0 , .typ=.uinteger, .name="CueRelativePosition" ,.importance=.default }, IdInfo { .id=0xB2 , .typ=.uinteger, .name="CueDuration" ,.importance=.default }, IdInfo { .id=0x5378 , .typ=.uinteger, .name="CueBlockNumber" ,.importance=.default }, IdInfo { .id=0xEA , .typ=.uinteger, .name="CueCodecState" ,.importance=.default }, IdInfo { .id=0xDB , .typ=.master , .name="CueReference" ,.importance=.default }, IdInfo { .id=0x96 , .typ=.uinteger, .name="CueRefTime" ,.importance=.default }, IdInfo { .id=0x97 , .typ=.uinteger, .name="CueRefCluster" ,.importance=.default }, IdInfo { .id=0x535F , .typ=.uinteger, .name="CueRefNumber" ,.importance=.default }, IdInfo { .id=0xEB , .typ=.uinteger, .name="CueRefCodecState" ,.importance=.default }, IdInfo { .id=0x1941A469, .typ=.master , .name="Attachments" ,.importance=.default }, IdInfo { .id=0x61A7 , .typ=.master , .name="AttachedFile" ,.importance=.default }, IdInfo { .id=0x467E , .typ=.utf8 , .name="FileDescription" ,.importance=.default }, IdInfo { .id=0x466E , .typ=.utf8 , .name="FileName" ,.importance=.default }, IdInfo { .id=0x4660 , .typ=.string , .name="FileMediaType" ,.importance=.default }, IdInfo { .id=0x465C , .typ=.binary , .name="FileData" ,.importance=.default }, IdInfo { .id=0x46AE , .typ=.uinteger, .name="FileUID" ,.importance=.default }, IdInfo { .id=0x4675 , .typ=.binary , .name="FileReferral" ,.importance=.default }, IdInfo { .id=0x4661 , .typ=.uinteger, .name="FileUsedStartTime" ,.importance=.default }, IdInfo { .id=0x4662 , .typ=.uinteger, .name="FileUsedEndTime" ,.importance=.default }, IdInfo { .id=0x1043A770, .typ=.master , .name="Chapters" ,.importance=.default }, IdInfo { .id=0x45B9 , .typ=.master , .name="EditionEntry" ,.importance=.default }, IdInfo { .id=0x45BC , .typ=.uinteger, .name="EditionUID" ,.importance=.default }, IdInfo { .id=0x45BD , .typ=.uinteger, .name="EditionFlagHidden" ,.importance=.default }, IdInfo { .id=0x45DB , .typ=.uinteger, .name="EditionFlagDefault" ,.importance=.default }, IdInfo { .id=0x45DD , .typ=.uinteger, .name="EditionFlagOrdered" ,.importance=.default }, IdInfo { .id=0x4520 , .typ=.master , .name="EditionDisplay" ,.importance=.default }, IdInfo { .id=0x4521 , .typ=.utf8 , .name="EditionString" ,.importance=.default }, IdInfo { .id=0x45E4 , .typ=.string , .name="EditionLanguageIETF" ,.importance=.default }, IdInfo { .id=0xB6 , .typ=.master , .name="ChapterAtom" ,.importance=.default }, IdInfo { .id=0x73C4 , .typ=.uinteger, .name="ChapterUID" ,.importance=.default }, IdInfo { .id=0x5654 , .typ=.utf8 , .name="ChapterStringUID" ,.importance=.default }, IdInfo { .id=0x91 , .typ=.uinteger, .name="ChapterTimeStart" ,.importance=.default }, IdInfo { .id=0x92 , .typ=.uinteger, .name="ChapterTimeEnd" ,.importance=.default }, IdInfo { .id=0x98 , .typ=.uinteger, .name="ChapterFlagHidden" ,.importance=.default }, IdInfo { .id=0x4598 , .typ=.uinteger, .name="ChapterFlagEnabled" ,.importance=.default }, IdInfo { .id=0x6E67 , .typ=.binary , .name="ChapterSegmentUUID" ,.importance=.default }, IdInfo { .id=0x4588 , .typ=.uinteger, .name="ChapterSkipType" ,.importance=.default }, IdInfo { .id=0x6EBC , .typ=.uinteger, .name="ChapterSegmentEditionUID" ,.importance=.default }, IdInfo { .id=0x63C3 , .typ=.uinteger, .name="ChapterPhysicalEquiv" ,.importance=.default }, IdInfo { .id=0x8F , .typ=.master , .name="ChapterTrack" ,.importance=.default }, IdInfo { .id=0x89 , .typ=.uinteger, .name="ChapterTrackUID" ,.importance=.default }, IdInfo { .id=0x80 , .typ=.master , .name="ChapterDisplay" ,.importance=.default }, IdInfo { .id=0x85 , .typ=.utf8 , .name="ChapString" ,.importance=.default }, IdInfo { .id=0x437C , .typ=.string , .name="ChapLanguage" ,.importance=.default }, IdInfo { .id=0x437D , .typ=.string , .name="ChapLanguageBCP47" ,.importance=.default }, IdInfo { .id=0x437E , .typ=.string , .name="ChapCountry" ,.importance=.default }, IdInfo { .id=0x6944 , .typ=.master , .name="ChapProcess" ,.importance=.default }, IdInfo { .id=0x6955 , .typ=.uinteger, .name="ChapProcessCodecID" ,.importance=.default }, IdInfo { .id=0x450D , .typ=.binary , .name="ChapProcessPrivate" ,.importance=.default }, IdInfo { .id=0x6911 , .typ=.master , .name="ChapProcessCommand" ,.importance=.default }, IdInfo { .id=0x6922 , .typ=.uinteger, .name="ChapProcessTime" ,.importance=.default }, IdInfo { .id=0x6933 , .typ=.binary , .name="ChapProcessData" ,.importance=.default }, IdInfo { .id=0x1254C367, .typ=.master , .name="Tags" ,.importance=.default }, IdInfo { .id=0x7373 , .typ=.master , .name="Tag" ,.importance=.default }, IdInfo { .id=0x63C0 , .typ=.master , .name="Targets" ,.importance=.default }, IdInfo { .id=0x68CA , .typ=.uinteger, .name="TargetTypeValue" ,.importance=.default }, IdInfo { .id=0x63CA , .typ=.string , .name="TargetType" ,.importance=.default }, IdInfo { .id=0x63C5 , .typ=.uinteger, .name="TagTrackUID" ,.importance=.default }, IdInfo { .id=0x63C9 , .typ=.uinteger, .name="TagEditionUID" ,.importance=.default }, IdInfo { .id=0x63C4 , .typ=.uinteger, .name="TagChapterUID" ,.importance=.default }, IdInfo { .id=0x63C6 , .typ=.uinteger, .name="TagAttachmentUID" ,.importance=.default }, IdInfo { .id=0x67C8 , .typ=.master , .name="SimpleTag" ,.importance=.default }, IdInfo { .id=0x45A3 , .typ=.utf8 , .name="TagName" ,.importance=.default }, IdInfo { .id=0x447A , .typ=.string , .name="TagLanguage" ,.importance=.default }, IdInfo { .id=0x447B , .typ=.string , .name="TagLanguageBCP47" ,.importance=.default }, IdInfo { .id=0x4484 , .typ=.uinteger, .name="TagDefault" ,.importance=.default }, IdInfo { .id=0x44B4 , .typ=.uinteger, .name="TagDefaultBogus" ,.importance=.default }, IdInfo { .id=0x4487 , .typ=.utf8 , .name="TagString" ,.importance=.default }, IdInfo { .id=0x4485 , .typ=.binary , .name="TagBinary" ,.importance=.default }, }; pub const ID_EBML = Id.wrap(0x1A45DFA3); pub const ID_EBMLVersion = Id.wrap(0x4286 ); pub const ID_EBMLReadVersion = Id.wrap(0x42F7 ); pub const ID_EBMLMaxIDLength = Id.wrap(0x42F2 ); pub const ID_EBMLMaxSizeLength = Id.wrap(0x42F3 ); pub const ID_DocType = Id.wrap(0x4282 ); pub const ID_DocTypeVersion = Id.wrap(0x4287 ); pub const ID_DocTypeReadVersion = Id.wrap(0x4285 ); pub const ID_DocTypeExtension = Id.wrap(0x4281 ); pub const ID_DocTypeExtensionName = Id.wrap(0x4283 ); pub const ID_DocTypeExtensionVersion = Id.wrap(0x4284 ); pub const ID_Void = Id.wrap(0xEC ); pub const ID_CRC32 = Id.wrap(0xBF ); pub const ID_Segment = Id.wrap(0x18538067); pub const ID_SeekHead = Id.wrap(0x114D9B74); pub const ID_Seek = Id.wrap(0x4DBB ); pub const ID_SeekID = Id.wrap(0x53AB ); pub const ID_SeekPosition = Id.wrap(0x53AC ); pub const ID_Info = Id.wrap(0x1549A966); pub const ID_SegmentUID = Id.wrap(0x73A4 ); // legacy alias pub const ID_SegmentUUID = Id.wrap(0x73A4 ); pub const ID_SegmentFilename = Id.wrap(0x7384 ); pub const ID_PrevUID = Id.wrap(0x3CB923 ); // legacy alias pub const ID_PrevUUID = Id.wrap(0x3CB923 ); pub const ID_PrevFilename = Id.wrap(0x3C83AB ); pub const ID_NextUID = Id.wrap(0x3EB923 ); // legacy alias pub const ID_NextUUID = Id.wrap(0x3EB923 ); pub const ID_NextFilename = Id.wrap(0x3E83BB ); pub const ID_SegmentFamily = Id.wrap(0x4444 ); pub const ID_ChapterTranslate = Id.wrap(0x6924 ); pub const ID_ChapterTranslateEditionUID = Id.wrap(0x69FC ); pub const ID_ChapterTranslateCodec = Id.wrap(0x69BF ); pub const ID_ChapterTranslateID = Id.wrap(0x69A5 ); pub const ID_TimestampScale = Id.wrap(0x2AD7B1 ); pub const ID_Duration = Id.wrap(0x4489 ); pub const ID_DateUTC = Id.wrap(0x4461 ); pub const ID_Title = Id.wrap(0x7BA9 ); pub const ID_MuxingApp = Id.wrap(0x4D80 ); pub const ID_WritingApp = Id.wrap(0x5741 ); pub const ID_Cluster = Id.wrap(0x1F43B675); pub const ID_Timestamp = Id.wrap(0xE7 ); pub const ID_SilentTracks = Id.wrap(0x5854 ); pub const ID_SilentTrackNumber = Id.wrap(0x58D7 ); pub const ID_Position = Id.wrap(0xA7 ); pub const ID_PrevSize = Id.wrap(0xAB ); pub const ID_SimpleBlock = Id.wrap(0xA3 ); pub const ID_BlockGroup = Id.wrap(0xA0 ); pub const ID_Block = Id.wrap(0xA1 ); pub const ID_BlockVirtual = Id.wrap(0xA2 ); pub const ID_BlockAdditions = Id.wrap(0x75A1 ); pub const ID_BlockMore = Id.wrap(0xA6 ); pub const ID_BlockAddID = Id.wrap(0xEE ); pub const ID_BlockAdditional = Id.wrap(0xA5 ); pub const ID_BlockDuration = Id.wrap(0x9B ); pub const ID_ReferencePriority = Id.wrap(0xFA ); pub const ID_ReferenceBlock = Id.wrap(0xFB ); pub const ID_ReferenceVirtual = Id.wrap(0xFD ); pub const ID_CodecState = Id.wrap(0xA4 ); pub const ID_DiscardPadding = Id.wrap(0x75A2 ); pub const ID_Slices = Id.wrap(0x8E ); pub const ID_TimeSlice = Id.wrap(0xE8 ); pub const ID_LaceNumber = Id.wrap(0xCC ); pub const ID_FrameNumber = Id.wrap(0xCD ); pub const ID_BlockAdditionID = Id.wrap(0xCB ); pub const ID_Delay = Id.wrap(0xCE ); pub const ID_SliceDuration = Id.wrap(0xCF ); pub const ID_ReferenceFrame = Id.wrap(0xC8 ); pub const ID_ReferenceOffset = Id.wrap(0xC9 ); pub const ID_ReferenceTimestamp = Id.wrap(0xCA ); pub const ID_EncryptedBlock = Id.wrap(0xAF ); pub const ID_Tracks = Id.wrap(0x1654AE6B); pub const ID_TrackEntry = Id.wrap(0xAE ); pub const ID_TrackNumber = Id.wrap(0xD7 ); pub const ID_TrackUID = Id.wrap(0x73C5 ); pub const ID_TrackType = Id.wrap(0x83 ); pub const ID_FlagEnabled = Id.wrap(0xB9 ); pub const ID_FlagDefault = Id.wrap(0x88 ); pub const ID_FlagForced = Id.wrap(0x55AA ); pub const ID_FlagHearingImpaired = Id.wrap(0x55AB ); pub const ID_FlagVisualImpaired = Id.wrap(0x55AC ); pub const ID_FlagTextDescriptions = Id.wrap(0x55AD ); pub const ID_FlagOriginal = Id.wrap(0x55AE ); pub const ID_FlagCommentary = Id.wrap(0x55AF ); pub const ID_FlagLacing = Id.wrap(0x9C ); pub const ID_MinCache = Id.wrap(0x6DE7 ); pub const ID_MaxCache = Id.wrap(0x6DF8 ); pub const ID_DefaultDuration = Id.wrap(0x23E383 ); pub const ID_DefaultDecodedFieldDuration = Id.wrap(0x234E7A ); pub const ID_TrackTimestampScale = Id.wrap(0x23314F ); pub const ID_TrackOffset = Id.wrap(0x537F ); pub const ID_MaxBlockAdditionID = Id.wrap(0x55EE ); pub const ID_BlockAdditionMapping = Id.wrap(0x41E4 ); pub const ID_BlockAddIDValue = Id.wrap(0x41F0 ); pub const ID_BlockAddIDName = Id.wrap(0x41A4 ); pub const ID_BlockAddIDType = Id.wrap(0x41E7 ); pub const ID_BlockAddIDExtraData = Id.wrap(0x41ED ); pub const ID_Name = Id.wrap(0x536E ); pub const ID_Language = Id.wrap(0x22B59C ); pub const ID_LanguageIETF = Id.wrap(0x22B59D ); // legacy alias pub const ID_LanguageBCP47 = Id.wrap(0x22B59D ); pub const ID_CodecID = Id.wrap(0x86 ); pub const ID_CodecPrivate = Id.wrap(0x63A2 ); pub const ID_CodecName = Id.wrap(0x258688 ); pub const ID_AttachmentLink = Id.wrap(0x7446 ); pub const ID_CodecSettings = Id.wrap(0x3A9697 ); pub const ID_CodecInfoURL = Id.wrap(0x3B4040 ); pub const ID_CodecDownloadURL = Id.wrap(0x26B240 ); pub const ID_CodecDecodeAll = Id.wrap(0xAA ); pub const ID_TrackOverlay = Id.wrap(0x6FAB ); pub const ID_CodecDelay = Id.wrap(0x56AA ); pub const ID_SeekPreRoll = Id.wrap(0x56BB ); pub const ID_TrackTranslate = Id.wrap(0x6624 ); pub const ID_TrackTranslateEditionUID = Id.wrap(0x66FC ); pub const ID_TrackTranslateCodec = Id.wrap(0x66BF ); pub const ID_TrackTranslateTrackID = Id.wrap(0x66A5 ); pub const ID_Video = Id.wrap(0xE0 ); pub const ID_FlagInterlaced = Id.wrap(0x9A ); pub const ID_FieldOrder = Id.wrap(0x9D ); pub const ID_StereoMode = Id.wrap(0x53B8 ); pub const ID_AlphaMode = Id.wrap(0x53C0 ); pub const ID_OldStereoMode = Id.wrap(0x53B9 ); pub const ID_PixelWidth = Id.wrap(0xB0 ); pub const ID_PixelHeight = Id.wrap(0xBA ); pub const ID_PixelCropBottom = Id.wrap(0x54AA ); pub const ID_PixelCropTop = Id.wrap(0x54BB ); pub const ID_PixelCropLeft = Id.wrap(0x54CC ); pub const ID_PixelCropRight = Id.wrap(0x54DD ); pub const ID_DisplayWidth = Id.wrap(0x54B0 ); pub const ID_DisplayHeight = Id.wrap(0x54BA ); pub const ID_DisplayUnit = Id.wrap(0x54B2 ); pub const ID_AspectRatioType = Id.wrap(0x54B3 ); pub const ID_ColourSpace = Id.wrap(0x2EB524 ); // legacy alias pub const ID_UncompressedFourCC = Id.wrap(0x2EB524 ); pub const ID_GammaValue = Id.wrap(0x2FB523 ); pub const ID_FrameRate = Id.wrap(0x2383E3 ); pub const ID_Colour = Id.wrap(0x55B0 ); pub const ID_MatrixCoefficients = Id.wrap(0x55B1 ); pub const ID_BitsPerChannel = Id.wrap(0x55B2 ); pub const ID_ChromaSubsamplingHorz = Id.wrap(0x55B3 ); pub const ID_ChromaSubsamplingVert = Id.wrap(0x55B4 ); pub const ID_CbSubsamplingHorz = Id.wrap(0x55B5 ); pub const ID_CbSubsamplingVert = Id.wrap(0x55B6 ); pub const ID_ChromaSitingHorz = Id.wrap(0x55B7 ); pub const ID_ChromaSitingVert = Id.wrap(0x55B8 ); pub const ID_Range = Id.wrap(0x55B9 ); pub const ID_TransferCharacteristics = Id.wrap(0x55BA ); pub const ID_Primaries = Id.wrap(0x55BB ); pub const ID_MaxCLL = Id.wrap(0x55BC ); pub const ID_MaxFALL = Id.wrap(0x55BD ); pub const ID_MasteringMetadata = Id.wrap(0x55D0 ); pub const ID_PrimaryRChromaticityX = Id.wrap(0x55D1 ); pub const ID_PrimaryRChromaticityY = Id.wrap(0x55D2 ); pub const ID_PrimaryGChromaticityX = Id.wrap(0x55D3 ); pub const ID_PrimaryGChromaticityY = Id.wrap(0x55D4 ); pub const ID_PrimaryBChromaticityX = Id.wrap(0x55D5 ); pub const ID_PrimaryBChromaticityY = Id.wrap(0x55D6 ); pub const ID_WhitePointChromaticityX = Id.wrap(0x55D7 ); pub const ID_WhitePointChromaticityY = Id.wrap(0x55D8 ); pub const ID_LuminanceMax = Id.wrap(0x55D9 ); pub const ID_LuminanceMin = Id.wrap(0x55DA ); pub const ID_Projection = Id.wrap(0x7670 ); pub const ID_ProjectionType = Id.wrap(0x7671 ); pub const ID_ProjectionPrivate = Id.wrap(0x7672 ); pub const ID_ProjectionPoseYaw = Id.wrap(0x7673 ); pub const ID_ProjectionPosePitch = Id.wrap(0x7674 ); pub const ID_ProjectionPoseRoll = Id.wrap(0x7675 ); pub const ID_Audio = Id.wrap(0xE1 ); pub const ID_SamplingFrequency = Id.wrap(0xB5 ); pub const ID_OutputSamplingFrequency = Id.wrap(0x78B5 ); pub const ID_Channels = Id.wrap(0x9F ); pub const ID_ChannelPositions = Id.wrap(0x7D7B ); pub const ID_BitDepth = Id.wrap(0x6264 ); pub const ID_Emphasis = Id.wrap(0x92F1 ); pub const ID_TrackOperation = Id.wrap(0xE2 ); pub const ID_TrackCombinePlanes = Id.wrap(0xE3 ); pub const ID_TrackPlane = Id.wrap(0xE4 ); pub const ID_TrackPlaneUID = Id.wrap(0xE5 ); pub const ID_TrackPlaneType = Id.wrap(0xE6 ); pub const ID_TrackJoinBlocks = Id.wrap(0xE9 ); pub const ID_TrackJoinUID = Id.wrap(0xED ); pub const ID_TrickTrackUID = Id.wrap(0xC0 ); pub const ID_TrickTrackSegmentUID = Id.wrap(0xC1 ); pub const ID_TrickTrackFlag = Id.wrap(0xC6 ); pub const ID_TrickMasterTrackUID = Id.wrap(0xC7 ); pub const ID_TrickMasterTrackSegmentUID = Id.wrap(0xC4 ); pub const ID_ContentEncodings = Id.wrap(0x6D80 ); pub const ID_ContentEncoding = Id.wrap(0x6240 ); pub const ID_ContentEncodingOrder = Id.wrap(0x5031 ); pub const ID_ContentEncodingScope = Id.wrap(0x5032 ); pub const ID_ContentEncodingType = Id.wrap(0x5033 ); pub const ID_ContentCompression = Id.wrap(0x5034 ); pub const ID_ContentCompAlgo = Id.wrap(0x4254 ); pub const ID_ContentCompSettings = Id.wrap(0x4255 ); pub const ID_ContentEncryption = Id.wrap(0x5035 ); pub const ID_ContentEncAlgo = Id.wrap(0x47E1 ); pub const ID_ContentEncKeyID = Id.wrap(0x47E2 ); pub const ID_ContentEncAESSettings = Id.wrap(0x47E7 ); pub const ID_AESSettingsCipherMode = Id.wrap(0x47E8 ); pub const ID_ContentSignature = Id.wrap(0x47E3 ); pub const ID_ContentSigKeyID = Id.wrap(0x47E4 ); pub const ID_ContentSigAlgo = Id.wrap(0x47E5 ); pub const ID_ContentSigHashAlgo = Id.wrap(0x47E6 ); pub const ID_Cues = Id.wrap(0x1C53BB6B); pub const ID_CuePoint = Id.wrap(0xBB ); pub const ID_CueTime = Id.wrap(0xB3 ); pub const ID_CueTrackPositions = Id.wrap(0xB7 ); pub const ID_CueTrack = Id.wrap(0xF7 ); pub const ID_CueClusterPosition = Id.wrap(0xF1 ); pub const ID_CueRelativePosition = Id.wrap(0xF0 ); pub const ID_CueDuration = Id.wrap(0xB2 ); pub const ID_CueBlockNumber = Id.wrap(0x5378 ); pub const ID_CueCodecState = Id.wrap(0xEA ); pub const ID_CueReference = Id.wrap(0xDB ); pub const ID_CueRefTime = Id.wrap(0x96 ); pub const ID_CueRefCluster = Id.wrap(0x97 ); pub const ID_CueRefNumber = Id.wrap(0x535F ); pub const ID_CueRefCodecState = Id.wrap(0xEB ); pub const ID_Attachments = Id.wrap(0x1941A469); pub const ID_AttachedFile = Id.wrap(0x61A7 ); pub const ID_FileDescription = Id.wrap(0x467E ); pub const ID_FileName = Id.wrap(0x466E ); pub const ID_FileMimeType = Id.wrap(0x4660 ); // legacy alias pub const ID_FileMediaType = Id.wrap(0x4660 ); pub const ID_FileData = Id.wrap(0x465C ); pub const ID_FileUID = Id.wrap(0x46AE ); pub const ID_FileReferral = Id.wrap(0x4675 ); pub const ID_FileUsedStartTime = Id.wrap(0x4661 ); pub const ID_FileUsedEndTime = Id.wrap(0x4662 ); pub const ID_Chapters = Id.wrap(0x1043A770); pub const ID_EditionEntry = Id.wrap(0x45B9 ); pub const ID_EditionUID = Id.wrap(0x45BC ); pub const ID_EditionFlagHidden = Id.wrap(0x45BD ); pub const ID_EditionFlagDefault = Id.wrap(0x45DB ); pub const ID_EditionFlagOrdered = Id.wrap(0x45DD ); pub const ID_EditionDisplay = Id.wrap(0x4520 ); pub const ID_EditionString = Id.wrap(0x4521 ); pub const ID_EditionLanguageIETF = Id.wrap(0x45E4 ); pub const ID_ChapterAtom = Id.wrap(0xB6 ); pub const ID_ChapterUID = Id.wrap(0x73C4 ); pub const ID_ChapterStringUID = Id.wrap(0x5654 ); pub const ID_ChapterTimeStart = Id.wrap(0x91 ); pub const ID_ChapterTimeEnd = Id.wrap(0x92 ); pub const ID_ChapterFlagHidden = Id.wrap(0x98 ); pub const ID_ChapterFlagEnabled = Id.wrap(0x4598 ); pub const ID_ChapterSegmentUID = Id.wrap(0x6E67 ); // legacy alias pub const ID_ChapterSegmentUUID = Id.wrap(0x6E67 ); pub const ID_ChapterSkipType = Id.wrap(0x4588 ); pub const ID_ChapterSegmentEditionUID = Id.wrap(0x6EBC ); pub const ID_ChapterPhysicalEquiv = Id.wrap(0x63C3 ); pub const ID_ChapterTrack = Id.wrap(0x8F ); pub const ID_ChapterTrackUID = Id.wrap(0x89 ); pub const ID_ChapterDisplay = Id.wrap(0x80 ); pub const ID_ChapString = Id.wrap(0x85 ); pub const ID_ChapLanguage = Id.wrap(0x437C ); pub const ID_ChapLanguageIETF = Id.wrap(0x437D ); // legacy alias pub const ID_ChapLanguageBCP47 = Id.wrap(0x437D ); pub const ID_ChapCountry = Id.wrap(0x437E ); pub const ID_ChapProcess = Id.wrap(0x6944 ); pub const ID_ChapProcessCodecID = Id.wrap(0x6955 ); pub const ID_ChapProcessPrivate = Id.wrap(0x450D ); pub const ID_ChapProcessCommand = Id.wrap(0x6911 ); pub const ID_ChapProcessTime = Id.wrap(0x6922 ); pub const ID_ChapProcessData = Id.wrap(0x6933 ); pub const ID_Tags = Id.wrap(0x1254C367); pub const ID_Tag = Id.wrap(0x7373 ); pub const ID_Targets = Id.wrap(0x63C0 ); pub const ID_TargetTypeValue = Id.wrap(0x68CA ); pub const ID_TargetType = Id.wrap(0x63CA ); pub const ID_TagTrackUID = Id.wrap(0x63C5 ); pub const ID_TagEditionUID = Id.wrap(0x63C9 ); pub const ID_TagChapterUID = Id.wrap(0x63C4 ); pub const ID_TagAttachmentUID = Id.wrap(0x63C6 ); pub const ID_SimpleTag = Id.wrap(0x67C8 ); pub const ID_TagName = Id.wrap(0x45A3 ); pub const ID_TagLanguage = Id.wrap(0x447A ); pub const ID_TagLanguageIETF = Id.wrap(0x447B ); // legacy alias pub const ID_TagLanguageBCP47 = Id.wrap(0x447B ); pub const ID_TagDefault = Id.wrap(0x4484 ); pub const ID_TagDefaultBogus = Id.wrap(0x44B4 ); pub const ID_TagString = Id.wrap(0x4487 ); pub const ID_TagBinary = Id.wrap(0x4485 );
0
repos/zigmkv/src
repos/zigmkv/src/mkv/l2.zig
const std = @import("std"); const mkv = @import("../mkv.zig"); const Id = mkv.id.Id; const Type = mkv.id.Type; const BUFL = 8; // to fit any float or number as element pub const ElementBegins = struct { id: Id, typ: Type, size: ?u64, /// Allows quick-skipping unneeded elements. Contect will be delibered as unknown_or_void chunks. write_true_to_decode_as_binary: *bool, }; pub const ElementEnds = struct { id: Id, typ: Type, }; pub const Event = union(enum) { element_begins: ElementBegins, number: u64, signed_number: i64, binary_chunk: []const u8, string_chunk: []const u8, utf8_chunk: []const u8, unknown_or_void_chunk: []const u8, float: f64, element_ends: ElementEnds, }; const BEUnsignedReader = struct { x: u64, filled: u8, size: u8, const Self2 = @This(); pub fn new(sz: u64) Self2 { return Self2 { .x = 0, .filled = 0, .size = @intCast(u8, sz), }; } pub fn push_bytes(self: *Self2, bb: []const u8) ?u64 { for (bb) |b| { if (self.size == self.filled) break; self.x <<= 8; self.x |= @intCast(u64, b); self.filled += 1; } if (self.size == self.filled) return self.x; return null; } }; const BESignedReader = struct { x: i64, filled: u8, size: u8, const Self2 = @This(); pub fn new(sz: u64) Self2 { return Self2 { .x = 0, .filled = 0, .size = @intCast(u8, sz), }; } pub fn push_bytes(self: *Self2, bb: []const u8) ?i64 { for (bb) |b| { if (self.size == self.filled) break; if (self.filled == 0 and b >= 0x80) { self.x = @intCast(i64, b) - 256; } else { self.x <<= 8; self.x |= @intCast(i64, b); } self.filled += 1; } if (self.size == self.filled) return self.x; return null; } }; test "numreaders" { const expectEqual = @import("std").testing.expectEqual; expectEqual((?u64)(0x12 ), (BEUnsignedReader.new(1).push_bytes("\x12"))); expectEqual((?u64)(0x1234 ), (BEUnsignedReader.new(2).push_bytes("\x12\x34"))); expectEqual((?u64)(null ), (BEUnsignedReader.new(2).push_bytes("\x12"))); expectEqual((?u64)(0x1234567812345678), (BEUnsignedReader.new(8).push_bytes("\x12\x34\x56\x78\x12\x34\x56\x78"))); expectEqual((?i64)(0x12 ), (BESignedReader.new(1).push_bytes("\x12"))); expectEqual((?i64)(0x1234 ), (BESignedReader.new(2).push_bytes("\x12\x34"))); expectEqual((?i64)(null ), (BESignedReader.new(2).push_bytes("\x12"))); expectEqual((?i64)(0x1234567812345678), (BESignedReader.new(8).push_bytes("\x12\x34\x56\x78\x12\x34\x56\x78"))); expectEqual((?i64)(-1 ), (BESignedReader.new(1).push_bytes("\xFF"))); expectEqual((?i64)(-1 ), (BESignedReader.new(2).push_bytes("\xFF\xFF"))); expectEqual((?i64)(null ), (BESignedReader.new(2).push_bytes("\xFF"))); expectEqual((?i64)(-1 ), (BESignedReader.new(8).push_bytes("\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF"))); } /// Read exactly `required_len` bytes, emitting a buffer of exactly BUFL bytes, prepended with zero bytes const AccumulateZeroPrependedBuffer = struct { buf: [BUFL]u8, filled: u8, const Self2 = @This(); pub fn new(sz: u64) Self2 { return Self2 { .buf = [_]u8{0} ** BUFL, .filled = BUFL - @intCast(u8, sz), }; } /// XXX: ignores trailing bytes pub fn push_bytes(self: *Self2, b: []const u8) ?[BUFL]u8 { var to_copy = b.len; if (to_copy > (BUFL - self.filled)) { to_copy = (BUFL - self.filled); } std.mem.copy(u8, self.buf[self.filled..(self.filled+to_copy)], b[0..to_copy]); self.filled += @intCast(u8,to_copy); if (self.filled == BUFL) { return self.buf; } else { return null; } } }; const RawDataChunkMode = union(enum) { /// Pass-though RawDataChunks to Event.unknown_or_void_chunk unknown, /// Pass-though RawDataChunks to Event.binary_chunk binary, /// Pass-though RawDataChunks to Event.string_chunk string, /// Pass-though RawDataChunks to Event.utf8_chunk utf8, number: BEUnsignedReader, signed_number: BESignedReader, float32: BEUnsignedReader, float64: BEUnsignedReader, }; const Self = @This(); pub fn new() Self { return Self { .l1 = mkv.L1Parser.new(), .state = RawDataChunkMode { .unknown={} }, }; } l1: mkv.L1Parser, state: RawDataChunkMode, pub fn push_bytes( self: *Self, b: []const u8, usrdata: anytype, callback: fn(usrdata: @TypeOf(usrdata), event: Event)anyerror!void, )anyerror!void { const H = L1Handler(@TypeOf(usrdata)); const h = H { .self = self, .usrdata = usrdata, .callback = callback }; try self.l1.push_bytes(b, h, H.handler); } fn L1Handler(comptime T:type) type { return struct { self: *Self, usrdata: T, callback: fn(usrdata: T, event: Event)anyerror!void, fn handler(self: @This(), e: mkv.L1Parser.Event) anyerror!void { return self.self.l1handler(e, self.usrdata, self.callback); } }; } fn l1handler( self: *Self, event: mkv.L1Parser.Event, usrdata: anytype, callback: fn(usrdata: @TypeOf(usrdata), event: Event)anyerror!void, )anyerror!void { switch(event) { .TagOpened => |x| { const id = Id.wrap(x.id); const typ = id.get_type(); var skip = false; const ev = Event { .element_begins = ElementBegins { .id = id, .typ = typ, .size = x.size, .write_true_to_decode_as_binary = &skip, } }; try callback(usrdata, ev); self.state = switch(typ) { .unknown => .unknown, .string => .string, .binary => .binary, .utf8 => .utf8, .master => .unknown, .uinteger, .integer, .float, .date, => blk: { if (x.size) |sz| { if (sz > 8 or sz == 0) { return error.MkvWrongSizeForNumericElement; } if (typ == .date and sz != 8) { return error.MkvWrongSizeForNumericElement; } if (typ == .float and (sz != 8 and sz != 4)) { return error.MkvWrongSizeForNumericElement; } break :blk switch (typ) { .uinteger => RawDataChunkMode { .number = BEUnsignedReader.new(sz) }, .integer => RawDataChunkMode { .signed_number = BESignedReader.new(sz) }, // TODO: proper date handling? .date => RawDataChunkMode { .signed_number = BESignedReader.new(sz) }, .float => if (sz == 4) RawDataChunkMode { .float32 = BEUnsignedReader.new(4) } else RawDataChunkMode { .float32 = BEUnsignedReader.new(8) } , else => unreachable, }; } return error.MkvNoSizeForNumericElement; }, }; if (typ == .master and !skip) { x.write_true_here_if_master_element = true; } if (id.eql(mkv.id.ID_Void)) { self.state = .unknown; } }, .RawDataChunk => |x| { switch (self.state) { .unknown => try callback(usrdata, Event { .unknown_or_void_chunk = x }), .binary => try callback(usrdata, Event { .binary_chunk = x }), .string => try callback(usrdata, Event { .string_chunk = x }), .utf8 => try callback(usrdata, Event { .utf8_chunk = x }), .number, .float32, .float64 => |*y| { if (y.push_bytes(x)) |xx| { switch (self.state) { .number => { try callback(usrdata, Event { .number = xx }); }, .float64 => { const f = @bitCast(f64, xx); try callback(usrdata, Event { .float = f }); }, .float32 => { const f = @floatCast(f64, @bitCast(f32, @intCast(u32, xx))); try callback(usrdata, Event { .float = f }); }, else => unreachable, } } else { // number is not ready yet. Awaiting for more RawDataChunks } }, .signed_number => |*y| { if (y.push_bytes(x)) |xx| { try callback(usrdata, Event { .signed_number = xx }); } }, } }, .TagClosed => |x| { const id = Id.wrap(x.id); const typ = id.get_type(); const ev = Event { .element_ends = ElementEnds { .id = id, .typ = typ, } }; try callback(usrdata, ev); }, } } fn fortest(q: void, e:Event)anyerror!void {_ = e;_=q;} test "l2" { const e = Event { .number = 0 }; _ = e; var p : Self = new(); try p.push_bytes("", {}, fortest); }
0
repos/zigmkv/src
repos/zigmkv/src/mkv/id.zig
/// Include database of all possible Matroska elements, not just ones that are used in this parser const know_all_elements = true; pub const Importance = enum { /// get_type should be optimized to handle those quickly hot, /// handled somehow by this library important, /// the rest of elements default, }; pub const Type = enum(u4) { unknown, master, uinteger, string, binary, utf8, float, date, integer, }; pub const IdInfo = struct { id: u32, typ: Type, name: []const u8, /// Required for obtaining content from files, disregarding metadata, seeking, etc. importance: Importance, }; const database2 = @import("database.zig"); /// `database` is not expected to be included in compiled code unless explicitly references /// Type of it is `[_]IdInfo` /// /// There are also a lot of ID_SomeElementName constants typed `Id`. usingnamespace database2; /// Wrapper type for Matroska element ID. pub const Id = struct { id : u32, const Self = @This(); pub fn wrap(x:u32)Self { return Self { .id = x }; } fn entry(self:Self)?IdInfo { @setEvalBranchQuota(2000); inline for (database2.database) |x| { if (x.importance == .hot) { if (self.id == x.id) return x; } } inline for (database2.database) |x| { if (x.importance == .important or (know_all_elements and x.importance != .hot) ) { if (self.id == x.id) return x; } } return null; } pub fn get_type(self:Self) Type { return if (@call(.{.modifier = .always_inline}, entry, .{self})) |x|x.typ else Type.unknown; } pub fn get_name(self:Self)?[]const u8 { return if (@call(.{.modifier = .always_inline}, entry, .{self})) |x|x.name else null; } pub fn eql(self:Self, other:Self)bool { return self.id == other.id; } }; test "basic" { const expectEqual = @import("std").testing.expectEqual; expectEqual((?Type)(Type.master), Id.wrap(0x18538067).get_type()); expectEqual((?[]const u8)("Segment"), Id.wrap(0x18538067).get_name()); @import("std").debug.assert(Id.wrap(0x18538067).eql(database2.ID_Segment)); }
0
repos/zigmkv/src
repos/zigmkv/src/mkv/vln.zig
const std = @import("std"); const assert = std.debug.assert; /// Returns length of EBML VLN based on first byte, including the first byte /// Returns error if it is 0. pub fn len(first_byte:u8) !usize { return switch(first_byte) { 0x80...0xFF => 1, 0x40...0x7F => 2, 0x20...0x3F => 3, 0x10...0x1F => 4, 0x08...0x0F => 5, 0x04...0x07 => 6, 0x02...0x03 => 7, 0x01...0x01 => 8, 0x00...0x00 => error.MkvWrongByteInEbmlVarnum, }; } /// Returns parsed VLN, with or without the size tag, or null of VLN's data part is all 1-s. /// Panics if the number is invalid. pub fn parse_unsigned(b:[]const u8, with_tag: bool) ?u64 { assert(b.len > 0); const s = len(b[0]) catch @panic("Invalid EMBL variable-length number"); assert(b.len == s); var mask : u8 = switch(s) { 1 => 0xFF, 2 => 0x7F, 3 => 0x3F, 4 => 0x1F, 5 => 0x0F, 6 => 0x07, 7 => 0x03, 8 => 0x01, else => unreachable, }; if (!with_tag) mask >>= 1; var x = @intCast(u64, mask & b[0]); var maxpossible = @intCast(u64, mask); for(b[1..]) |v| { x <<= 8; x |= @intCast(u64, v); maxpossible <<= 8; maxpossible |= 0xFF; } if (x == maxpossible) return null; return x; } test "ebml_get_unsigned" { const expectEqual = @import("std").testing.expectEqual; expectEqual((?u64)(0x1A45DFA3), parse_unsigned("\x1a\x45\xdf\xa3", true)); expectEqual((?u64)(0x0A45DFA3), parse_unsigned("\x1a\x45\xdf\xa3", false)); expectEqual((?u64)(null), parse_unsigned("\x1f\xff\xff\xff", false)); expectEqual((?u64)(null), parse_unsigned("\x3f\xff\xff", false)); expectEqual((?u64)(null), parse_unsigned("\x7f\xff", false)); expectEqual((?u64)(null), parse_unsigned("\xff", false)); expectEqual((?u64)(null), parse_unsigned("\x1f\xff\xff\xff", true)); expectEqual((?u64)(null), parse_unsigned("\x3f\xff\xff", true)); expectEqual((?u64)(null), parse_unsigned("\x7f\xff", true)); expectEqual((?u64)(null), parse_unsigned("\xff", true)); expectEqual((?u64)(0), parse_unsigned("\x80", false)); expectEqual((?u64)(0), parse_unsigned("\x40\x00", false)); expectEqual((?u64)(0), parse_unsigned("\x20\x00\x00", false)); expectEqual((?u64)(0), parse_unsigned("\x10\x00\x00\x00", false)); expectEqual((?u64)(0), parse_unsigned("\x08\x00\x00\x00\x00", false)); expectEqual((?u64)(0), parse_unsigned("\x04\x00\x00\x00\x00\x00", false)); expectEqual((?u64)(0), parse_unsigned("\x02\x00\x00\x00\x00\x00\x00", false)); expectEqual((?u64)(0), parse_unsigned("\x01\x00\x00\x00\x00\x00\x00\x00", false)); expectEqual((?u64)(0xFE), parse_unsigned("\xfe", true)); expectEqual((?u64)(0x7FFE), parse_unsigned("\x7f\xfe", true)); expectEqual((?u64)(0x3FFFFE), parse_unsigned("\x3f\xff\xfe", true)); expectEqual((?u64)(0x1FFFFFFE), parse_unsigned("\x1f\xff\xff\xfe", true)); expectEqual((?u64)(0x7E), parse_unsigned("\xfe", false)); expectEqual((?u64)(0x3FFE), parse_unsigned("\x7f\xfe", false)); expectEqual((?u64)(0x1FFFFE), parse_unsigned("\x3f\xff\xfe", false)); expectEqual((?u64)(0x0FFFFFFE), parse_unsigned("\x1f\xff\xff\xfe", false)); expectEqual((?u64)(0x07FFFFFFFE), parse_unsigned("\x0f\xff\xff\xff\xfe", false)); expectEqual((?u64)(0x03FFFFFFFFFE), parse_unsigned("\x07\xff\xff\xff\xff\xfe", false)); expectEqual((?u64)(0x01FFFFFFFFFFFE), parse_unsigned("\x03\xff\xff\xff\xff\xff\xfe", false)); expectEqual((?u64)(0x00FFFFFFFFFFFFFE), parse_unsigned("\x01\xff\xff\xff\xff\xff\xff\xfe", false)); } const BUFL = 8; pub const EbmlVlnReader = struct { buf: [BUFL]u8, bytes_already_in_buffer: u8, const Self2 = @This(); pub fn new() Self2 { return Self2 { .bytes_already_in_buffer = 0, .buf = [1]u8{0} ** BUFL, }; } const PushBytesRet = struct { /// four outcomes: 1. ready number, 2. null, 3. not enough bytes, keep feeding, 3. error happened result: anyerror!?u64, /// Bytes can be consumed even if null returned in `result` consumed_bytes: usize, }; pub fn push_bytes(self: *Self2, bb: []const u8, with_tag: bool) PushBytesRet { if (bb.len == 0) return PushBytesRet { .result = error._NotReadyYet, .consumed_bytes = 0 }; const bytes_available = @intCast(usize,self.bytes_already_in_buffer) + bb.len; const first_byte : u8 = if (self.bytes_already_in_buffer > 0) self.buf[0] else bb[0]; const required_bytes : usize = len(first_byte) catch |e| return PushBytesRet { .result = e, .consumed_bytes = 0}; if (required_bytes > bytes_available) { // Remember those bytes var can_copy = BUFL - @intCast(usize, self.bytes_already_in_buffer); if (can_copy > bb.len) can_copy = bb.len; std.mem.copy(u8, self.buf[self.bytes_already_in_buffer..(self.bytes_already_in_buffer+can_copy)], bb[0..can_copy]); self.bytes_already_in_buffer+=@intCast(u8,can_copy); return PushBytesRet { .result = error._NotReadyYet, .consumed_bytes = can_copy }; } var vnb : []const u8 = undefined; var consumed_bytes : usize = undefined; if (self.bytes_already_in_buffer == 0) { // fast&happy path vnb = bb[0..required_bytes]; consumed_bytes = required_bytes; } else { const to_copy = required_bytes-self.bytes_already_in_buffer; std.mem.copy(u8, self.buf[self.bytes_already_in_buffer..required_bytes], bb[0..to_copy]); vnb = self.buf[0..required_bytes]; consumed_bytes = to_copy; } return PushBytesRet { .result = parse_unsigned(vnb, with_tag), .consumed_bytes = consumed_bytes }; } };
0
repos/zigmkv/src
repos/zigmkv/src/mkv/database.py
#!/usr/bin/env python3 # https://raw.githubusercontent.com/cellar-wg/matroska-specification/master/ebml_matroska.xml import sys from xml.etree import ElementTree as ET header="""// This file is codegenerated. Run `./database.py --help` for info. const mkv = @import("../mkv.zig"); const IdInfo = mkv.id.IdInfo; const Id = mkv.id.Id; pub const database = [_]IdInfo { """ footer=""" }; """ hot_elements=""" Cluster SimpleBlock Timestamp """.split() important_elements=""" Segment Info TimestampScale Cluster Timestamp SimpleBlock BlockGroup Block BlockDuration Tracks TrackEntry TrackNumber TrackType CodecID CodecPrivate Video PixelWidth PixelHeight Audio SamplingFrequency Channels ContentCompression """.split() def codegen(elids): print(header) for x in elids: i=x.get("id") t=x.get("type") n=x.get("name") p=x.get("imp") print(" IdInfo { .id=%-10s, .typ=.%-8s, .name=%-30s,.importance=.%-10s}," % (i, t, '"'+n+'"', p)) print(footer) for x in elids: i=x.get("id") n=x.get("name") print("pub const ID_%-30s = Id.wrap(%-10s);" % (n,i) ) pass def codegen_database_zig(): r=ET.fromstring(sys.stdin.buffer.read()) elids = [ { 'id':"0x1A45DFA3", 'type':"master" , "name": "EBML" ,"imp":"important" }, { 'id':"0x4286" , 'type':"uinteger", "name": "EBMLVersion" ,"imp":"default" }, { 'id':"0x42F7" , 'type':"uinteger", "name": "EBMLReadVersion" ,"imp":"important" }, { 'id':"0x42F2" , 'type':"uinteger", "name": "EBMLMaxIDLength" ,"imp":"default" }, { 'id':"0x42F3" , 'type':"uinteger", "name": "EBMLMaxSizeLength" ,"imp":"default" }, { 'id':"0x4282" , 'type':"string" , "name": "DocType" ,"imp":"important" }, { 'id':"0x4287" , 'type':"uinteger", "name": "DocTypeVersion" ,"imp":"default" }, { 'id':"0x4285" , 'type':"uinteger", "name": "DocTypeReadVersion" ,"imp":"important" }, { 'id':"0x4281" , 'type':"master" , "name": "DocTypeExtension" ,"imp":"default" }, { 'id':"0x4283" , 'type':"string" , "name": "DocTypeExtensionName" ,"imp":"default" }, { 'id':"0x4284" , 'type':"uinteger", "name": "DocTypeExtensionVersion" ,"imp":"default" }, { 'id':"0xEC" , 'type':"binary" , "name": "Void" ,"imp":"default" }, { 'id':"0xBF" , 'type':"binary" , "name": "CRC32" ,"imp":"default" }, ]; for x in r.findall("q:element",namespaces={"q":"urn:ietf:rfc:8794"}): i=x.get("id") t=x.get("type") n=x.get("name") impo=n in important_elements; hoto=n in hot_elements; if t == "utf-8": t="utf8" if n.startswith("EBML"): continue imp = "important" if impo else "default" if hoto: imp = "hot" elids.append({ 'name': n, 'id': i, 'type': t, 'imp': imp, }); codegen(elids) if __name__ == "__main__": if len(sys.argv) != 1: print("Usage: curl -s https://raw.githubusercontent.com/cellar-wg/matroska-specification/master/ebml_matroska.xml | python3 src/mkv/database.py > src/mkv/database.zig\n") sys.exit(1) codegen_database_zig()
0
repos/zigmkv/src
repos/zigmkv/src/mkv/l1.zig
const std = @import("std"); const BUFL = 8; // to fit any VLN const MAXDEPTH = 8; // max depth of nested EBML elements const vln = @import("../mkv.zig").vln; pub const TagOpenInfo = struct { id: u32, size: ?u64, /// To be set by event handler. If size is null and this is a master element then no tag closed event may be not delivered. write_true_here_if_master_element: bool, }; pub const TagCloseInfo = struct { id: u32, }; pub const Event = union(enum) { /// Do not squirrel away the pointer TagOpened: *TagOpenInfo, RawDataChunk: []const u8, TagClosed: TagCloseInfo, }; const ReadingEbmlVln = vln.EbmlVlnReader; const WaitingForId = struct { reading_num : ReadingEbmlVln, }; const WaitingForSize = struct { reading_num : ReadingEbmlVln, element_id: u32, }; const StreamingData = struct { element_id: u32, bytes_remaining: ?u32, }; const State = union(enum) { /// Waiting until we get full element ID waiting_for_id: WaitingForId, /// Waiting until we get full EBML element size waiting_for_size : WaitingForSize, /// Inside non-Master EBML element streaming_data : StreamingData, }; const ParentElement = struct { element_id: u32, bytes_remaining: u32, // shall it handle super-large segments that fail to fit in u32? }; const Self = @This(); state: State, parent_elements: [MAXDEPTH]ParentElement, parent_element_count: u8, pub fn new() Self { var p = Self { .state = State { .waiting_for_id = WaitingForId { .reading_num = ReadingEbmlVln.new(), } }, .parent_elements = undefined, .parent_element_count = 0, }; return p; } /// Make L1Parser interpret specified bytes, calling `callback` if some event is ready to go. /// The data is only minimally cached. Short pushes result in short `RawData` events. pub fn push_bytes( self: *Self, b: []const u8, usrdata: anytype, callback: fn(usrdata: @TypeOf(usrdata), event: Event)anyerror!void, )anyerror!void { var bb = b; var loop_again = false; // for some final cleanup events even when all data is processed while(bb.len != 0 or loop_again) //: ({@import("std").debug.warn("L {} {}\n", bb.len, loop_again);}) { loop_again=false; const immediate_parent_element : ?*ParentElement = if (self.parent_element_count > 0) &self.parent_elements[self.parent_element_count-1] else null; if (immediate_parent_element) |par| { //@import("std").debug.warn("P rem={} id={x}\n", par.bytes_remaining, par.element_id); if (par.bytes_remaining == 0) { try callback(usrdata, Event{.TagClosed=TagCloseInfo { .id = par.element_id} }); self.parent_element_count -= 1; // TODO: check if state is not this one and maybe report error self.state = State { .waiting_for_id = WaitingForId { .reading_num = ReadingEbmlVln.new(), }, }; loop_again = true; continue; } } switch (self.state) { .waiting_for_id => |*ss| { var allowed_bytes = bb.len; if (immediate_parent_element) |par| { if (allowed_bytes > par.bytes_remaining) { allowed_bytes = par.bytes_remaining; } } const reti = ss.reading_num.push_bytes(bb[0..allowed_bytes], true); bb = bb[reti.consumed_bytes..]; if (immediate_parent_element) |par| { par.bytes_remaining -= @intCast(u32, reti.consumed_bytes); } const ret : anyerror!?u64 = reti.result; _ = ret catch |x| if (x == error._NotReadyYet) continue; const id = (try ret) orelse return error.MkvInvalidElementId; if (id > 0xFFFFFFFE) return error.MkvElementIdTooLarge; self.state = State { .waiting_for_size = WaitingForSize { .reading_num = ReadingEbmlVln.new(), .element_id = @intCast(u32,id), }, }; continue; }, .waiting_for_size => |*ss| { var allowed_bytes = bb.len; if (immediate_parent_element) |par| { if (allowed_bytes > par.bytes_remaining) { allowed_bytes = par.bytes_remaining; } } const reti = ss.reading_num.push_bytes(bb[0..allowed_bytes], false); bb = bb[reti.consumed_bytes..]; if (immediate_parent_element) |par| { par.bytes_remaining -= @intCast(u32, reti.consumed_bytes); } const ret : anyerror!?u64 = reti.result; _ = ret catch |x| if (x == error._NotReadyYet) continue; var size = try ret; var ti = TagOpenInfo { .id = ss.element_id, .size = size, .write_true_here_if_master_element = false, }; try callback(usrdata, Event{.TagOpened=&ti}); if (size) |x| if (x > 0xFFFFFFFF) { // Considering that large elements infinite size = null; }; var size32 = if(size)|x|@intCast(u32, x) else null; if (immediate_parent_element) |par| { // Fill in size even if child element's size is null // Or trim too large size, prefering parent element's size over child's if (size32) |sz| { if (sz > par.bytes_remaining) { size32 = par.bytes_remaining; } } else { size32 = par.bytes_remaining; } } if (!ti.write_true_here_if_master_element) { // non-master element self.state = State { .streaming_data = StreamingData { .element_id = ss.element_id, .bytes_remaining = size32, }, }; continue; } else { // master element if (self.parent_element_count >= MAXDEPTH) { return error.MkvElementsNestTooDeep; } if (size32) |sz| { // There is some size, so can add parent element to the stack const new_parent_element = &self.parent_elements[self.parent_element_count]; new_parent_element.*.element_id = ss.element_id; new_parent_element.*.bytes_remaining = sz; self.parent_element_count += 1; if (immediate_parent_element) |par| { par.bytes_remaining -= sz; } } self.state = State { .waiting_for_id = WaitingForId { .reading_num = ReadingEbmlVln.new(), }, }; continue; } }, .streaming_data => |*ss| { var bytes_to_haul_this_time = bb.len; if (ss.bytes_remaining)|x|{ if (bytes_to_haul_this_time > x) bytes_to_haul_this_time = x; } try callback(usrdata, Event{.RawDataChunk=bb[0..bytes_to_haul_this_time]}); bb=bb[bytes_to_haul_this_time..]; if (immediate_parent_element) |par| { par.bytes_remaining -= @intCast(u32, bytes_to_haul_this_time); } if (ss.bytes_remaining)|*x|{ x.* -= @intCast(u32,bytes_to_haul_this_time); if (x.* == 0) { // finished streaming try callback(usrdata, Event{.TagClosed=TagCloseInfo { .id = ss.element_id} }); self.state = State { .waiting_for_id = WaitingForId { .reading_num = ReadingEbmlVln.new(), }, }; loop_again = true; } } continue; }, } } }
0
repos
repos/zig-build-system--0.13.0-examples/README.md
# Zig Build System Exampels of Zig's tutorial - Getting Started - [Simple Executable](projects/pr01) - [Adding a Convenience Step for Running the Application](projects/pr02) - The Basics - [User-Provided Options](projects/pr03) - [Standard Configuration Options](projects/pr04) - [Options for Conditional Compilation](projects/pr05) - [Static Library](projects/pr06) - [Dynamic Library](projects/pr07) - [Testing](projects/pr08) - [Linking to System Libraries](projects/pr09) - Generating Files - [Running System Tools](projects/pr10) - [Running the Project’s Tools](projects/pr11) - [Producing Assets for @embedFile](projects/pr12) - [Generating Zig Source Code](projects/pr13) - [Dealing With One or More Generated Files](projects/pr14) - [Mutating Source Files in Place](projects/pr15) - Handy Examples - [Build for multiple targets to make a release](projects/pr16)
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr03/example.zig
const std = @import("std"); pub fn main() !void { std.debug.print("Hello World!\n", .{}); }
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr03/README.md
## User-Provided Options Use `b.option` to make the build script configurable to end users as well as other projects that depend on the project as a package. `zig build --summary all -Dwindows=true`
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr03/build.zig
const std = @import("std"); pub fn build(b: *std.Build) void { const windows = b.option(bool, "windows", "Target Microsoft Windows") orelse false; const exe = b.addExecutable(.{ .name = "hello", .root_source_file = b.path("example.zig"), .target = b.resolveTargetQuery(.{ .os_tag = if (windows) .windows else null, }), }); b.installArtifact(exe); }
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr13/main.zig
const std = @import("std"); const Person = @import("person").Person; pub fn main() !void { const p: Person = .{}; try std.io.getStdOut().writer().print("Hello {any}\n", .{p}); }
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr13/README.md
## Generating Zig Source Code This build file uses a Zig program to generate a Zig file and then exposes it to the main program as a module dependency. `zig build -Dlanguage=ja --summary all`
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr13/build.zig
const std = @import("std"); pub fn build(b: *std.Build) void { const tool = b.addExecutable(.{ .name = "generate_struct", .root_source_file = b.path("tools/generate_struct.zig"), .target = b.host, }); const tool_step = b.addRunArtifact(tool); const output = tool_step.addOutputFileArg("person.zig"); const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); const exe = b.addExecutable(.{ .name = "hello", .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, }); exe.root_module.addAnonymousImport("person", .{ .root_source_file = output, }); b.installArtifact(exe); }
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr13/generate_struct.zig
const std = @import("std"); pub fn main() !void { var arena_state = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); const args = try std.process.argsAlloc(arena); if (args.len != 2) fatal("wrong number of arguments", .{}); const output_file_path = args[1]; var output_file = std.fs.cwd().createFile(output_file_path, .{}) catch |err| { fatal("unable to open '{s}': {s}", .{ output_file_path, @errorName(err) }); }; defer output_file.close(); try output_file.writeAll( \\pub const Person = struct { \\ age: usize = 18, \\ name: []const u8 = "foo" \\}; ); return std.process.cleanExit(); } fn fatal(comptime format: []const u8, args: anytype) noreturn { std.debug.print(format, args); std.process.exit(1); }
0
repos/zig-build-system--0.13.0-examples/projects/pr13
repos/zig-build-system--0.13.0-examples/projects/pr13/src/main.zig
const std = @import("std"); pub fn main() !void { var arena_state = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); const self_exe_dir_path = try std.fs.selfExeDirPathAlloc(arena); var self_exe_dir = try std.fs.cwd().openDir(self_exe_dir_path, .{}); defer self_exe_dir.close(); const word = try self_exe_dir.readFileAlloc(arena, "word.txt", 1000); try std.io.getStdOut().writer().print("Hello {s}\n", .{word}); }
0
repos/zig-build-system--0.13.0-examples/projects/pr13
repos/zig-build-system--0.13.0-examples/projects/pr13/tools/word_select.zig
const std = @import("std"); const usage = \\Usage: ./word_select [options] \\ \\Options: \\ --input-file INPUT_JSON_FILE \\ --output-file OUTPUT_TXT_FILE \\ --lang LANG \\ ; pub fn main() !void { var arena_state = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); const args = try std.process.argsAlloc(arena); var opt_input_file_path: ?[]const u8 = null; var opt_output_file_path: ?[]const u8 = null; var opt_lang: ?[]const u8 = null; { var i: usize = 1; while (i < args.len) : (i += 1) { const arg = args[i]; if (std.mem.eql(u8, "-h", arg) or std.mem.eql(u8, "--help", arg)) { try std.io.getStdOut().writeAll(usage); return std.process.cleanExit(); } else if (std.mem.eql(u8, "--input-file", arg)) { i += 1; if (i > args.len) fatal("expected arg after '{s}'", .{arg}); if (opt_input_file_path != null) fatal("duplicated {s} argument", .{arg}); opt_input_file_path = args[i]; } else if (std.mem.eql(u8, "--output-file", arg)) { i += 1; if (i > args.len) fatal("expected arg after '{s}'", .{arg}); if (opt_output_file_path != null) fatal("duplicated {s} argument", .{arg}); opt_output_file_path = args[i]; } else if (std.mem.eql(u8, "--lang", arg)) { i += 1; if (i > args.len) fatal("expected arg after '{s}'", .{arg}); if (opt_lang != null) fatal("duplicated {s} argument", .{arg}); opt_lang = args[i]; } else { fatal("unrecognized arg: '{s}'", .{arg}); } } } const input_file_path = opt_input_file_path orelse fatal("missing --input-file", .{}); const output_file_path = opt_output_file_path orelse fatal("missing --output-file", .{}); const lang = opt_lang orelse fatal("missing --lang", .{}); var input_file = std.fs.cwd().openFile(input_file_path, .{}) catch |err| { fatal("unable to open '{s}': {s}", .{ input_file_path, @errorName(err) }); }; defer input_file.close(); var output_file = std.fs.cwd().createFile(output_file_path, .{}) catch |err| { fatal("unable to open '{s}': {s}", .{ output_file_path, @errorName(err) }); }; defer output_file.close(); var json_reader = std.json.reader(arena, input_file.reader()); var words = try std.json.ArrayHashMap([]const u8).jsonParse(arena, &json_reader, .{ .allocate = .alloc_if_needed, .max_value_len = 1000, }); const w = words.map.get(lang) orelse fatal("Lang not found in JSON file", .{}); try output_file.writeAll(w); return std.process.cleanExit(); } fn fatal(comptime format: []const u8, args: anytype) noreturn { std.debug.print(format, args); std.process.exit(1); }
0
repos/zig-build-system--0.13.0-examples/projects/pr13
repos/zig-build-system--0.13.0-examples/projects/pr13/tools/words.json
{ "en": "world", "it": "mondo", "ja": "世界" }
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr14/README.md
## Dealing With One or More Generated Files `zig build --summary all`
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr14/build.zig
const std = @import("std"); pub fn build(b: *std.Build) void { const exe = b.addExecutable(.{ .name = "app", .root_source_file = b.path("src/main.zig"), .target = b.host, }); const version = b.option([]const u8, "version", "application version string") orelse "0.0.0"; const wf = b.addWriteFiles(); const app_exe_name = b.fmt("project/{s}", .{exe.out_filename}); _ = wf.addCopyFile(exe.getEmittedBin(), app_exe_name); _ = wf.add("project/version.txt", version); const tar = b.addSystemCommand(&.{ "tar", "czf" }); tar.setCwd(wf.getDirectory()); const out_file = tar.addOutputFileArg("project.tar.gz"); tar.addArgs(&.{"project/"}); const install_tar = b.addInstallFileWithDir(out_file, .prefix, "project.tar.gz"); b.getInstallStep().dependOn(&install_tar.step); }
0
repos/zig-build-system--0.13.0-examples/projects/pr14
repos/zig-build-system--0.13.0-examples/projects/pr14/src/main.zig
const std = @import("std"); pub fn main() !void { std.debug.print("hello world\n", .{}); }
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr10/zip.zig
const std = @import("std"); pub fn main() !void { std.debug.print("Hello World!\n", .{}); }
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr10/README.md
## Running System Tools This build script creates a dynamic library from Zig code. `zig build -Dlanguage=ja --summary all`
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr10/build.zig
const std = @import("std"); pub fn build(b: *std.Build) void { const lang = b.option([]const u8, "language", "language of the greeting") orelse "en"; const tool_run = b.addSystemCommand(&.{"jq"}); tool_run.addArgs(&.{ b.fmt( \\.["{s}"] , .{lang}), "-r", // raw output to omit quotes around the selected string }); tool_run.addFileArg(b.path("words.json")); const output = tool_run.captureStdOut(); b.getInstallStep().dependOn(&b.addInstallFileWithDir(output, .prefix, "word.txt").step); const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); const exe = b.addExecutable(.{ .name = "hello", .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, }); const install_artifact = b.addInstallArtifact(exe, .{ .dest_dir = .{ .override = .prefix }, }); b.getInstallStep().dependOn(&install_artifact.step); }
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr10/words.json
{ "en": "world", "it": "mondo", "ja": "世界" }
0
repos/zig-build-system--0.13.0-examples/projects/pr10
repos/zig-build-system--0.13.0-examples/projects/pr10/src/main.zig
const std = @import("std"); pub fn main() !void { var arena_state = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); const self_exe_dir_path = try std.fs.selfExeDirPathAlloc(arena); var self_exe_dir = try std.fs.cwd().openDir(self_exe_dir_path, .{}); defer self_exe_dir.close(); const word = try self_exe_dir.readFileAlloc(arena, "word.txt", 1000); try std.io.getStdOut().writer().print("Hello {s}\n", .{word}); }
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr11/main.zig
const std = @import("std"); pub fn main() !void { var arena_state = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); const self_exe_dir_path = try std.fs.selfExeDirPathAlloc(arena); var self_exe_dir = try std.fs.cwd().openDir(self_exe_dir_path, .{}); defer self_exe_dir.close(); const word = try self_exe_dir.readFileAlloc(arena, "word.txt", 1000); try std.io.getStdOut().writer().print("Hello {s}\n", .{word}); }
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr11/README.md
## Running the Project’s Tools This version of hello world expects to find a `word.txt` file in the same path, and we want to produce it at build-time by invoking a Zig program on a JSON file. `zig build -Dlanguage=ja --summary all`
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr11/build.zig
const std = @import("std"); pub fn build(b: *std.Build) void { const lang = b.option([]const u8, "language", "language of the greeting") orelse "en"; const tool = b.addExecutable(.{ .name = "word_select", .root_source_file = b.path("tools/word_select.zig"), .target = b.host, }); const tool_step = b.addRunArtifact(tool); tool_step.addArg("--input-file"); tool_step.addFileArg(b.path("tools/words.json")); tool_step.addArg("--output-file"); const output = tool_step.addOutputFileArg("word.txt"); tool_step.addArgs(&.{ "--lang", lang }); b.getInstallStep().dependOn(&b.addInstallFileWithDir(output, .prefix, "word.txt").step); const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); const exe = b.addExecutable(.{ .name = "hello", .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, }); const install_artifact = b.addInstallArtifact(exe, .{ .dest_dir = .{ .override = .prefix }, }); b.getInstallStep().dependOn(&install_artifact.step); }
0
repos/zig-build-system--0.13.0-examples/projects/pr11
repos/zig-build-system--0.13.0-examples/projects/pr11/src/main.zig
const std = @import("std"); pub fn main() !void { var arena_state = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); const self_exe_dir_path = try std.fs.selfExeDirPathAlloc(arena); var self_exe_dir = try std.fs.cwd().openDir(self_exe_dir_path, .{}); defer self_exe_dir.close(); const word = try self_exe_dir.readFileAlloc(arena, "word.txt", 1000); try std.io.getStdOut().writer().print("Hello {s}\n", .{word}); }
0
repos/zig-build-system--0.13.0-examples/projects/pr11
repos/zig-build-system--0.13.0-examples/projects/pr11/tools/word_select.zig
const std = @import("std"); const usage = \\Usage: ./word_select [options] \\ \\Options: \\ --input-file INPUT_JSON_FILE \\ --output-file OUTPUT_TXT_FILE \\ --lang LANG \\ ; pub fn main() !void { var arena_state = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); const args = try std.process.argsAlloc(arena); var opt_input_file_path: ?[]const u8 = null; var opt_output_file_path: ?[]const u8 = null; var opt_lang: ?[]const u8 = null; { var i: usize = 1; while (i < args.len) : (i += 1) { const arg = args[i]; if (std.mem.eql(u8, "-h", arg) or std.mem.eql(u8, "--help", arg)) { try std.io.getStdOut().writeAll(usage); return std.process.cleanExit(); } else if (std.mem.eql(u8, "--input-file", arg)) { i += 1; if (i > args.len) fatal("expected arg after '{s}'", .{arg}); if (opt_input_file_path != null) fatal("duplicated {s} argument", .{arg}); opt_input_file_path = args[i]; } else if (std.mem.eql(u8, "--output-file", arg)) { i += 1; if (i > args.len) fatal("expected arg after '{s}'", .{arg}); if (opt_output_file_path != null) fatal("duplicated {s} argument", .{arg}); opt_output_file_path = args[i]; } else if (std.mem.eql(u8, "--lang", arg)) { i += 1; if (i > args.len) fatal("expected arg after '{s}'", .{arg}); if (opt_lang != null) fatal("duplicated {s} argument", .{arg}); opt_lang = args[i]; } else { fatal("unrecognized arg: '{s}'", .{arg}); } } } const input_file_path = opt_input_file_path orelse fatal("missing --input-file", .{}); const output_file_path = opt_output_file_path orelse fatal("missing --output-file", .{}); const lang = opt_lang orelse fatal("missing --lang", .{}); var input_file = std.fs.cwd().openFile(input_file_path, .{}) catch |err| { fatal("unable to open '{s}': {s}", .{ input_file_path, @errorName(err) }); }; defer input_file.close(); var output_file = std.fs.cwd().createFile(output_file_path, .{}) catch |err| { fatal("unable to open '{s}': {s}", .{ output_file_path, @errorName(err) }); }; defer output_file.close(); var json_reader = std.json.reader(arena, input_file.reader()); var words = try std.json.ArrayHashMap([]const u8).jsonParse(arena, &json_reader, .{ .allocate = .alloc_if_needed, .max_value_len = 1000, }); const w = words.map.get(lang) orelse fatal("Lang not found in JSON file", .{}); try output_file.writeAll(w); return std.process.cleanExit(); } fn fatal(comptime format: []const u8, args: anytype) noreturn { std.debug.print(format, args); std.process.exit(1); }
0
repos/zig-build-system--0.13.0-examples/projects/pr11
repos/zig-build-system--0.13.0-examples/projects/pr11/tools/words.json
{ "en": "world", "it": "mondo", "ja": "世界" }
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr06/fizzbuzz.zig
export fn fizzbuzz(n: usize) ?[*:0]const u8 { if (n % 5 == 0) { if (n % 3 == 0) { return "fizzbuzz"; } else { return "fizz"; } } else if (n % 3 == 0) { return "buzz"; } return null; }
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr06/demo.zig
const std = @import("std"); extern fn fizzbuzz(n: usize) ?[*:0]const u8; pub fn main() !void { const stdout = std.io.getStdOut(); var bw = std.io.bufferedWriter(stdout.writer()); const w = bw.writer(); for (0..100) |n| { if (fizzbuzz(n)) |s| { try w.print("{s}\n", .{s}); } else { try w.print("{d}\n", .{n}); } } try bw.flush(); }
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr06/README.md
## Static Library This build script creates a static library from Zig code, and then also an executable from other Zig code that consumes it. - `zig build --summary all`
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr06/build.zig
const std = @import("std"); pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); const libfizzbuzz = b.addStaticLibrary(.{ .name = "fizzbuzz", .root_source_file = b.path("fizzbuzz.zig"), .target = target, .optimize = optimize, }); const exe = b.addExecutable(.{ .name = "demo", .root_source_file = b.path("demo.zig"), .target = target, .optimize = optimize, }); exe.linkLibrary(libfizzbuzz); b.installArtifact(libfizzbuzz); if (b.option(bool, "enable-demo", "install the demo too") orelse false) { b.installArtifact(exe); } }
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr01/hello.zig
const std = @import("std"); pub fn main() !void { std.debug.print("Hello World!\n", .{}); }
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr01/README.md
# Simple Executable This build script creates an executable from a Zig file that contains a public main function definition. `zig build --summary all`
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr01/build.zig
const std = @import("std"); pub fn build(b: *std.Build) void { const exe = b.addExecutable(.{ .name = "hello", .root_source_file = b.path("hello.zig"), .target = b.host, }); b.installArtifact(exe); }
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr04/hello.zig
const std = @import("std"); pub fn main() !void { std.debug.print("Hello World!\n", .{}); }
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr04/README.md
# Standard Configuration Options Standard optimization options allow the person running `zig` build to select between `Debug`, `ReleaseSafe`, `ReleaseFast`, and `ReleaseSmall`. By default none of the release options are considered the preferable choice by the build script, and the user must make a decision in order to create a release build. `zig build --help` `zig build -Dtarget=x86_64-windows -Doptimize=ReleaseSmall --summary all`
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr04/build.zig
const std = @import("std"); pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); const exe = b.addExecutable(.{ .name = "hello", .root_source_file = b.path("hello.zig"), .target = target, .optimize = optimize, }); b.installArtifact(exe); }
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr16/hello.zig
const std = @import("std"); pub fn main() !void { std.debug.print("Hello World!\n", .{}); }
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr16/README.md
## Build for multiple targets to make a release In this example we’re going to change some defaults when creating an InstallArtifact step in order to put the build for each target into a separate subdirectory inside the install path. `zig build --summary all`
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr16/build.zig
const std = @import("std"); const targets: []const std.Target.Query = &.{ .{ .cpu_arch = .aarch64, .os_tag = .macos }, .{ .cpu_arch = .aarch64, .os_tag = .linux }, .{ .cpu_arch = .x86_64, .os_tag = .linux, .abi = .gnu }, .{ .cpu_arch = .x86_64, .os_tag = .linux, .abi = .musl }, .{ .cpu_arch = .x86_64, .os_tag = .windows }, }; pub fn build(b: *std.Build) !void { for (targets) |t| { const exe = b.addExecutable(.{ .name = "hello", .root_source_file = b.path("hello.zig"), .target = b.resolveTargetQuery(t), .optimize = .ReleaseSafe, }); const target_output = b.addInstallArtifact(exe, .{ .dest_dir = .{ .override = .{ .custom = try t.zigTriple(b.allocator), }, }, }); b.getInstallStep().dependOn(&target_output.step); } }
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr07/fizzbuzz.zig
export fn fizzbuzz(n: usize) ?[*:0]const u8 { if (n % 5 == 0) { if (n % 3 == 0) { return "fizzbuzz"; } else { return "fizz"; } } else if (n % 3 == 0) { return "buzz"; } return null; }
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr07/README.md
## Dynamic Library This build script creates a dynamic library from Zig code. `zig build --summary all` `zig build-exe demo.zig -l fizzbuzz -L fizzbuzz.lib` `zig build --summary all -Denable-demo`
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr07/build.zig
const std = @import("std"); pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); const libfizzbuzz = b.addSharedLibrary(.{ .name = "fizzbuzz", .root_source_file = b.path("fizzbuzz.zig"), .target = target, .optimize = optimize, .version = .{ .major = 1, .minor = 2, .patch = 3 }, }); b.installArtifact(libfizzbuzz); }
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr08/main.zig
const std = @import("std"); test "simple test" { var list = std.ArrayList(i32).init(std.testing.allocator); defer list.deinit(); try list.append(42); try std.testing.expectEqual(@as(i32, 42), list.pop()); }
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr08/README.md
## Testing This build script creates a dynamic library from Zig code. `zig test foo.zig` `zig build test --summary all`
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr08/build.zig
const std = @import("std"); const test_targets = [_]std.Target.Query{ .{}, // native .{ .cpu_arch = .x86_64, .os_tag = .linux, }, .{ .cpu_arch = .aarch64, .os_tag = .macos, }, }; pub fn build(b: *std.Build) void { const test_step = b.step("test", "Run unit tests"); for (test_targets) |target| { const unit_tests = b.addTest(.{ .root_source_file = b.path("main.zig"), .target = b.resolveTargetQuery(target), }); const run_unit_tests = b.addRunArtifact(unit_tests); run_unit_tests.skip_foreign_checks = true; test_step.dependOn(&run_unit_tests.step); } }
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr02/hello.zig
const std = @import("std"); pub fn main() !void { std.debug.print("Hello World!\n", .{}); }
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr02/README.md
# Adding a Convenience Step for Running the Application It is common to add a Run step to provide a way to run one’s main application directly from the build command. `zig build run --summary all`
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr02/build.zig
const std = @import("std"); pub fn build(b: *std.Build) void { const exe = b.addExecutable(.{ .name = "hello", .root_source_file = b.path("hello.zig"), .target = b.host, }); b.installArtifact(exe); const run_exe = b.addRunArtifact(exe); const run_step = b.step("run", "Run the application"); run_step.dependOn(&run_exe.step); }
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr12/main.zig
const std = @import("std"); const word = @embedFile("word"); pub fn main() !void { try std.io.getStdOut().writer().print("Hello {s}\n", .{word}); }
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr12/README.md
## Producing Assets for `@embedFile` This version of hello world wants to `@embedFile` an asset generated at build time, which we’re going to produce using a tool written in Zig. `zig build -Dlanguage=ja --summary all`
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr12/build.zig
const std = @import("std"); pub fn build(b: *std.Build) void { const lang = b.option([]const u8, "language", "language of the greeting") orelse "en"; const tool = b.addExecutable(.{ .name = "word_select", .root_source_file = b.path("tools/word_select.zig"), .target = b.host, }); const tool_step = b.addRunArtifact(tool); tool_step.addArg("--input-file"); tool_step.addFileArg(b.path("tools/words.json")); tool_step.addArg("--output-file"); const output = tool_step.addOutputFileArg("word.txt"); tool_step.addArgs(&.{ "--lang", lang }); b.getInstallStep().dependOn(&b.addInstallFileWithDir(output, .prefix, "word.txt").step); const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); const exe = b.addExecutable(.{ .name = "hello", .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, }); const install_artifact = b.addInstallArtifact(exe, .{ .dest_dir = .{ .override = .prefix }, }); b.getInstallStep().dependOn(&install_artifact.step); }
0
repos/zig-build-system--0.13.0-examples/projects/pr12
repos/zig-build-system--0.13.0-examples/projects/pr12/src/main.zig
const std = @import("std"); pub fn main() !void { var arena_state = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); const self_exe_dir_path = try std.fs.selfExeDirPathAlloc(arena); var self_exe_dir = try std.fs.cwd().openDir(self_exe_dir_path, .{}); defer self_exe_dir.close(); const word = try self_exe_dir.readFileAlloc(arena, "word.txt", 1000); try std.io.getStdOut().writer().print("Hello {s}\n", .{word}); }
0
repos/zig-build-system--0.13.0-examples/projects/pr12
repos/zig-build-system--0.13.0-examples/projects/pr12/tools/word_select.zig
const std = @import("std"); const usage = \\Usage: ./word_select [options] \\ \\Options: \\ --input-file INPUT_JSON_FILE \\ --output-file OUTPUT_TXT_FILE \\ --lang LANG \\ ; pub fn main() !void { var arena_state = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); const args = try std.process.argsAlloc(arena); var opt_input_file_path: ?[]const u8 = null; var opt_output_file_path: ?[]const u8 = null; var opt_lang: ?[]const u8 = null; { var i: usize = 1; while (i < args.len) : (i += 1) { const arg = args[i]; if (std.mem.eql(u8, "-h", arg) or std.mem.eql(u8, "--help", arg)) { try std.io.getStdOut().writeAll(usage); return std.process.cleanExit(); } else if (std.mem.eql(u8, "--input-file", arg)) { i += 1; if (i > args.len) fatal("expected arg after '{s}'", .{arg}); if (opt_input_file_path != null) fatal("duplicated {s} argument", .{arg}); opt_input_file_path = args[i]; } else if (std.mem.eql(u8, "--output-file", arg)) { i += 1; if (i > args.len) fatal("expected arg after '{s}'", .{arg}); if (opt_output_file_path != null) fatal("duplicated {s} argument", .{arg}); opt_output_file_path = args[i]; } else if (std.mem.eql(u8, "--lang", arg)) { i += 1; if (i > args.len) fatal("expected arg after '{s}'", .{arg}); if (opt_lang != null) fatal("duplicated {s} argument", .{arg}); opt_lang = args[i]; } else { fatal("unrecognized arg: '{s}'", .{arg}); } } } const input_file_path = opt_input_file_path orelse fatal("missing --input-file", .{}); const output_file_path = opt_output_file_path orelse fatal("missing --output-file", .{}); const lang = opt_lang orelse fatal("missing --lang", .{}); var input_file = std.fs.cwd().openFile(input_file_path, .{}) catch |err| { fatal("unable to open '{s}': {s}", .{ input_file_path, @errorName(err) }); }; defer input_file.close(); var output_file = std.fs.cwd().createFile(output_file_path, .{}) catch |err| { fatal("unable to open '{s}': {s}", .{ output_file_path, @errorName(err) }); }; defer output_file.close(); var json_reader = std.json.reader(arena, input_file.reader()); var words = try std.json.ArrayHashMap([]const u8).jsonParse(arena, &json_reader, .{ .allocate = .alloc_if_needed, .max_value_len = 1000, }); const w = words.map.get(lang) orelse fatal("Lang not found in JSON file", .{}); try output_file.writeAll(w); return std.process.cleanExit(); } fn fatal(comptime format: []const u8, args: anytype) noreturn { std.debug.print(format, args); std.process.exit(1); }
0
repos/zig-build-system--0.13.0-examples/projects/pr12
repos/zig-build-system--0.13.0-examples/projects/pr12/tools/words.json
{ "en": "world", "it": "mondo", "ja": "世界" }
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr05/app.zig
const std = @import("std"); const config = @import("config"); const semver = std.SemanticVersion.parse(config.version) catch unreachable; extern fn foo_bar() void; pub fn main() !void { if (semver.major < 1) { @compileError("too old"); } std.debug.print("version: {s}\n", .{config.version}); if (config.have_libfoo) { foo_bar(); } }
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr05/README.md
## Options for Conditional Compilation To pass options from the build script and into the project’s Zig code, use the Options step. `zig build -Dversion=1.2.3 --summary all`
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr05/build.zig
const std = @import("std"); pub fn build(b: *std.Build) void { const exe = b.addExecutable(.{ .name = "app", .root_source_file = b.path("app.zig"), .target = b.host, }); const version = b.option([]const u8, "version", "application version string") orelse "0.0.0"; const enable_foo = detectWhetherToEnableLibFoo(); const options = b.addOptions(); options.addOption([]const u8, "version", version); options.addOption(bool, "have_libfoo", enable_foo); exe.root_module.addOptions("config", options); b.installArtifact(exe); } fn detectWhetherToEnableLibFoo() bool { return false; }
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr15/protocol.zig
pub const Header = extern struct { magic: u64, width: u32, height: u32, };
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr15/README.md
## Mutating Source Files in Place `zig build update-protocol --summary all`
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr15/build.zig
const std = @import("std"); pub fn build(b: *std.Build) void { const exe = b.addExecutable(.{ .name = "demo", .root_source_file = b.path("src/main.zig"), }); b.installArtifact(exe); const proto_gen = b.addExecutable(.{ .name = "proto_gen", .root_source_file = b.path("tools/proto_gen.zig"), }); const run = b.addRunArtifact(proto_gen); const generated_protocol_file = run.addOutputFileArg("protocol.zig"); const wf = b.addWriteFiles(); wf.addCopyFileToSource(generated_protocol_file, "src/protocol.zig"); const update_protocol_step = b.step("update-protocol", "update src/protocol.zig to latest"); update_protocol_step.dependOn(&wf.step); } fn detectWhetherToEnableLibFoo() bool { return false; }
0
repos/zig-build-system--0.13.0-examples/projects/pr15
repos/zig-build-system--0.13.0-examples/projects/pr15/src/main.zig
const std = @import("std"); const Protocol = @import("protocol.zig"); pub fn main() !void { const header = try std.io.getStdIn().reader().readStruct(Protocol.Header); std.debug.print("header: {any}\n", .{header}); }
0
repos/zig-build-system--0.13.0-examples/projects/pr15
repos/zig-build-system--0.13.0-examples/projects/pr15/tools/proto_gen.zig
const std = @import("std"); pub fn main() !void { var arena_state = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); const args = try std.process.argsAlloc(arena); if (args.len != 2) fatal("wrong number of arguments", .{}); const output_file_path = args[1]; var output_file = std.fs.cwd().createFile(output_file_path, .{}) catch |err| { fatal("unable to open '{s}': {s}", .{ output_file_path, @errorName(err) }); }; defer output_file.close(); try output_file.writeAll( \\pub const Header = extern struct { \\ magic: u64, \\ width: u32, \\ height: u32, \\}; ); return std.process.cleanExit(); } fn fatal(comptime format: []const u8, args: anytype) noreturn { std.debug.print(format, args); std.process.exit(1); }
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr09/zip.zig
const std = @import("std"); pub fn main() !void { std.debug.print("Hello World!\n", .{}); }
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr09/README.md
## Linking to System Libraries This build script creates a dynamic library from Zig code. `zig test foo.zig` `zig build test --summary all`
0
repos/zig-build-system--0.13.0-examples/projects
repos/zig-build-system--0.13.0-examples/projects/pr09/build.zig
const std = @import("std"); pub fn build(b: *std.Build) void { const exe = b.addExecutable(.{ .name = "zip", .root_source_file = b.path("zip.zig"), .target = b.host, }); exe.linkSystemLibrary("z"); exe.linkLibC(); b.installArtifact(exe); }
0
repos
repos/filez/README.md
# Filez Filez is a very simple tool for receiving and sending files written in the Zig programming language (version is 0.13.0) made to gain better understanding of low level languages and systems programming in general. ## Building At the moment, there is no direct method to download a binary for your system. Therefore, if you wish to utilize this application, you will need to compile it from source. Here are the steps to do so. Clone this repository onto your local machine using the Git Command Line Interface (CLI): ```bash git clone https://github.com/mkashirin/filez ``` Compile a binary using the Zig compiler (the sole valid version of Zig is 0.13.0) by running the following command: ```bash zig build --release="safe" ``` After completing the above steps, the binary will be located in the "zig-out/bin/" directory. That concludes the process. Consider different `zig build` modes for embedded systems. ## Usage The information provided by the `filez help` options describes all the arguments in detail. However, the following is an example of how to use the tool on your local machine only (make sure to make Filez visible to your system first). Open a terminal and execute the following command, specifying the path to the file that you wish to process: ```bash filez \ --action="dispatch" \ --fdpath="/absolute/path/to/file.ext" \ --host="127.0.0.1" \ --port="8080" \ --password="abcd1234" ``` Then, open a second terminal instance and execute the following command, specifying your own path to the directory where you want to store the received file: ```bash filez \ --action="receive" \ --fdpath="/absolute/path/to/directory/" \ --host="127.0.0.1" \ --port="8080" \ --password="abcd1234" ``` **Remember**, the file size must not exceed the maximum of 8 kilobytes. ## Note Devises to be communicating with files must have ability to ping each other.
0
repos
repos/filez/build.zig.zon
.{ .name = "filez", .version = "0.2.0", .paths = .{ "", }, }
0
repos
repos/filez/build.zig
const std = @import("std"); const Build = std.Build; pub fn build(b: *Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); const exe = b.addExecutable(.{ .name = "filez", .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, }); b.installArtifact(exe); const run_cmd = b.addRunArtifact(exe); 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 unit_tests = b.addTest(.{ .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, }); const run_unit_tests = b.addRunArtifact(unit_tests); const test_step = b.step("test", "Run unit tests"); test_step.dependOn(&run_unit_tests.step); }
0
repos/filez
repos/filez/src/main.zig
const std = @import("std"); const mem = std.mem; const process = std.process; const Allocator = mem.Allocator; const actions = @import("actions.zig"); const config = @import("config.zig"); const socket = @import("socket.zig"); pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); const allocator = arena.allocator(); defer arena.deinit(); run(allocator) catch |err| { config.log( .err, "Could not run the application due to the following error: {s}", .{@errorName(err)}, ); std.process.exit(1); }; } /// This function, in fact, runs the application. It processes the command /// line arguments into the `socket.ActionOptions` struct which then gets /// fed to the `actions.receive()` or `actions.dispatch()`. fn run(arena: Allocator) !void { var args = try process.argsWithAllocator(arena); defer args.deinit(); // This hash map will serve as a temporary storage for the argumnets. var args_map = std.StringHashMap([]const u8).init(arena); defer args_map.deinit(); var help_flag = false; var args_count: usize = 1; while (args.next()) |arg| : (args_count += 1) { if (mem.eql(u8, arg, "help")) { // Display the help message if command is "help". help_flag = true; config.log(.info, "{s}\n", .{config.help_message}); return; } else if (args_count > 1 and args_count <= 6) { // Otherwise continue iterating until arguments count does not // exceed 6. var arg_iter = mem.splitScalar(u8, arg, '='); // Exclude "--" at the start of an argument name. const name = blk: { const arg_passed = arg_iter.next().?[2..]; for (config.args_names) |arg_name| { if (mem.eql(u8, arg_passed, arg_name)) { break :blk arg_passed; } } else return error.InvalidArgument; }; const value = arg_iter.next().?; try args_map.put(name, value); } } // Tell the user if the input is incorrect. if ((args_count - 1 != 6 and help_flag != true) or args_count < 2) { config.log(.info, "{s}\n", .{config.incorr_input_res}); return error.InvalidInput; } var options = socket.ActionOptions.initFromArgs(&args_map); defer options.deinit(); const action = options.parseAction(); if (action == .dispatch) { try actions.dispatch(arena, &options); } else if (action == .receive) { try actions.receive(arena, &options); } }
0
repos/filez
repos/filez/src/actions.zig
const std = @import("std"); const log = std.log; const net = std.net; const Allocator = std.mem.Allocator; const config = @import("config.zig"); const socket = @import("socket.zig"); /// Dispatches the file to the host with port specified in the `ActionConfig` /// passed. pub fn dispatch( arena: Allocator, action_options: *socket.ActionOptions, ) !void { // The `std.net.Address` needs to be parsed at first to accept any TCP // converseur. But first `action_options` must become varibale in order to // be mutable. var options_variable = action_options; const address = try net.Address.parseIp( options_variable.host, try options_variable.parsePort(), ); config.log(.info, "Listening on the {}...\n", .{address}); var server = try address.listen(.{ .reuse_port = true }); // Accept incoming connection and acquire the stream. const connection = try server.accept(); config.log(.info, "{} connected. Transmitting file...\n", .{address}); const stream = connection.stream; defer stream.close(); const writer = stream.writer(); // Initialize the `socket.SocketBuffer` based on the `ActionConfig`. var socket_buffer = try socket.SocketBuffer.initFromOptions( arena, options_variable, ); defer socket_buffer.deinit(); // Write the data into the socket and store the number of bytes written. const bytes_written = try socket_buffer.writeIntoStream(writer); config.log( .info, "File successfully transmitted ({} bytes written).\n", .{bytes_written}, ); } /// Connects to the dispatching peer and saves the addressed file into the /// directory specified in the `buffer.ActionOptions`. pub fn receive( arena: Allocator, action_options: *socket.ActionOptions, ) !void { // The `std.net.Address` needs to be parsed at first to connect to any TCP // converseur. But first `action_options` must become varibale in order to // be mutable. var options_variable = action_options; const address = try std.net.Address.parseIp( options_variable.host, try options_variable.parsePort(), ); // Connect to the dispatcher via TCP. const stream = try std.net.tcpConnectToAddress(address); defer stream.close(); config.log(.info, "Connected to {}. Receiving file...\n", .{address}); // Reader of the stream allows to read from a socket. const reader = stream.reader(); // Buffer automatically fills it's fields based on the incoming data. var socket_buffer = try socket.SocketBuffer.initFromStream( arena, reader, ); defer socket_buffer.deinit(); // The following statement insures that passwords for server and client // sides are equal. const password_buffer: []const u8 = socket_buffer.password; if (!std.mem.eql(u8, options_variable.password, password_buffer)) return error.PasswordMismatch; // Finally, the received data gets written into the file placed in the // specified directory. try socket_buffer.writeContentsIntoFile( options_variable.fdpath, &socket_buffer.contents, ); config.log(.info, "file successfully received.", .{}); }
0
repos/filez
repos/filez/src/config.zig
const std = @import("std"); pub const help_message = \\Filez is a minimalistic LAN file buffer. It allows you transceive your \\files over TCP until your machines have access to each other's ports. \\ \\Usage: filez [arguments] \\ \\Example: \\ \\ filez \ \\ --action="receive" \ \\ --fdpath="/absolute/path/to/directory/" \ \\ --host="127.0.0.1" \ \\ --port="8080" \ \\ --password="pass1234" \\ \\You can only receive or dispatch a file at a time specifying \\`--action="receive"` or `--action="dispatch"` correspondingly. Also if you \\are receiving the `fdpath` parameter should lead to the directory where \\the file should be saved, but if you are dispatching `fdpath` should lead \\to the file to be sent including the extension. \\ \\Commands: \\ \\ help Display this message and exit. \\ \\Arguments: \\ \\ --action <action> Receive or dispatch file. \\ --fdpath <string> Absolute path to the file or directory. \\ --host <string> Host to be listened on/connected to. \\ --port <u16> Port to be listened on/connected to. \\ --password <string> Password to be matched. \\ \\Note that every argument **must** be connected to it's value by "=". ; pub const incorr_input_res = \\The input you have provided is incorrect and can not be parsed. Please \\check the prompt and try again or use "help" to see the available \\options. ; pub const args_names: [5][]const u8 = .{ "action", "fdpath", "host", "port", "password", }; pub const Prefix = enum { info, err }; pub fn log( comptime prefix: Prefix, comptime format: []const u8, args: anytype, ) void { std.debug.lockStdErr(); defer std.debug.unlockStdErr(); const stderr = std.io.getStdErr().writer(); const app_name = "Filez"; nosuspend stderr.print( app_name ++ " (" ++ @tagName(prefix) ++ "): " ++ format, args, ) catch return; }
0
repos/filez
repos/filez/src/socket.zig
const std = @import("std"); const meta = std.meta; const net = std.net; const Allocator = std.mem.Allocator; pub const ActionOptions = struct { /// This struct stores command line arguments and provides the action /// options which should be passed to the `SocketBuffer`, `receive()` and /// `dispatch()` functions. const Self = @This(); pub const Action = enum { dispatch, receive }; action: []const u8, fdpath: []const u8, host: []const u8, port: []const u8, password: []const u8, /// Initilizes action options struct using a hash map of CLI arguments. pub fn initFromArgs( args_map: *std.StringHashMap([]const u8), ) Self { var new: Self = undefined; const fields = meta.fields(@This()); inline for (fields) |field| { const arg_value = args_map.get(field.name); @field(new, field.name) = arg_value.?; } return new; } /// Returns an enum based on the active action field. pub fn parseAction(self: *Self) Action { return meta.stringToEnum(Action, self.action).?; } /// Returns a `u16` integer to passed as a port to the further functions. pub fn parsePort(self: *Self) !u16 { return try std.fmt.parseInt(u16, self.port, 10); } /// Frees all the memory been allocated to store the options. pub fn deinit(self: *Self) void { self.* = undefined; } }; pub const SocketBuffer = struct { /// This structure is the core of the application. As both `receive()` and /// `dispatch()` simply manipulate data coming from and going into the /// socket, it would be appropriate to transfer all responsibility for this /// functionality to a separate socket management structure. Therefore, the /// `SocketBuffer`, which serves as an interface for manipulating socket /// data, is introduced. const Self = @This(); fdpath: []u8, password: []u8, contents: []u8, /// Initializes a new `SocketBuffer` based on the `ActionConfig` data. pub fn initFromOptions( arena: Allocator, options: *ActionOptions, ) !Self { return .{ .fdpath = try arena.dupe(u8, options.fdpath), .password = try arena.dupe(u8, options.password), .contents = try readFileContents(arena, options.fdpath), }; } /// Initializes a new `SocketBuffer` based on the data coming from the /// connection stream. pub fn initFromStream( arena: Allocator, stream_reader: net.Stream.Reader, ) !Self { // This loop has to be inline to make use of a comptime known // `SocketBuffer` field names. var new: Self = undefined; const fields = meta.fields(@This()); inline for (fields) |field| { // This `list` serves as a buffer, since the object with writer is // required to be passed as an argument to the // `net.Stream.Reader.streamUntilDelimiter()` function. var list = std.ArrayList(u8).init(arena); const list_writer = list.writer(); if (!std.mem.eql(u8, field.name, "contents")) { try stream_reader.streamUntilDelimiter( list_writer, '\n', null, ); } else { // Reading the file contents with maximum size of 8192 bits. try stream_reader.readAllArrayList(&list, 8192); } // The data read from the stream must be duped since `list.items` // contains a slice. (Slice is essentially a pointer to memory // which can be corrupted due to the function return.) @field(new, field.name) = try arena.dupe(u8, list.items); // Temporary buffer must be deinitialized to be flused and for the // resources allocated to be freed. list.deinit(); } return new; } /// Writes the conetents stored in the `self` into the file. pub fn writeContentsIntoFile( self: *Self, dir_absolute_path: []const u8, contents: *[]u8, ) !void { var dir = try std.fs.openDirAbsolute( dir_absolute_path, .{ .no_follow = true }, ); defer dir.close(); var file_path_iterator = std.mem.splitBackwardsScalar( u8, @as([]const u8, self.fdpath), '/', ); // Acquire the name of the file received. const file_name = file_path_iterator.first(); var file = try dir.createFile(file_name, .{ .read = true }); defer file.close(); // Write into file. try file.seekTo(0); try file.writeAll(contents.*); try file.seekTo(0); } /// Writes the data stored in `self` into the connection stream. pub fn writeIntoStream( self: *Self, stream_writer: net.Stream.Writer, ) !usize { // Store the size of the data being written in bytes. var bytes_written: usize = 0; const fields = meta.fields(@This()); inline for (fields) |field| { const value = &@field(self, field.name); bytes_written += try stream_writer.write(value.*); try stream_writer.writeByte('\n'); bytes_written += 1; } return bytes_written; } /// Deinitializes the existing `SocketBuffer` discarding all the memory /// that was allocated for it to prevent memory leaks. pub fn deinit(self: *Self) void { self.* = undefined; } /// Utility function to read the contents of the file specified. fn readFileContents( arena: Allocator, file_absolute_path: []const u8, ) ![]u8 { const file = try std.fs.openFileAbsolute(file_absolute_path, .{}); defer file.close(); try file.seekTo(0); const contents = try file.readToEndAlloc(arena, 8192); return contents; } };
0
repos
repos/edsm-in-zig-demo-2/LICENSE.txt
Copyright © 2022 Evgenii Zhiganov <[email protected]> This work is free. You can redistribute it and/or modify it under the terms of the Do What The Fuck You Want To Public License, Version 2, as published by Sam Hocevar: DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE Version 2, December 2004 Copyright (C) 2004 Sam Hocevar <[email protected]> Everyone is permitted to copy and distribute verbatim or modified copies of this license document, and changing it is allowed as long as the name is changed. DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. You just DO WHAT THE FUCK YOU WANT TO.
0
repos
repos/edsm-in-zig-demo-2/README.md
# echo-server and echo-client To build: ``` /opt/zig-0.14/zig build ``` ## Preliminary notes First of all - this is **NOT** so called hierarchical state machines (nested states and whatnots) implementation. It is much more convenient to deal with *hierarchy of* (relatively simple) *interacting state machines* rather than with a single huge machine having *hierarchy of states*. ### Events This is epoll based implementation, so in essence events are: * `EPOLLIN` (`read()`/`accept()` will not block) * `EPOLLOUT` (`write()` will not block) * `EPOLLERR/EPOLLHUP/EPOLLRDHUP` Upon returning from `epoll_wait()` these events are transformed into messages and then delivered to destination state machine (owner of a channel, see below). Besides messages triggered by 'external world', there are internal messages - machines can send them to each other directly (see `engine/architecture.txt` in the sources). ### Event sources (channels) Event source is anything representable by file descriptor and thus can be used with `epoll` facility: * signals (`EPOLLIN` only) * timers (`EPOLLIN` only) * sockets, terminals, serial devices, fifoes etc. * file system (via `inotify` facility) Each event source has an owner (it is some state machine). ### Events/messages notation * `M0, M1, M2 ...`: internal messages * `S0, S1, S2 ...`: signals * `T0, T1, T2 ...`: timers * `DO, D1, D2 `: i/o ('can read', 'can write', 'error') * `F0, F1, F2 ...`: file system ('writable file was closed' and alike) These 'tags' are used in the names of state machines 'methods', for example: ```zig fn workD2(me: *StageMachine, _: ?*StageMachine, _: ?*anyopaque) void { var pd = utils.opaqPtrTo(me.data, *RxData); me.msgTo(me, M0_IDLE, null); me.msgTo(pd.customer, M2_FAIL, null); } ``` ### Enter/Leave functions Each state can have enter/leave functions, which can be used to perform some action in addition to 'regular' actions. For example, `RX` machine (see below) stops timeout timer when leaving `WORK` state: ```zig fn workLeave(me: *StageMachine) void { var pd = utils.opaqPtrTo(me.data, *RxData); pd.tm0.disable(&me.md.eq) catch unreachable; } ``` ## Server architecture The server consists of 4 kinds of state machines: * LISTENER (one instance) * WORKER (many instances, kept in a pool when idle) * RX/TX (many instances, also kept in pools) Thus we have 3-level hierarchy here. ### LISTENER Listener is responsible for accepting incoming connections and also for managing resources, associated with connected client (memory and file descriptor). Has 2 states: * INIT * enter: prepare channels * `M0`: goto `WORK` state * leave: nothing * WORK * enter: enable channels * `D0`: accept connection, take WORKER from the pool, send it `M1` with ptr to client as payload * `M0`: close connection, free memory * `S0` (SIGINT): stop event loop * `S1` (SIGTERM): stop event loop * leave: say goodbye ### WORKER Worker is a machine which implements message flow pattern. Has 5 states: * INIT * enter: send `M0` to self * `M0`: goto `IDLE` state * leave: nothing * IDLE * enter: put self into the pool * `M1`: store information about client * `M0`: goto `RECV` state * leave: nothing * RECV * enter: get `RX` machine from pool, send it `M1` with ptr to context * `M0`: goto `SEND` state * `M1`: send `M0` to self * `M2`: goto `FAIL` state * leave: nothing * SEND * enter: get `TX` machine from pool, send it `M1` with ptr to context * `M0`: goto `RECV` state * `M1`: send `M0` to self * `M2`: goto `FAIL` state * leave: nothing * FAIL * enter: send `M0` to self, `M0` to `LISTENER` with ptr to client * `M0`: goto `IDLE` state * leave: nothing ### RX Rx is a machine which knows how to read data. Has 3 states: * INIT * enter: init timer and i/o channels, send `M0` to self * `M0`: goto `IDLE` state * leave: nothing * IDLE * enter: put self into the pool * `M0`: goto `WORK` state * `M1`: store context given by requester * leave: nothing * WORK * enter: enable i/o and timer * `D0`: read data, send `M1` to requester when done * `D2`: send `M0` to self, `M2` to requester * `T0` (timeout): send `M0` to self, `M2` to requester * `M0`: goto `IDLE` state * leave: stop timer ### TX Tx is a machine which knows how to write data. Also has 3 states: * INIT * enter: init i/o channel * `M0`: goto `IDLE` state * leave: nothing * IDLE * enter: put self into the pool * `M0`: goto `WORK` state * `M1`: store context given by requester * leave: nothing * WORK * enter: enable i/o * `D1`: write data, send `M1` to requester when done * `D2`: send `M0` to self, `M2` to requester * `M0`: goto `IDLE` state * leave: nothing ### Examples of workflow * client connected (note `D0`) ``` LISTENER-1 @ WORK got 'D0' from OS WORKER-4 @ IDLE got 'M1' from LISTENER-1 WORKER-4 @ IDLE got 'M0' from SELF RX-4 @ IDLE got 'M1' from WORKER-4 RX-4 @ IDLE got 'M0' from SELF ``` * client suddenly disconnected (note `D2`) ``` RX-4 @ IDLE got 'M0' from SELF RX-4 @ WORK got 'D2' from OS RX-4 @ WORK got 'M0' from SELF WORKER-4 @ RECV got 'M2' from RX-4 WORKER-4 @ FAIL got 'M0' from SELF LISTENER-1 @ WORK got 'M0' from WORKER-4 ``` * normal request-reply (note `D0` and `D1`) ``` RX-4 @ IDLE got 'M0' from SELF RX-4 @ WORK got 'D0' from OS <<< 4 bytes: { 49, 50, 51, 10 } RX-4 @ WORK got 'M0' from SELF WORKER-4 @ RECV got 'M1' from RX-4 WORKER-4 @ RECV got 'M0' from SELF TX-4 @ IDLE got 'M1' from WORKER-4 TX-4 @ IDLE got 'M0' from SELF TX-4 @ WORK got 'D1' from OS TX-4 @ WORK got 'M0' from SELF WORKER-4 @ SEND got 'M1' from TX-4 WORKER-4 @ SEND got 'M0' from SELF ``` * request timeout (note `T0`) ``` RX-4 @ IDLE got 'M0' from SELF RX-4 @ WORK got 'T0' from OS RX-4 @ WORK got 'M0' from SELF WORKER-4 @ RECV got 'M2' from RX-4 WORKER-4 @ FAIL got 'M0' from SELF LISTENER-1 @ WORK got 'M0' from WORKER-4 ``` ## Client architecture The client also consists of 4 kinds of state machines: * TERMINATOR (one instance) * WORKER (many instances) * RX/TX (many instances, in pools) However here we have only 2-level machine hierarchy because `TERMINATOR` is stand-alone machine and it's only purpose is catching `SIGTERM` and `SIGINT`. ### TERMINATOR * INIT * enter: init channels, send 'M0' to self * `M0`: goto `IDLE` state * leave: nothing * IDLE * enter: enable channels (`SIGINT` and `SIGTERM`) * `S0` and `S1`: stop event loop * leave: nothing ### WORKER * INIT * enter: init io and timer channels, send `M0` to self * `M0`: goto `CONN` state * leave: nothing * CONN * enter: take `TX` machine, start connect, send `M1` to `TX` * `M1`: send `M0` to self (connection Ok) * `M2`: send `M3` to self (can not connect) * `M0`: goto `SEND` state * `M3`: goto `WAIT` state * leave: nothing * SEND * enter: prepare request, take `TX` machine, send it `M1` * `M1`: send `M0` to self * `M2`: send `M3` to self * `M0`: goto `RECV` state * `M3`: goto `WAIT` state * leave: nothing * RECV * enter: take `RX` machine, send it `M1` * `M1`: send `M0` to self * `M2`: send `M3` to self * `M0`: goto `TWIX` state * `M3`: goto `WAIT` state * leave: nothing * TWIX * enter: start timer (500 msec) * `T0`: goto `SEND` state * leave: nothing * WAIT * enter: start timer (5000 msec) * `T0`: goto `CONN` state * leave: nothing ### Examples of workflow * successful connection ``` TX-1 @ IDLE got 'M1' from WORKER-1 TX-1 @ IDLE got 'M0' from SELF TX-1 @ WORK got 'D1' from OS TX-1 @ WORK got 'M0' from SELF WORKER-1 @ CONN got 'M1' from TX-1 WORKER-1 : connected to '127.0.0.1:3333' WORKER-1 @ CONN got 'M0' from SELF ``` * failed connection ``` TX-1 @ IDLE got 'M1' from WORKER-1 TX-1 @ IDLE got 'M0' from SELF TX-1 @ WORK got 'D2' from OS TX-1 @ WORK got 'M0' from SELF WORKER-1 @ CONN got 'M2' from TX-1 WORKER-1 : can not connect to '127.0.0.1:3333': error.ConnectionRefused WORKER-1 @ CONN got 'M3' from SELF ``` * request-reply ``` TX-1 @ IDLE got 'M1' from WORKER-1 TX-1 @ IDLE got 'M0' from SELF TX-1 @ WORK got 'D1' from OS TX-1 @ WORK got 'M0' from SELF WORKER-1 @ SEND got 'M1' from TX-1 WORKER-1 @ SEND got 'M0' from SELF RX-1 @ IDLE got 'M1' from WORKER-1 RX-1 @ IDLE got 'M0' from SELF RX-1 @ WORK got 'D0' from OS RX-1 @ WORK got 'M0' from SELF WORKER-1 @ RECV got 'M1' from RX-1 reply: WORKER-1-7 ``` ## Links * [Event driven state machine](https://en.wikipedia.org/wiki/Event-driven_finite-state_machine) * [Reactor pattern](https://en.wikipedia.org/wiki/Reactor_pattern) * [Modeling Software with Finite State Machines](http://www.stateworks.com/book/book/)
0
repos
repos/edsm-in-zig-demo-2/build.zig
const std = @import("std"); pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); const apps = [_][]const u8{"server", "client"}; inline for (apps) |app| { const exe = b.addExecutable(.{ .name = app, .root_source_file = b.path("src/" ++ app ++ ".zig"), .target = target, .optimize = optimize, .single_threaded = true, .strip = true, }); b.installArtifact(exe); } }
0
repos/edsm-in-zig-demo-2
repos/edsm-in-zig-demo-2/src/machine-pool.zig
const std = @import("std"); const edsm = @import("engine/edsm.zig"); const StageMachine = edsm.StageMachine; const Allocator = std.mem.Allocator; pub const MachinePool = struct { const Self = @This(); const MachinePtrList = std.ArrayList(*StageMachine); allocator: Allocator, list: MachinePtrList, pub fn init(a: Allocator, cap: usize) !Self { return Self { .allocator = a, .list = try MachinePtrList.initCapacity(a, cap), }; } pub fn put(self: *Self, sm: *StageMachine) !void { const p = try self.list.addOne(); p.* = sm; } pub fn get(self: *Self) ?*StageMachine { return self.list.popOrNull(); } };
0
repos/edsm-in-zig-demo-2
repos/edsm-in-zig-demo-2/src/server.zig
const std = @import("std"); const print = std.debug.print; const Allocator = std.mem.Allocator; const MessageDispatcher = @import("engine/message-queue.zig").MessageDispatcher; const MachinePool = @import("machine-pool.zig").MachinePool; const Listener = @import("server-sm/listener.zig").Listener; const Worker = @import("server-sm/worker.zig").Worker; const RxPotBoy = @import("common-sm/rx.zig").RxPotBoy; const TxPotBoy = @import("common-sm/tx.zig").TxPotBoy; pub fn main() !void { const max_clients = 4; var gpa = std.heap.GeneralPurposeAllocator(.{}){}; //defer print("leakage?.. {}\n", .{gpa.deinit()}); const allocator = gpa.allocator(); var md = try MessageDispatcher.onStack(allocator, 5); var worker_pool = try MachinePool.init(allocator, max_clients); var rx_pool = try MachinePool.init(allocator, max_clients); var tx_pool = try MachinePool.init(allocator, max_clients); var i: u32 = 0; while (i < max_clients) : (i += 1) { var rx = try RxPotBoy.onHeap(allocator, &md, &rx_pool); try rx.run(); } i = 0; while (i < max_clients) : (i += 1) { var tx = try TxPotBoy.onHeap(allocator, &md, &tx_pool); try tx.run(); } i = 0; while (i < max_clients) : (i += 1) { var worker = try Worker.onHeap(allocator, &md, &worker_pool, &rx_pool, &tx_pool); try worker.run(); } var reception = try Listener.onHeap(allocator, &md, 3333, &worker_pool); try reception.run(); try md.loop(); md.eq.fini(); }
0
repos/edsm-in-zig-demo-2
repos/edsm-in-zig-demo-2/src/utils.zig
pub fn opaqPtrTo(ptr: ?*anyopaque, comptime T: type) T { return @ptrCast(@alignCast(ptr)); }
0
repos/edsm-in-zig-demo-2
repos/edsm-in-zig-demo-2/src/client.zig
const std = @import("std"); const print = std.debug.print; const Allocator = std.mem.Allocator; const page_allocator = std.heap.page_allocator; const ArenaAllocator = std.heap.ArenaAllocator; const MessageDispatcher = @import("engine/message-queue.zig").MessageDispatcher; const MachinePool = @import("machine-pool.zig").MachinePool; const Terminator = @import("client-sm/terminator.zig").Terminator; const Worker = @import("client-sm/worker.zig").Worker; const RxPotBoy = @import("common-sm/rx.zig").RxPotBoy; const TxPotBoy = @import("common-sm/tx.zig").TxPotBoy; pub fn main() !void { const nconnections = 4; var arena = ArenaAllocator.init(page_allocator); defer arena.deinit(); const allocator = arena.allocator(); var md = try MessageDispatcher.onStack(allocator, 5); var rx_pool = try MachinePool.init(allocator, nconnections); var tx_pool = try MachinePool.init(allocator, nconnections); var i: u32 = 0; while (i < nconnections) : (i += 1) { var rx = try RxPotBoy.onHeap(allocator, &md, &rx_pool); try rx.run(); } i = 0; while (i < nconnections) : (i += 1) { var tx = try TxPotBoy.onHeap(allocator, &md, &tx_pool); try tx.run(); } i = 0; while (i < nconnections) : (i += 1) { var w = try Worker.onHeap(allocator, &md, &rx_pool, &tx_pool, "127.0.0.1", 3333); try w.run(); } var t = try Terminator.onHeap(allocator, &md); try t.run(); try md.loop(); md.eq.fini(); }
0
repos/edsm-in-zig-demo-2/src
repos/edsm-in-zig-demo-2/src/common-sm/context.zig
const NeedMoreData = *const fn(buf: []u8) bool; pub const IoContext = struct { fd: i32, buf: []u8, cnt: usize, needMore: NeedMoreData, timeout: u32, };
0
repos/edsm-in-zig-demo-2/src
repos/edsm-in-zig-demo-2/src/common-sm/tx.zig
const std = @import("std"); const os = std.os; const mem = std.mem; const math = std.math; const print = std.debug.print; const Allocator = std.mem.Allocator; const mq = @import("../engine/message-queue.zig"); const MessageDispatcher = mq.MessageDispatcher; const MessageQueue = MessageDispatcher.MessageQueue; const Message = MessageQueue.Message; const esrc = @import("../engine//event-sources.zig"); const EventSourceKind = esrc.EventSourceKind; const EventSourceSubKind = esrc.EventSourceSubKind; const EventSource = esrc.EventSource; const edsm = @import("../engine/edsm.zig"); const StageMachine = edsm.StageMachine; const Stage = StageMachine.Stage; const Reflex = Stage.Reflex; const StageList = edsm.StageList; const MachinePool = @import("../machine-pool.zig").MachinePool; const Context = @import("../common-sm/context.zig").IoContext; const utils = @import("../utils.zig"); pub const TxPotBoy = struct { const M0_IDLE = Message.M0; const M0_WORK = Message.M0; const M1_DONE = Message.M1; const M2_FAIL = Message.M2; var number: u16 = 0; const TxData = struct { my_pool: *MachinePool, io0: EventSource, ctx: *Context, customer: ?*StageMachine, }; pub fn onHeap(a: Allocator, md: *MessageDispatcher, tx_pool: *MachinePool) !*StageMachine { number += 1; var me = try StageMachine.onHeap(a, md, "TX", number); try me.addStage(Stage{.name = "INIT", .enter = &initEnter, .leave = null}); try me.addStage(Stage{.name = "IDLE", .enter = &idleEnter, .leave = null}); try me.addStage(Stage{.name = "WORK", .enter = &workEnter, .leave = null}); var init = &me.stages.items[0]; var idle = &me.stages.items[1]; var work = &me.stages.items[2]; init.setReflex(.sm, Message.M0, Reflex{.transition = idle}); idle.setReflex(.sm, Message.M1, Reflex{.action = &idleM1}); idle.setReflex(.sm, Message.M0, Reflex{.transition = work}); work.setReflex(.io, Message.D1, Reflex{.action = &workD1}); work.setReflex(.io, Message.D2, Reflex{.action = &workD2}); work.setReflex(.sm, Message.M0, Reflex{.transition = idle}); me.data = me.allocator.create(TxData) catch unreachable; var pd = utils.opaqPtrTo(me.data, *TxData); pd.my_pool = tx_pool; return me; } fn initEnter(me: *StageMachine) void { var pd = utils.opaqPtrTo(me.data, *TxData); me.initIo(&pd.io0); me.msgTo(me, M0_IDLE, null); } fn idleEnter(me: *StageMachine) void { var pd = utils.opaqPtrTo(me.data, *TxData); pd.ctx = undefined; pd.customer = null; pd.my_pool.put(me) catch unreachable; } // message from 'customer' - 'transfer data' fn idleM1(me: *StageMachine, src: ?*StageMachine, dptr: ?*anyopaque) void { var pd = utils.opaqPtrTo(me.data, *TxData); pd.customer = src; pd.ctx = utils.opaqPtrTo(dptr, *Context); pd.io0.id = pd.ctx.fd; me.msgTo(me, M0_WORK, null); } fn workEnter(me: *StageMachine) void { var pd = utils.opaqPtrTo(me.data, *TxData); pd.ctx.cnt = pd.ctx.buf.len; pd.io0.enableOut(&me.md.eq) catch unreachable; } fn workD1(me: *StageMachine, src: ?*StageMachine, dptr: ?*anyopaque) void { _ = src; const io = utils.opaqPtrTo(dptr, *EventSource); var pd = utils.opaqPtrTo(me.data, *TxData); if (0 == pd.ctx.cnt) { // it was request for asynchronous connect me.msgTo(me, M0_IDLE, null); me.msgTo(pd.customer, M1_DONE, null); return; } const bw = std.posix.write(io.id, pd.ctx.buf[pd.ctx.buf.len - pd.ctx.cnt..pd.ctx.buf.len]) catch { me.msgTo(me, M0_IDLE, null); me.msgTo(pd.customer, M2_FAIL, null); return; }; pd.ctx.cnt -= bw; if (pd.ctx.cnt > 0) { pd.io0.enableOut(&me.md.eq) catch unreachable; return; } me.msgTo(me, M0_IDLE, null); me.msgTo(pd.customer, M1_DONE, null); } fn workD2(me: *StageMachine, src: ?*StageMachine, dptr: ?*anyopaque) void { _ = src; _ = dptr; const pd = utils.opaqPtrTo(me.data, *TxData); me.msgTo(me, M0_IDLE, null); me.msgTo(pd.customer, M2_FAIL, null); } };
0
repos/edsm-in-zig-demo-2/src
repos/edsm-in-zig-demo-2/src/common-sm/rx.zig
const std = @import("std"); const os = std.os; const mem = std.mem; const math = std.math; const print = std.debug.print; const Allocator = std.mem.Allocator; const mq = @import("../engine/message-queue.zig"); const MessageDispatcher = mq.MessageDispatcher; const MessageQueue = MessageDispatcher.MessageQueue; const Message = MessageQueue.Message; const esrc = @import("../engine/event-sources.zig"); const EventSourceKind = esrc.EventSourceKind; const EventSourceSubKind = esrc.EventSourceSubKind; const EventSource = esrc.EventSource; const edsm = @import("../engine/edsm.zig"); const StageMachine = edsm.StageMachine; const Stage = StageMachine.Stage; const Reflex = Stage.Reflex; const StageList = edsm.StageList; const MachinePool = @import("../machine-pool.zig").MachinePool; const Context = @import("../common-sm/context.zig").IoContext; const utils = @import("../utils.zig"); pub const RxPotBoy = struct { const M0_IDLE = Message.M0; const M0_WORK = Message.M0; const M1_DONE = Message.M1; const M2_FAIL = Message.M2; var number: u16 = 0; const RxData = struct { my_pool: *MachinePool, io0: EventSource, tm0: EventSource, ctx: *Context, customer: ?*StageMachine, }; pub fn onHeap(a: Allocator, md: *MessageDispatcher, rx_pool: *MachinePool) !*StageMachine { number += 1; var me = try StageMachine.onHeap(a, md, "RX", number); try me.addStage(Stage{.name = "INIT", .enter = &initEnter, .leave = null}); try me.addStage(Stage{.name = "IDLE", .enter = &idleEnter, .leave = null}); try me.addStage(Stage{.name = "WORK", .enter = &workEnter, .leave = &workLeave}); var init = &me.stages.items[0]; var idle = &me.stages.items[1]; var work = &me.stages.items[2]; init.setReflex(.sm, Message.M0, Reflex{.transition = idle}); idle.setReflex(.sm, Message.M1, Reflex{.action = &idleM1}); idle.setReflex(.sm, Message.M0, Reflex{.transition = work}); work.setReflex(.io, Message.D0, Reflex{.action = &workD0}); work.setReflex(.io, Message.D2, Reflex{.action = &workD2}); work.setReflex(.tm, Message.T0, Reflex{.action = &workT0}); work.setReflex(.sm, Message.M0, Reflex{.transition = idle}); me.data = me.allocator.create(RxData) catch unreachable; var pd = utils.opaqPtrTo(me.data, *RxData); pd.my_pool = rx_pool; return me; } fn initEnter(me: *StageMachine) void { var pd = utils.opaqPtrTo(me.data, *RxData); me.initTimer(&pd.tm0, Message.T0) catch unreachable; me.initIo(&pd.io0); me.msgTo(me, M0_IDLE, null); } fn idleEnter(me: *StageMachine) void { var pd = utils.opaqPtrTo(me.data, *RxData); pd.ctx = undefined; pd.customer = null; pd.my_pool.put(me) catch unreachable; } // message from 'customer' - 'bring me data' fn idleM1(me: *StageMachine, src: ?*StageMachine, dptr: ?*anyopaque) void { var pd = utils.opaqPtrTo(me.data, *RxData); pd.customer = src; pd.ctx = utils.opaqPtrTo(dptr, *Context); pd.io0.id = pd.ctx.fd; me.msgTo(me, M0_WORK, null); } fn workEnter(me: *StageMachine) void { var pd: *RxData = @ptrCast(@alignCast(me.data)); pd.ctx.cnt = 0; const to = if (0 == pd.ctx.timeout) 1000 else pd.ctx.timeout; pd.tm0.enable(&me.md.eq, .{to}) catch unreachable; pd.io0.enable(&me.md.eq, .{}) catch unreachable; } fn workD0(me: *StageMachine, src: ?*StageMachine, dptr: ?*anyopaque) void { _ = src; var io = utils.opaqPtrTo(dptr, *EventSource); var pd = utils.opaqPtrTo(me.data, *RxData); const ba = io.info.io.bytes_avail; if (0 == ba) { me.msgTo(me, M0_IDLE, null); me.msgTo(pd.customer, M2_FAIL, null); return; } const br = std.posix.read(io.id, pd.ctx.buf[pd.ctx.cnt..]) catch { me.msgTo(me, M0_IDLE, null); me.msgTo(pd.customer, M2_FAIL, null); return; }; pd.ctx.cnt += br; if (pd.ctx.needMore(pd.ctx.buf[0..pd.ctx.cnt])) { io.enable(&me.md.eq, .{}) catch unreachable; return; } me.msgTo(me, M0_IDLE, null); me.msgTo(pd.customer, M1_DONE, null); } fn workD2(me: *StageMachine, src: ?*StageMachine, data: ?*anyopaque) void { _ = src; _ = data; const pd = utils.opaqPtrTo(me.data, *RxData); me.msgTo(me, M0_IDLE, null); me.msgTo(pd.customer, M2_FAIL, null); } // timeout fn workT0(me: *StageMachine, src: ?*StageMachine, data: ?*anyopaque) void { _ = src; _ = data; const pd = utils.opaqPtrTo(me.data, *RxData); me.msgTo(me, M0_IDLE, null); me.msgTo(pd.customer, M2_FAIL, null); } fn workLeave(me: *StageMachine) void { var pd = utils.opaqPtrTo(me.data, *RxData); pd.tm0.disable(&me.md.eq) catch unreachable; } };
0
repos/edsm-in-zig-demo-2/src
repos/edsm-in-zig-demo-2/src/server-sm/worker.zig
const std = @import("std"); const os = std.os; const mem = std.mem; const math = std.math; const print = std.debug.print; const Allocator = std.mem.Allocator; const mq = @import("../engine/message-queue.zig"); const MessageDispatcher = mq.MessageDispatcher; const MessageQueue = MessageDispatcher.MessageQueue; const Message = MessageQueue.Message; const esrc = @import("../engine//event-sources.zig"); const EventSourceKind = esrc.EventSourceKind; const EventSourceSubKind = esrc.EventSourceSubKind; const EventSource = esrc.EventSource; const edsm = @import("../engine/edsm.zig"); const StageMachine = edsm.StageMachine; const Stage = StageMachine.Stage; const Reflex = Stage.Reflex; const StageList = edsm.StageList; const MachinePool = @import("../machine-pool.zig").MachinePool; const Client = @import("client.zig").Client; const Context = @import("../common-sm/context.zig").IoContext; const utils = @import("../utils.zig"); pub const Worker = struct { const M0_IDLE = Message.M0; const M0_RECV = Message.M0; const M1_WORK = Message.M1; const M0_SEND = Message.M0; const M0_GONE = Message.M0; const M2_FAIL = Message.M2; const max_bytes = 64; var number: u16 = 0; const WorkerData = struct { my_pool: *MachinePool, rx_pool: *MachinePool, tx_pool: *MachinePool, listener: ?*StageMachine, client: ?*Client, request: [max_bytes]u8, // reply: [max_bytes]u8, ctx: Context, }; pub fn onHeap ( a: Allocator, md: *MessageDispatcher, my_pool: *MachinePool, rx_pool: *MachinePool, tx_pool: *MachinePool, ) !*StageMachine { number += 1; var me = try StageMachine.onHeap(a, md, "WORKER", number); try me.addStage(Stage{.name = "INIT", .enter = &initEnter, .leave = null}); try me.addStage(Stage{.name = "IDLE", .enter = &idleEnter, .leave = null}); try me.addStage(Stage{.name = "RECV", .enter = &recvEnter, .leave = null}); try me.addStage(Stage{.name = "SEND", .enter = &sendEnter, .leave = null}); try me.addStage(Stage{.name = "FAIL", .enter = &failEnter, .leave = null}); var init = &me.stages.items[0]; var idle = &me.stages.items[1]; var recv = &me.stages.items[2]; var send = &me.stages.items[3]; var fail = &me.stages.items[4]; init.setReflex(.sm, Message.M0, Reflex{.transition = idle}); idle.setReflex(.sm, Message.M1, Reflex{.action = &idleM1}); idle.setReflex(.sm, Message.M0, Reflex{.transition = recv}); recv.setReflex(.sm, Message.M0, Reflex{.transition = send}); recv.setReflex(.sm, Message.M1, Reflex{.action = &recvM1}); recv.setReflex(.sm, Message.M2, Reflex{.transition = fail}); send.setReflex(.sm, Message.M0, Reflex{.transition = recv}); send.setReflex(.sm, Message.M1, Reflex{.action = &sendM1}); send.setReflex(.sm, Message.M2, Reflex{.transition = fail}); fail.setReflex(.sm, Message.M0, Reflex{.transition = idle}); me.data = me.allocator.create(WorkerData) catch unreachable; var pd = utils.opaqPtrTo(me.data, *WorkerData); pd.my_pool = my_pool; pd.rx_pool = rx_pool; pd.tx_pool = tx_pool; return me; } fn initEnter(me: *StageMachine) void { me.msgTo(me, M0_IDLE, null); } fn idleEnter(me: *StageMachine) void { var pd = utils.opaqPtrTo(me.data, *WorkerData); pd.listener = null; pd.client = null; pd.my_pool.put(me) catch unreachable; } // message from LISTENER (new client) fn idleM1(me: *StageMachine, src: ?*StageMachine, dptr: ?*anyopaque) void { var pd = utils.opaqPtrTo(me.data, *WorkerData); const client = utils.opaqPtrTo(dptr, *Client); pd.listener = src; pd.client = client; pd.ctx.fd = client.fd; me.msgTo(me, M0_RECV, null); } fn myNeedMore(buf: []u8) bool { print("<<< {} bytes: {any}\n", .{buf.len, buf}); if (0x0A == buf[buf.len - 1]) return false; return true; } fn recvEnter(me: *StageMachine) void { var pd = utils.opaqPtrTo(me.data, *WorkerData); const rx = pd.rx_pool.get() orelse { me.msgTo(me, M2_FAIL, null); return; }; pd.ctx.fd = if (pd.client) |c| c.fd else unreachable; pd.ctx.needMore = &myNeedMore; pd.ctx.timeout = 10000; // msec pd.ctx.buf = pd.request[0..]; me.msgTo(rx, M1_WORK, &pd.ctx); } // message from RX machine (success) fn recvM1(me: *StageMachine, src: ?*StageMachine, data: ?*anyopaque) void { const pd = utils.opaqPtrTo(me.data, *WorkerData); _ = pd; _ = data; _ = src; me.msgTo(me, M0_SEND, null); } fn sendEnter(me: *StageMachine) void { var pd = utils.opaqPtrTo(me.data, *WorkerData); const tx = pd.tx_pool.get() orelse { me.msgTo(me, M2_FAIL, null); return; }; pd.ctx.buf = pd.request[0..pd.ctx.cnt]; me.msgTo(tx, M1_WORK, &pd.ctx); } // message from TX machine (success) fn sendM1(me: *StageMachine, src: ?*StageMachine, data: ?*anyopaque) void { _ = src; _ = data; me.msgTo(me, M0_RECV, null); } fn failEnter(me: *StageMachine) void { const pd = utils.opaqPtrTo(me.data, *WorkerData); me.msgTo(me, M0_IDLE, null); me.msgTo(pd.listener, M0_GONE, pd.client); } };
0
repos/edsm-in-zig-demo-2/src
repos/edsm-in-zig-demo-2/src/server-sm/client.zig
pub const Client = struct { fd: i32, aa: i32, // https://github.com/ziglang/zig/issues/13066 };
0
repos/edsm-in-zig-demo-2/src
repos/edsm-in-zig-demo-2/src/server-sm/listener.zig
const std = @import("std"); const os = std.os; const print = std.debug.print; const Allocator = std.mem.Allocator; const mq = @import("../engine/message-queue.zig"); const MessageDispatcher = mq.MessageDispatcher; const MessageQueue = MessageDispatcher.MessageQueue; const Message = MessageQueue.Message; const esrc = @import("../engine//event-sources.zig"); const EventSourceKind = esrc.EventSourceKind; const EventSourceSubKind = esrc.EventSourceSubKind; const EventSource = esrc.EventSource; const edsm = @import("../engine/edsm.zig"); const StageMachine = edsm.StageMachine; const Stage = StageMachine.Stage; const Reflex = Stage.Reflex; const StageList = edsm.StageList; const MachinePool = @import("../machine-pool.zig").MachinePool; const Client = @import("client.zig").Client; const utils = @import("../utils.zig"); pub const Listener = struct { const M0_WORK = Message.M0; const M1_MEET = Message.M1; const M0_GONE = Message.M0; const ListenerData = struct { sg0: EventSource, sg1: EventSource, io0: EventSource, // listening socket port: u16, wpool: *MachinePool, }; pub fn onHeap( a: Allocator, md: *MessageDispatcher, port: u16, wpool: *MachinePool ) !*StageMachine { var me = try StageMachine.onHeap(a, md, "LISTENER", 1); try me.addStage(Stage{.name = "INIT", .enter = &initEnter, .leave = null}); try me.addStage(Stage{.name = "WORK", .enter = &workEnter, .leave = &workLeave}); var init = &me.stages.items[0]; var work = &me.stages.items[1]; init.setReflex(.sm, Message.M0, Reflex{.transition = work}); work.setReflex(.io, Message.D0, Reflex{.action = &workD0}); work.setReflex(.sm, Message.M0, Reflex{.action = &workM0}); work.setReflex(.sg, Message.S0, Reflex{.action = &workS0}); work.setReflex(.sg, Message.S1, Reflex{.action = &workS0}); me.data = me.allocator.create(ListenerData) catch unreachable; var pd = utils.opaqPtrTo(me.data, *ListenerData); pd.port = port; pd.wpool = wpool; return me; } fn initEnter(me: *StageMachine) void { var pd = utils.opaqPtrTo(me.data, *ListenerData); me.initSignal(&pd.sg0, std.posix.SIG.INT, Message.S0) catch unreachable; me.initSignal(&pd.sg1, std.posix.SIG.TERM, Message.S1) catch unreachable; me.initListener(&pd.io0, pd.port) catch unreachable; me.msgTo(me, M0_WORK, null); } fn workEnter(me: *StageMachine) void { var pd = utils.opaqPtrTo(me.data, *ListenerData); pd.io0.enable(&me.md.eq, .{}) catch unreachable; pd.sg0.enable(&me.md.eq, .{}) catch unreachable; pd.sg1.enable(&me.md.eq, .{}) catch unreachable; print("\nHello! I am '{s}' on port {}.\n", .{me.name, pd.port}); } // incoming connection fn workD0(me: *StageMachine, src: ?*StageMachine, dptr: ?*anyopaque) void { _ = src; var pd = utils.opaqPtrTo(me.data, *ListenerData); var io = utils.opaqPtrTo(dptr, *EventSource); io.enable(&me.md.eq, .{}) catch unreachable; const fd = io.acceptClient() catch unreachable; const ptr = me.allocator.create(Client) catch unreachable; var client: *Client = @ptrCast(@alignCast(ptr)); client.fd = fd; // client. const sm = pd.wpool.get(); if (sm) |worker| { me.msgTo(worker, M1_MEET, client); } else { me.msgTo(me, M0_GONE, client); } } // message from worker machine (client gone) // or from self (if no workers were available) fn workM0(me: *StageMachine, src: ?*StageMachine, dptr: ?*anyopaque) void { _ = src; const client = utils.opaqPtrTo(dptr, *Client); std.posix.close(client.fd); me.allocator.destroy(client); } fn workS0(me: *StageMachine, src: ?*StageMachine, dptr: ?*anyopaque) void { _ = src; const sg = utils.opaqPtrTo(dptr, *EventSource); const si = sg.info.sg.sig_info; print("got signal #{} from PID {}\n", .{si.signo, si.pid}); me.msgTo(null, Message.M0, null); } fn workLeave(me: *StageMachine) void { var pd = utils.opaqPtrTo(me.data, *ListenerData); pd.io0.disable(&me.md.eq) catch unreachable; print("Bye! It was '{s}'.\n", .{me.name}); } };
0
repos/edsm-in-zig-demo-2/src
repos/edsm-in-zig-demo-2/src/client-sm/worker.zig
const std = @import("std"); const os = std.os; const mem = std.mem; const net = std.net; const print = std.debug.print; const Allocator = std.mem.Allocator; const mq = @import("../engine/message-queue.zig"); const MessageDispatcher = mq.MessageDispatcher; const MessageQueue = MessageDispatcher.MessageQueue; const Message = MessageQueue.Message; const esrc = @import("../engine//event-sources.zig"); const EventSourceKind = esrc.EventSourceKind; const EventSourceSubKind = esrc.EventSourceSubKind; const EventSource = esrc.EventSource; const edsm = @import("../engine/edsm.zig"); const StageMachine = edsm.StageMachine; const Stage = StageMachine.Stage; const Reflex = Stage.Reflex; const StageList = edsm.StageList; const MachinePool = @import("../machine-pool.zig").MachinePool; const Context = @import("../common-sm/context.zig").IoContext; const utils = @import("../utils.zig"); pub const Worker = struct { const M0_CONN = Message.M0; const M0_SEND = Message.M0; const M0_RECV = Message.M0; const M0_TWIX = Message.M0; const M1_WORK = Message.M1; const M3_WAIT = Message.M3; const max_bytes = 64; var number: u16 = 0; const WorkerData = struct { rxp: *MachinePool, txp: *MachinePool, request: [max_bytes]u8, request_seqn: u32, reply: [max_bytes]u8, ctx: Context, tm: EventSource, io: EventSource, host: []const u8, port: u16, addr: net.Address, }; pub fn onHeap ( a: Allocator, md: *MessageDispatcher, rx_pool: *MachinePool, tx_pool: *MachinePool, host: []const u8, port: u16, ) !*StageMachine { number += 1; var me = try StageMachine.onHeap(a, md, "WORKER", number); try me.addStage(Stage{.name = "INIT", .enter = &initEnter, .leave = null}); try me.addStage(Stage{.name = "CONN", .enter = &connEnter, .leave = null}); try me.addStage(Stage{.name = "SEND", .enter = &sendEnter, .leave = null}); try me.addStage(Stage{.name = "RECV", .enter = &recvEnter, .leave = null}); try me.addStage(Stage{.name = "TWIX", .enter = &twixEnter, .leave = null}); try me.addStage(Stage{.name = "WAIT", .enter = &waitEnter, .leave = null}); var init = &me.stages.items[0]; var conn = &me.stages.items[1]; var send = &me.stages.items[2]; var recv = &me.stages.items[3]; var twix = &me.stages.items[4]; var wait = &me.stages.items[5]; init.setReflex(.sm, Message.M0, Reflex{.transition = conn}); conn.setReflex(.sm, Message.M1, Reflex{.action = &connM1}); conn.setReflex(.sm, Message.M2, Reflex{.action = &connM2}); conn.setReflex(.sm, Message.M0, Reflex{.transition = send}); conn.setReflex(.sm, Message.M3, Reflex{.transition = wait}); send.setReflex(.sm, Message.M1, Reflex{.action = &sendM1}); send.setReflex(.sm, Message.M2, Reflex{.action = &sendM2}); send.setReflex(.sm, Message.M0, Reflex{.transition = recv}); send.setReflex(.sm, Message.M3, Reflex{.transition = wait}); recv.setReflex(.sm, Message.M1, Reflex{.action = &recvM1}); recv.setReflex(.sm, Message.M2, Reflex{.action = &recvM2}); recv.setReflex(.sm, Message.M0, Reflex{.transition = twix}); recv.setReflex(.sm, Message.M3, Reflex{.transition = wait}); twix.setReflex(.tm, Message.T0, Reflex{.transition = send}); wait.setReflex(.tm, Message.T0, Reflex{.transition = conn}); me.data = me.allocator.create(WorkerData) catch unreachable; var pd = utils.opaqPtrTo(me.data, *WorkerData); pd.host = host; pd.port = port; pd.rxp = rx_pool; pd.txp = tx_pool; pd.request_seqn = 0; return me; } fn initEnter(me: *StageMachine) void { var pd = utils.opaqPtrTo(me.data, *WorkerData); pd.io = EventSource.init(me, .io, .csock, Message.D0); me.initTimer(&pd.tm, Message.T0) catch unreachable; pd.addr = net.Address.resolveIp(pd.host, pd.port) catch unreachable; me.msgTo(me, M0_CONN, null); } fn connEnter(me: *StageMachine) void { var pd = utils.opaqPtrTo(me.data, *WorkerData); pd.io.getId(.{}) catch unreachable; const tx = pd.txp.get() orelse { me.msgTo(me, M3_WAIT, null); return; }; pd.ctx.fd = pd.io.id; pd.ctx.buf = pd.request[0..0]; pd.io.startConnect(&pd.addr) catch unreachable; me.msgTo(tx, M1_WORK, &pd.ctx); } // message from TX machine, connection established fn connM1(me: *StageMachine, src: ?*StageMachine, dptr: ?*anyopaque) void { _ = src; _ = dptr; const pd = utils.opaqPtrTo(me.data, *WorkerData); print("{s} : connected to '{s}:{}'\n", .{me.name, pd.host, pd.port}); me.msgTo(me, M0_SEND, null); } // message from TX machine, can't connect fn connM2(me: *StageMachine, src: ?*StageMachine, dptr: ?*anyopaque) void { _ = src; _ = dptr; const pd = utils.opaqPtrTo(me.data, *WorkerData); print("{s} : can not connect to '{s}:{}'\n", .{me.name, pd.host, pd.port}); me.msgTo(me, M3_WAIT, null); } fn sendEnter(me: *StageMachine) void { var pd = utils.opaqPtrTo(me.data, *WorkerData); const tx = pd.txp.get() orelse { me.msgTo(me, M3_WAIT, null); return; }; pd.request_seqn += 1; pd.ctx.buf = std.fmt.bufPrint(&pd.request, "{s}-{}\n", .{me.name, pd.request_seqn}) catch unreachable; me.msgTo(tx, M1_WORK, &pd.ctx); } // message from TX machine (success) fn sendM1(me: *StageMachine, src: ?*StageMachine, dptr: ?*anyopaque) void { _ = src; _ = dptr; me.msgTo(me, M0_RECV, null); } // message from TX machine (failure) fn sendM2(me: *StageMachine, src: ?*StageMachine, dptr: ?*anyopaque) void { _ = src; _ = dptr; me.msgTo(me, M3_WAIT, null); } fn myNeedMore(buf: []u8) bool { if (0x0A == buf[buf.len - 1]) return false; return true; } fn recvEnter(me: *StageMachine) void { var pd = utils.opaqPtrTo(me.data, *WorkerData); const rx = pd.rxp.get() orelse { me.msgTo(me, M3_WAIT, null); return; }; pd.ctx.needMore = &myNeedMore; pd.ctx.timeout = 10000; // msec pd.ctx.buf = pd.reply[0..]; me.msgTo(rx, M1_WORK, &pd.ctx); } // message from RX machine (success) fn recvM1(me: *StageMachine, src: ?*StageMachine, dptr: ?*anyopaque) void { var pd = utils.opaqPtrTo(me.data, *WorkerData); _ = dptr; _ = src; print("reply: {s}", .{pd.reply[0..pd.ctx.cnt]}); me.msgTo(me, M0_TWIX, null); } // message from RX machine (failure) fn recvM2(me: *StageMachine, src: ?*StageMachine, dptr: ?*anyopaque) void { const pd = utils.opaqPtrTo(me.data, *WorkerData); _ = pd; _ = dptr; _ = src; me.msgTo(me, M3_WAIT, null); } fn twixEnter(me: *StageMachine) void { var pd = utils.opaqPtrTo(me.data, *WorkerData); pd.tm.enable(&me.md.eq, .{500}) catch unreachable; } fn waitEnter(me: *StageMachine) void { var pd = utils.opaqPtrTo(me.data, *WorkerData); std.posix.close(pd.io.id); pd.tm.enable(&me.md.eq, .{5000}) catch unreachable; } };
0
repos/edsm-in-zig-demo-2/src
repos/edsm-in-zig-demo-2/src/client-sm/terminator.zig
const std = @import("std"); const os = std.os; const print = std.debug.print; const Allocator = std.mem.Allocator; const mq = @import("../engine/message-queue.zig"); const MessageDispatcher = mq.MessageDispatcher; const MessageQueue = MessageDispatcher.MessageQueue; const Message = MessageQueue.Message; const esrc = @import("../engine//event-sources.zig"); const EventSourceKind = esrc.EventSourceKind; const EventSourceSubKind = esrc.EventSourceSubKind; const EventSource = esrc.EventSource; const edsm = @import("../engine/edsm.zig"); const StageMachine = edsm.StageMachine; const Stage = StageMachine.Stage; const Reflex = Stage.Reflex; const StageList = edsm.StageList; const utils = @import("../utils.zig"); pub const Terminator = struct { const M0_IDLE = Message.M0; const TerminatorData = struct { sg0: EventSource, sg1: EventSource, }; pub fn onHeap(a: Allocator, md: *MessageDispatcher) !*StageMachine { var me = try StageMachine.onHeap(a, md, "TERMINATOR", 1); try me.addStage(Stage{.name = "INIT", .enter = &initEnter, .leave = null}); try me.addStage(Stage{.name = "IDLE", .enter = &idleEnter, .leave = null}); var init = &me.stages.items[0]; var idle = &me.stages.items[1]; init.setReflex(.sm, Message.M0, Reflex{.transition = idle}); idle.setReflex(.sg, Message.S0, Reflex{.action = &idleS0}); idle.setReflex(.sg, Message.S1, Reflex{.action = &idleS0}); me.data = me.allocator.create(TerminatorData) catch unreachable; return me; } fn initEnter(me: *StageMachine) void { var pd = utils.opaqPtrTo(me.data, *TerminatorData); me.initSignal(&pd.sg0, std.posix.SIG.INT, Message.S0) catch unreachable; me.initSignal(&pd.sg1, std.posix.SIG.TERM, Message.S1) catch unreachable; me.msgTo(me, M0_IDLE, null); } fn idleEnter(me: *StageMachine) void { var pd = utils.opaqPtrTo(me.data, *TerminatorData); pd.sg0.enable(&me.md.eq, .{}) catch unreachable; pd.sg1.enable(&me.md.eq, .{}) catch unreachable; } fn idleS0(me: *StageMachine, src: ?*StageMachine, dptr: ?*anyopaque) void { _ = src; const sg = utils.opaqPtrTo(dptr, *EventSource); const si = sg.info.sg.sig_info; print("got signal #{} from PID {}\n", .{si.signo, si.pid}); me.msgTo(null, Message.M0, null); } };
0
repos/edsm-in-zig-demo-2/src
repos/edsm-in-zig-demo-2/src/engine/event-capture.zig
const std = @import("std"); const print = std.debug.print; const EpollEvent = std.os.linux.epoll_event; const EpollData = std.os.linux.epoll_data; const epollCreate = std.posix.epoll_create1; const epollCtl = std.posix.epoll_ctl; const epollWait = std.posix.epoll_wait; const EPOLL = std.os.linux.EPOLL; const ioctl = std.os.linux.ioctl; const msgq = @import("message-queue.zig"); const MD = msgq.MessageDispatcher; const MessageQueue = MD.MessageQueue; const Message = MessageQueue.Message; const esrc = @import("event-sources.zig"); const EventSourceKind = esrc.EventSourceKind; const EventSource = esrc.EventSource; const EventSourceInfo = esrc.EventSourceInfo; const IoInfo = esrc.IoInfo; const edsm = @import("edsm.zig"); const StageMachine = edsm.StageMachine; pub const EventQueue = struct { fd: i32 = -1, mq: *MessageQueue, pub fn onStack(mq: *MessageQueue) !EventQueue { return EventQueue { .fd = try epollCreate(0), .mq = mq, }; } pub fn fini(self: *EventQueue) void { std.posix.close(self.fd); } fn getIoEventInfo(es: *EventSource, events: u32) !u4 { const FIONREAD = std.os.linux.T.FIONREAD; if (0 != events & (EPOLL.ERR | EPOLL.HUP | EPOLL.RDHUP)) { return Message.D2; } if (0 != events & EPOLL.OUT) return Message.D1; if (0 != events & EPOLL.IN) { var ba: u32 = 0; _ = ioctl(es.id, FIONREAD, @intFromPtr(&ba)); // IOCINQ // see https://github.com/ziglang/zig/issues/12961 es.info.io.bytes_avail = ba; return Message.D0; } unreachable; } fn getEventInfo(es: *EventSource, events: u32) !u4 { try es.readInfo(); return switch (es.kind) { .sm => unreachable, .tm => es.seqn, .sg => es.seqn, .io => getIoEventInfo(es, events), .fs => 0, // TODO }; } pub fn wait(self: *EventQueue) !void { const max_events = 1; var events: [max_events]EpollEvent = undefined; const wait_forever = -1; const n = epollWait(self.fd, events[0..], wait_forever); for (events[0..n]) |ev| { const es: *EventSource = @ptrFromInt(ev.data.ptr); const seqn = try getEventInfo(es, ev.events); const msg = Message { .src = null, .dst = es.owner, .esk = es.kind, .sqn = seqn, .ptr = es, }; try self.mq.put(msg); } } const EventKind = enum { can_read, can_write, }; fn enableEventSource(self: *EventQueue, es: *EventSource, ek: EventKind) !void { const FdAlreadyInSet = std.posix.EpollCtlError.FileDescriptorAlreadyPresentInSet; var em: u32 = if (.can_read == ek) (EPOLL.IN | EPOLL.RDHUP) else EPOLL.OUT; em |= EPOLL.ONESHOT; var ee = EpollEvent { .events = em, .data = EpollData{.ptr = @intFromPtr(es)}, }; // emulate FreeBSD kqueue behavior epollCtl(self.fd, EPOLL.CTL_ADD, es.id, &ee) catch |err| { return switch (err) { FdAlreadyInSet => try epollCtl(self.fd, EPOLL.CTL_MOD, es.id, &ee), else => err, }; }; } pub fn disableEventSource(self: *EventQueue, es: *EventSource) !void { var ee = EpollEvent { .events = 0, .data = EpollData{.ptr = @intFromPtr(es)}, }; try epollCtl(self.fd, EPOLL.CTL_MOD, es.id, &ee); } pub fn enableCanRead(self: *EventQueue, es: *EventSource) !void { return try enableEventSource(self, es, .can_read); } pub fn enableCanWrite(self: *EventQueue, es: *EventSource) !void { return try enableEventSource(self, es, .can_write); } };
0
repos/edsm-in-zig-demo-2/src
repos/edsm-in-zig-demo-2/src/engine/architecture.txt
SM == "State Machine" MD == "Message Dispatcher" MQ == "Message Queue" EC == "Event Capture" OS == "Operating System" SM SM SM ... | ^^ | || | MD \ ^ -> / MQ / / | <--- EC (epoll, kqueue) ^ | (i/o, timers, signals, fs events etc.) | OS