M
Modular14mo ago
Igor

_ImmutableString

How can I convert a _ImmutableString to String or StringRef?
6 Replies
Moosems / Three chickens
Since it’s immutable it can’t be changed at all 😄.
Igor
IgorOP14mo ago
Well yeah, but I want to craete a brand new string based on that _ImmutableString that returns object._value.to..string()...
Moosems / Three chickens
String(example_immutable.copyinit) maybe?
Igor
IgorOP14mo ago
'_ImmutableString' value has no attribute 'copyinit'
'_ImmutableString' value has no attribute 'copyinit'
Moosems / Three chickens
Can you find the docs page on this for me? And you did __copyinit__?
Stole
Stole14mo ago
The following should do something like you want, but it's important to be careful here with how long values live for. Again, only use this if you absolutely need to. More internal structures like _ImmutableString are probably best left alone.
let o: object = "abcdtest"
let s = o._value.get_as_string() # doing this just to get an example _ImmutableString to play with

let p = Pointer[Int8].alloc(s.length)
memcpy(p, s.data, s.length)
let st = String(p^, s.length) # using the ^ move syntax to denote now st owns p, though it is not at all needed
print(st)
_ = o # keeps o alive, to keep s and therefore its pointer from getting destructed early (we get bad memory otherwise, I guess there could be something else nefarious happening here that we can't see)
let o: object = "abcdtest"
let s = o._value.get_as_string() # doing this just to get an example _ImmutableString to play with

let p = Pointer[Int8].alloc(s.length)
memcpy(p, s.data, s.length)
let st = String(p^, s.length) # using the ^ move syntax to denote now st owns p, though it is not at all needed
print(st)
_ = o # keeps o alive, to keep s and therefore its pointer from getting destructed early (we get bad memory otherwise, I guess there could be something else nefarious happening here that we can't see)
Want results from more Discord servers?
Add your server