Zig 0.17.0-dev (Split by item) This is an example of documentation generated by
ZigDoc , an alternative to Zig's built-in
Auto Doc feature. See also
examples in other modes/formats . The project being documented here (as the example) is the Zig standard library.
std › math › log2 Public Namespace log2 Doc Source Public Namespace Namespaces Values Functions pub fn expect (ok : bool ) !void This function is intended to be used only in tests. When ok is false, returns a test failure error.
pub fn log2 (x : anytype ) @TypeOf (x ) Returns the base-2 logarithm of x.
Special Cases:
log2(+inf) = +inf log2(0) = -inf log2(x) = nan if x < 0 log2(nan) = nan File math/log2.zig
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56 const std = @import ("../std.zig " );
const builtin = @import ("builtin " );
const math = std .math ;
const expect = std .testing .expect ;
/// Returns the base-2 logarithm of x.
///
/// Special Cases:
/// - log2(+inf) = +inf
/// - log2(0) = -inf
/// - log2(x) = nan if x < 0
/// - log2(nan) = nan
pub fn log2 (x : anytype ) @TypeOf (x ) {
const T = @TypeOf (x );
return switch (@typeInfo (T )) {
.comptime_float , .float => @log2 (x ),
.comptime_int => comptime {
std .debug .assert (x > 0 );
var x_shifted = x ;
// First, calculate floorPowerOfTwo(x)
var shift_amt = 1 ;
while (x_shifted >> (shift_amt << 1 ) != 0 ) shift_amt <<= 1 ;
// Answer is in the range [shift_amt, 2 * shift_amt - 1]
// We can find it in O(log(N)) using binary search.
var result = 0 ;
while (shift_amt != 0 ) : (shift_amt >>= 1 ) {
if (x_shifted >> shift_amt != 0 ) {
x_shifted >>= shift_amt ;
result += shift_amt ;
}
}
return result ;
},
.int => |int_info | math .log2_int (switch (int_info .signedness ) {
.signed => @Int (.unsigned , int_info .bits -| 1 ),
.unsigned => T ,
}, @intCast (x )),
else => @compileError ("log2 not implemented for " ++ @typeName (T )),
};
}
test log2 {
// https://github.com/ziglang/zig/issues/13703
if (builtin .cpu .arch == .aarch64 and builtin .os .tag == .windows ) return error .SkipZigTest ;
try expect (log2 (@as (f32 , 0.2 )) == @log2 (0.2 ));
try expect (log2 (@as (f64 , 0.2 )) == @log2 (0.2 ));
comptime {
try expect (log2 (1 ) == 0 );
try expect (log2 (15 ) == 3 );
try expect (log2 (16 ) == 4 );
try expect (log2 (1 << 4073 ) == 4073 );
}
}