Skip to content

cgen: fix aliased fixed array option fn call (fix #22927)#22934

Merged
spytheman merged 1 commit intovlang:masterfrom
yuyi98:fix_or_block
Nov 21, 2024
Merged

cgen: fix aliased fixed array option fn call (fix #22927)#22934
spytheman merged 1 commit intovlang:masterfrom
yuyi98:fix_or_block

Conversation

@yuyi98
Copy link
Copy Markdown
Member

@yuyi98 yuyi98 commented Nov 21, 2024

This PR fix aliased fixed array option fn call (fix #22927).

  • Fix aliased fixed array option fn call.
  • Add test.
import encoding.binary

pub type Addr = [4]u8

pub fn Addr.from_u32(a u32) Addr {
	mut bytes := [4]u8{}
	binary.big_endian_put_u32_fixed(mut bytes, a)
	return Addr(bytes)
}

pub fn (a Addr) u32() u32 {
	return binary.big_endian_u32_fixed(a)
}

struct Net {
	netaddr   Addr
	broadcast Addr
}

// returns Nth IP-address from the network if exists, else none
fn (n Net) nth(num i64) ?Addr {
	mut addr := Addr{}
	if num >= 0 {
		addr = Addr.from_u32(n.netaddr.u32() + u32(num))
	} else {
		addr = Addr.from_u32(n.broadcast.u32() + u32(num))
	}
	if !(n.netaddr.u32() < addr.u32() && addr.u32() < n.broadcast.u32()) {
		return none
	}
	return addr
}

fn main() {
	net := Net{
		netaddr:   Addr([u8(172), 16, 16, 0]!)
		broadcast: Addr([u8(172), 16, 16, 3]!)
	}
	res1 := net.nth(1) or { panic(err) }
	res2 := net.nth(1) or { Addr{} }
	println(res1)
	println(res2)
	assert res1 == [u8(172), 16, 16, 1]!
	assert res2 == [u8(172), 16, 16, 1]!
}

PS D:\Test\v\tt1> v run .    
Addr([172, 16, 16, 1])
Addr([172, 16, 16, 1])

Huly®: V_0.6-21376

Copy link
Copy Markdown
Contributor

@spytheman spytheman left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Excellent work.

@spytheman spytheman merged commit 17f962d into vlang:master Nov 21, 2024
@yuyi98 yuyi98 deleted the fix_or_block branch November 21, 2024 12:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

C error and random values when handling option for aliased fixed array

2 participants