Skip to content

Converting between DynamicVector[UI8], DynamicVector[Int], and Buffer[x, UI8] in a zero copy way #127

Closed Locked Answered by sa-
sa- asked this question in Q&A
Discussion options

You must be logged in to vote

I've figured this out. Thanks to @czheo for helping me figure this out

from TargetInfo import sizeof

fn reinterpret_dynamic_vector[Tsrc: AnyType, Tdest: AnyType](
        src: DynamicVector[Tsrc]
) -> DynamicVector[Tdest]:
    let tsrc_bitwidth = sizeof[Tsrc]()
    let tdest_bitwidth = sizeof[Tdest]()
    
    let num_bytes_src = tsrc_bitwidth * src.size
    if num_bytes_src % tdest_bitwidth != 0:
        print("Cannot divide up the bits for the new type")
    let dest_num_elements = num_bytes_src // tdest_bitwidth
    return DynamicVector[Tdest](src.data.bitcast[Tdest](), dest_num_elements)
    
var int_vec = DynamicVector[Int]()
int_vec.push_back(-1)
print(int_vec[0]) # output: -1

var u…

Replies: 2 comments 6 replies

Comment options

You must be logged in to vote
6 replies
@sa-
Comment options

@sa-
Comment options

@czheo
Comment options

@sa-
Comment options

@sa-
Comment options

Comment options

You must be logged in to vote
0 replies
Answer selected by sa-
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