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 › big › int › Mutable › byteSwap Public Function byteSwap Doc Source Public Function std.math.big.int.Mutable.byteSwap
pub fn byteSwap (r : *Mutable , a : Const , signedness : Signedness , byte_count : usize ) void Params File math/big/int.zig: 992
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053 pub fn byteSwap (r : *Mutable , a : Const , signedness : Signedness , byte_count : usize ) void {
if (byte_count == 0 ) {
r .limbs [0 ] = 0 ;
r .len = 1 ;
r .positive = true ;
return ;
}
r .copy (a );
const limbs_required = calcTwosCompLimbCount (8 * byte_count );
if (!a .positive ) {
r .positive = true ; // Negate.
r .bitNotWrap (r .toConst (), .unsigned , 8 * byte_count ); // Bitwise NOT.
r .addScalar (r .toConst (), 1 ); // Add one.
} else if (limbs_required > a .limbs .len ) {
// Zero-extend to our output length
for (r .limbs [a .limbs .len ..limbs_required ]) |*limb | {
limb .* = 0 ;
}
r .len = limbs_required ;
}
// 0b0..01..1 with @log2(@sizeOf(Limb)) trailing ones
const endian_mask : usize = @sizeOf (Limb ) - 1 ;
var bytes = std .mem .sliceAsBytes (r .limbs );
assert (bytes .len >= byte_count );
var k : usize = 0 ;
while (k < (byte_count + 1 ) / 2 ) : (k += 1 ) {
var i = k ;
var rev_i = byte_count - k - 1 ;
// This "endian mask" remaps a low (LE) byte to the corresponding high
// (BE) byte in the Limb, without changing which limbs we are indexing
if (native_endian == .big ) {
i ^= endian_mask ;
rev_i ^= endian_mask ;
}
const byte_i = bytes [i ];
const byte_rev_i = bytes [rev_i ];
bytes [rev_i ] = byte_i ;
bytes [i ] = byte_rev_i ;
}
// Calculate signed-magnitude representation for output
if (signedness == .signed ) {
const last_byte = switch (native_endian ) {
.little => bytes [byte_count - 1 ],
.big => bytes [(byte_count - 1 ) ^ endian_mask ],
};
if (last_byte & (1 << 7 ) != 0 ) { // Check sign bit of last byte
r .bitNotWrap (r .toConst (), .unsigned , 8 * byte_count ); // Bitwise NOT.
r .addScalar (r .toConst (), 1 ); // Add one.
r .positive = false ; // Negate.
}
}
r .normalize (r .len );
}
r = @byteSwap(a) with 2s-complement semantics. r and a may be aliases.
Asserts the result fits in
r. Upper bound on the number of limbs needed by r iscalcTwosCompLimbCount(8*byte_count).