Skip to content

Custom Buffer Type using Parametric Polymorphism #3888

Closed Locked Answered by Kelimion
herohiralal asked this question in Q&A
Discussion options

You must be logged in to vote
FixedSizeBuffer :: struct($E: typeid, $SIZE: u64) {
	count:  u64,
	buffer: [SIZE]E,
}

// Didn't need a pointer
get_capacity :: proc(buffer: $B/FixedSizeBuffer) -> u64 {
	return B.SIZE
}

// Didn't need a pointer
get_count :: proc(buffer: $B/FixedSizeBuffer) -> u64 {
	return buffer.count
}

// What was $T2 supposed to be? You can't have a $ return value.
get_slot :: proc(buffer: ^$B/FixedSizeBuffer($E, $S), index: u64) -> ^E {
	if index < buffer.count {
		return &buffer.buffer[index]
	}
	return nil
}

_main :: proc() {
	fsb: FixedSizeBuffer(string, 5)
	fmt.println(fsb)
	fmt.println(get_capacity(fsb))
	fmt.println(get_count(fsb))
	fmt.println(get_slot(&fsb, 2)) // returns nil because buffe…

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by Kelimion
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants