Skip to content

Commit

Permalink
调整部分缩进,使得观看更加美观
Browse files Browse the repository at this point in the history
  • Loading branch information
jinzhongjia committed Sep 7, 2024
1 parent 4e5c9b5 commit ba99ce9
Show file tree
Hide file tree
Showing 22 changed files with 146 additions and 47 deletions.
8 changes: 6 additions & 2 deletions course/advanced/interact-with-c.md
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,8 @@ pub export fn foo() c_int {
_ = &b;
return a + b;
}
pub const MAKELOCAL = @compileError("unable to translate C expr: unexpected token .Equal");
pub const MAKELOCAL =
@compileError("unable to translate C expr: unexpected token .Equal");
```

:::
Expand Down Expand Up @@ -245,7 +246,10 @@ CC='zig cc -target x86_64-linux-gnu' CXX='zig cc -target x86_64-linux-gnu' go bu
再进一步,我们还可以构建出 linux 的使用 cgo 的静态链接的二进制可执行文件:

```sh
CC='zig cc -target x86_64-linux-musl' CXX='zig cc -target x86_64-linux-musl' CGO_CFLAGS='-D_LARGEFILE64_SOURCE' go build -ldflags='-linkmode=external -extldflags -static'
CC='zig cc -target x86_64-linux-musl' \
CXX='zig cc -target x86_64-linux-musl' \
CGO_CFLAGS='-D_LARGEFILE64_SOURCE' \
go build -ldflags='-linkmode=external -extldflags -static'
```

`CGO_CFLAGS` 是为了防止编译失败,`ldflags` 是为了指定静态链接!
6 changes: 5 additions & 1 deletion course/advanced/package_management.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,11 @@ zig 支持在一个 `build.zig` 中对外暴露出多个模块,也就是说一
可以使用 `build` 函数传入的参数 `b: *std.Build`,它包含一个方法 [`addModule`](https://ziglang.org/documentation/master/std/#std.Build.addModule), 它的原型如下:

```zig
pub fn addModule(b: *Build, name: []const u8, options: Module.CreateOptions) *Module
pub fn addModule(
b: *Build,
name: []const u8,
options: Module.CreateOptions
) *Module
```

使用起来也很简单,例如:
Expand Down
14 changes: 12 additions & 2 deletions course/basic/advanced_type/vector.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,12 @@ Zig 支持任何已知的最大 2^32-1 向量长度。请注意,过长的向
## `@shuffle`

```zig
@shuffle(comptime E: type, a: @Vector(a_len, E), b: @Vector(b_len, E), comptime mask: @Vector(mask_len, i32)) @Vector(mask_len, E)
@shuffle(
comptime E: type,
a: @Vector(a_len, E),
b: @Vector(b_len, E),
comptime mask: @Vector(mask_len, i32)
) @Vector(mask_len, E)
```

根据掩码`mask`(一个向量 Vector),返回向量 a 或者向量 b 的值,组成一个新的向量,mask 的长度决定返回的向量的长度,并且逐个根据 mask 中的值,来从 a 或 b选出值,正数是从 a 选出指定索引的值(从 0 开始,变大),负数是从 b 选出指定索引的值(从 -1 开始,变小)。
Expand All @@ -80,7 +85,12 @@ Zig 支持任何已知的最大 2^32-1 向量长度。请注意,过长的向
## `@select`

```zig
@select(comptime T: type, pred: @Vector(len, bool), a: @Vector(len, T), b: @Vector(len, T)) @Vector(len, T)
@select(
comptime T: type,
pred: @Vector(len, bool),
a: @Vector(len, T),
b: @Vector(len, T)
) @Vector(len, T)
```

根据 pred(一个元素全为布尔类型的向量)从 a 或 b 中按元素选择值。如果 `pred[i]``true`,则结果中的相应元素将为 `a[i]`,否则为 `b[i]`
Expand Down
6 changes: 5 additions & 1 deletion course/basic/union.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,11 @@ outline: deep
如果要初始化一个在编译期已知的字段名的联合类型,可以使用 [`@unionInit`](https://ziglang.org/documentation/master/#unionInit)

```zig
@unionInit(comptime Union: type, comptime active_field_name: []const u8, init_expr) Union
@unionInit(
comptime Union: type,
comptime active_field_name: []const u8,
init_expr
) Union
```

<<<@/code/release/union.zig#union_init
Expand Down
4 changes: 3 additions & 1 deletion course/code/12/build_system/cli/build.zig
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ pub fn build(b: *std.Build) void {
const optimize = b.standardOptimizeOption(.{});

// 使用 option 来获取命令参数决定是否剥离调试信息
const is_strip = b.option(bool, "is_strip", "whether strip executable") orelse false;
const is_strip =
b.option(bool, "is_strip", "whether strip executable") orelse
false;

// 添加一个二进制可执行程序构建
const exe = b.addExecutable(.{
Expand Down
5 changes: 4 additions & 1 deletion course/code/12/build_system/embedfile/build.zig
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ pub fn build(b: *std.Build) void {
.optimize = optimize,
});

exe.root_module.addAnonymousImport("hello", .{ .root_source_file = b.path("src/hello.txt") });
exe.root_module.addAnonymousImport(
"hello",
.{ .root_source_file = b.path("src/hello.txt") },
);

// 添加到顶级 install step 中作为依赖
b.installArtifact(exe);
Expand Down
3 changes: 2 additions & 1 deletion course/code/12/build_system/test/build.zig
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ pub fn build(b: *std.Build) void {
// 执行单元测试
const run_exe_unit_tests = b.addRunArtifact(exe_unit_tests);

// 如果想要跳过外部来自于其他包的单元测试(例如依赖中的包),可以使用 skip_foreign_checks
// 如果想要跳过外部来自于其他包的单元测试(例如依赖中的包)
// 可以使用 skip_foreign_checks
run_exe_unit_tests.skip_foreign_checks = true;

// 构建一个 step,用于执行测试
Expand Down
12 changes: 9 additions & 3 deletions course/code/12/echo_tcp_server.zig
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,10 @@ pub fn main() !void {
// 存储 accept 拿到的 connections
var connections: [max_sockets]?net.Server.Connection = undefined;
// sockfds 用于存储 pollfd, 用于传递给 poll 函数
var sockfds: [max_sockets]if (builtin.os.tag == .windows) windows.ws2_32.pollfd else std.posix.pollfd = undefined;
var sockfds: [max_sockets]if (builtin.os.tag == .windows)
windows.ws2_32.pollfd
else
std.posix.pollfd = undefined;
// #endregion data
for (0..max_sockets) |i| {
sockfds[i].fd = context.INVALID_SOCKET;
Expand Down Expand Up @@ -126,14 +129,17 @@ pub fn main() !void {
// 但仅仅这样写一次并不安全
// 最优解应该是使用for循环检测写入的数据大小是否等于buf长度
// 如果不等于就继续写入
// 这是因为 TCP 是一个面向流的协议,它并不保证一次 write 调用能够发送所有的数据
// 这是因为 TCP 是一个面向流的协议
// 它并不保证一次 write 调用能够发送所有的数据
// 作为示例,我们不检查是否全部写入
_ = try connection.stream.write(buf[0..len]);
}
}
}
// 检查是否是 POLLNVAL | POLLERR | POLLHUP 事件,即是否有错误发生,或者连接断开
else if (sockfd.revents & (context.POLLNVAL | context.POLLERR | context.POLLHUP) != 0) {
else if ((sockfd.revents &
(context.POLLNVAL | context.POLLERR | context.POLLHUP)) != 0)
{
// 将 pollfd 和 connection 置为无效
sockfds[i].fd = context.INVALID_SOCKET;
connections[i] = null;
Expand Down
5 changes: 4 additions & 1 deletion course/code/12/memory_manager.zig
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,10 @@ const StackFallbackAllocator = struct {
pub fn main() !void {
// 初始化一个优先使用栈区的分配器
// 栈区大小为256个字节,如果栈区不够用,就会使用page allocator
var stack_alloc = std.heap.stackFallback(256 * @sizeOf(u8), std.heap.page_allocator);
var stack_alloc = std.heap.stackFallback(
256 * @sizeOf(u8),
std.heap.page_allocator,
);
// 获取分配器
const stack_allocator = stack_alloc.get();
// 申请内存
Expand Down
4 changes: 3 additions & 1 deletion course/code/12/switch.zig
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,9 @@ fn isFieldOptional(comptime T: type, field_index: usize) !bool {
const fields = @typeInfo(T).Struct.fields;
return switch (field_index) {
// 这里每次都是不同的值
inline 0...fields.len - 1 => |idx| @typeInfo(fields[idx].type) == .Optional,
inline 0...fields.len - 1 => |idx| {
return @typeInfo(fields[idx].type) == .Optional;
},
else => return error.IndexOutOfBounds,
};
}
Expand Down
3 changes: 2 additions & 1 deletion course/code/12/type-cast.zig
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,8 @@ const tag_union_enum = struct {
try expect(e == E.two);

const three = E.three;
const u_2: U = three; // 将枚举转换为联合类型,注意这里 three 并没有对应的类型,故可以直接转换
// 将枚举转换为联合类型,注意这里 three 并没有对应的类型,故可以直接转换
const u_2: U = three;
try expect(u_2 == E.three);

const u_3: U = .three; // 字面量供 zig 编译器来自动推导
Expand Down
4 changes: 3 additions & 1 deletion course/code/14/build_system/cli/build.zig
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ pub fn build(b: *std.Build) void {
const optimize = b.standardOptimizeOption(.{});

// 使用 option 来获取命令参数决定是否剥离调试信息
const is_strip = b.option(bool, "is_strip", "whether strip executable") orelse false;
const is_strip =
b.option(bool, "is_strip", "whether strip executable") orelse
false;

// 添加一个二进制可执行程序构建
const exe = b.addExecutable(.{
Expand Down
5 changes: 4 additions & 1 deletion course/code/14/build_system/embedfile/build.zig
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ pub fn build(b: *std.Build) void {
.optimize = optimize,
});

exe.root_module.addAnonymousImport("hello", .{ .root_source_file = b.path("src/hello.txt") });
exe.root_module.addAnonymousImport(
"hello",
.{ .root_source_file = b.path("src/hello.txt") },
);

// 添加到顶级 install step 中作为依赖
b.installArtifact(exe);
Expand Down
3 changes: 2 additions & 1 deletion course/code/14/build_system/test/build.zig
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ pub fn build(b: *std.Build) void {
// 执行单元测试
const run_exe_unit_tests = b.addRunArtifact(exe_unit_tests);

// 如果想要跳过外部来自于其他包的单元测试(例如依赖中的包),可以使用 skip_foreign_checks
// 如果想要跳过外部来自于其他包的单元测试(例如依赖中的包)
// 可以使用 skip_foreign_checks
run_exe_unit_tests.skip_foreign_checks = true;

// 构建一个 step,用于执行测试
Expand Down
12 changes: 9 additions & 3 deletions course/code/14/echo_tcp_server.zig
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,10 @@ pub fn main() !void {
// 存储 accept 拿到的 connections
var connections: [max_sockets]?net.Server.Connection = undefined;
// sockfds 用于存储 pollfd, 用于传递给 poll 函数
var sockfds: [max_sockets]if (builtin.os.tag == .windows) windows.ws2_32.pollfd else std.posix.pollfd = undefined;
var sockfds: [max_sockets]if (builtin.os.tag == .windows)
windows.ws2_32.pollfd
else
std.posix.pollfd = undefined;
// #endregion data
for (0..max_sockets) |i| {
sockfds[i].fd = context.INVALID_SOCKET;
Expand Down Expand Up @@ -127,14 +130,17 @@ pub fn main() !void {
// 但仅仅这样写一次并不安全
// 最优解应该是使用for循环检测写入的数据大小是否等于buf长度
// 如果不等于就继续写入
// 这是因为 TCP 是一个面向流的协议,它并不保证一次 write 调用能够发送所有的数据
// 这是因为 TCP 是一个面向流的协议
// 它并不保证一次 write 调用能够发送所有的数据
// 作为示例,我们不检查是否全部写入
_ = try connection.stream.write(buf[0..len]);
}
}
}
// 检查是否是 POLLNVAL | POLLERR | POLLHUP 事件,即是否有错误发生,或者连接断开
else if (sockfd.revents & (context.POLLNVAL | context.POLLERR | context.POLLHUP) != 0) {
else if ((sockfd.revents &
(context.POLLNVAL | context.POLLERR | context.POLLHUP)) != 0)
{
// 将 pollfd 和 connection 置为无效
sockfds[i].fd = context.INVALID_SOCKET;
connections[i] = null;
Expand Down
5 changes: 4 additions & 1 deletion course/code/14/memory_manager.zig
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,10 @@ const StackFallbackAllocator = struct {
pub fn main() !void {
// 初始化一个优先使用栈区的分配器
// 栈区大小为256个字节,如果栈区不够用,就会使用page allocator
var stack_alloc = std.heap.stackFallback(256 * @sizeOf(u8), std.heap.page_allocator);
var stack_alloc = std.heap.stackFallback(
256 * @sizeOf(u8),
std.heap.page_allocator,
);
// 获取分配器
const stack_allocator = stack_alloc.get();
// 申请内存
Expand Down
4 changes: 3 additions & 1 deletion course/code/14/switch.zig
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,9 @@ fn isFieldOptional(comptime T: type, field_index: usize) !bool {
const fields = @typeInfo(T).Struct.fields;
return switch (field_index) {
// 这里每次都是不同的值
inline 0...fields.len - 1 => |idx| @typeInfo(fields[idx].type) == .Optional,
inline 0...fields.len - 1 => |idx| {
return @typeInfo(fields[idx].type) == .Optional;
},
else => return error.IndexOutOfBounds,
};
}
Expand Down
3 changes: 2 additions & 1 deletion course/code/14/type-cast.zig
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,8 @@ const tag_union_enum = struct {
try expect(e == E.two);

const three = E.three;
const u_2: U = three; // 将枚举转换为联合类型,注意这里 three 并没有对应的类型,故可以直接转换
// 将枚举转换为联合类型,注意这里 three 并没有对应的类型,故可以直接转换
const u_2: U = three;
try expect(u_2 == E.three);

const u_3: U = .three; // 字面量供 zig 编译器来自动推导
Expand Down
6 changes: 4 additions & 2 deletions course/environment/install-environment.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,15 +77,17 @@ choco install zig
```powershell [System]
[Environment]::SetEnvironmentVariable(
"Path",
[Environment]::GetEnvironmentVariable("Path", "Machine") + ";C:\your-path\zig-windows-x86_64-your-version",
[Environment]::GetEnvironmentVariable("Path", "Machine")
+ ";C:\your-path\zig-windows-x86_64-your-version",
"Machine"
)
```

```powershell [User]
[Environment]::SetEnvironmentVariable(
"Path",
[Environment]::GetEnvironmentVariable("Path", "User") + ";C:\your-path\zig-windows-x86_64-your-version",
[Environment]::GetEnvironmentVariable("Path", "User")
+ ";C:\your-path\zig-windows-x86_64-your-version",
"User"
)
```
Expand Down
39 changes: 34 additions & 5 deletions course/more/atomic.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,11 @@ outline: deep
函数原型:

```zig
@atomicLoad(comptime T: type, ptr: *const T, comptime ordering: AtomicOrder) T
@atomicLoad(
comptime T: type,
ptr: *const T,
comptime ordering: AtomicOrder
) T
```

用于某个类型指针进行原子化的读取值。
Expand All @@ -43,7 +47,13 @@ outline: deep
函数原型:

```zig
@atomicRmw(comptime T: type, ptr: *T, comptime op: AtomicRmwOp, operand: T, comptime ordering: AtomicOrder) T
@atomicRmw(
comptime T: type,
ptr: *T,
comptime op: AtomicRmwOp,
operand: T,
comptime ordering: AtomicOrder
) T
```

用于原子化的修改值并返回修改前的值。
Expand All @@ -55,7 +65,12 @@ outline: deep
函数原型:

```zig
@atomicStore(comptime T: type, ptr: *T, value: T, comptime ordering: AtomicOrder) void
@atomicStore(
comptime T: type,
ptr: *T,
value: T,
comptime ordering: AtomicOrder
) void
```

用于对某个类型指针进行原子化的赋值。
Expand All @@ -65,7 +80,14 @@ outline: deep
函数原型:

```zig
@cmpxchgWeak(comptime T: type, ptr: *T, expected_value: T, new_value: T, success_order: AtomicOrder, fail_order: AtomicOrder) ?T
@cmpxchgWeak(
comptime T: type,
ptr: *T,
expected_value: T,
new_value: T,
success_order: AtomicOrder,
fail_order: AtomicOrder
) ?T
```

弱原子的比较与交换操作,如果目标指针是给定值,那么赋值为参数的新值,并返回null,否则仅读取值返回。
Expand All @@ -75,7 +97,14 @@ outline: deep
函数原型:

```zig
@cmpxchgStrong(comptime T: type, ptr: *T, expected_value: T, new_value: T, success_order: AtomicOrder, fail_order: AtomicOrder) ?T
@cmpxchgStrong(
comptime T: type,
ptr: *T,
expected_value: T,
new_value: T,
success_order: AtomicOrder,
fail_order: AtomicOrder
) ?T
```

强原子的比较与交换操作,如果目标指针是给定值,那么赋值为参数的新值,并返回null,否则仅读取值返回。
Expand Down
5 changes: 4 additions & 1 deletion course/more/style_guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,10 @@ fn functionName(param_name: TypeName) void {
const functionAlias = functionName;
// 可被调用,且返回类型,使用 TitleCase 命名法
fn ListTemplateFunction(comptime ChildType: type, comptime fixed_size: usize) type {
fn ListTemplateFunction(
comptime ChildType: type,
comptime fixed_size: usize,
) type {
return List(ChildType, fixed_size);
}
Expand Down
Loading

0 comments on commit ba99ce9

Please sign in to comment.