M
Modular12mo ago
Igor

_ImmutableString

How can I convert a _ImmutableString to String or StringRef?
6 Replies
Three chickens in the green bag
Since it’s immutable it can’t be changed at all 😄.
Igor
Igor12mo ago
Well yeah, but I want to craete a brand new string based on that _ImmutableString that returns object._value.to..string()...
Three chickens in the green bag
String(example_immutable.copyinit) maybe?
Igor
Igor12mo ago
'_ImmutableString' value has no attribute 'copyinit'
'_ImmutableString' value has no attribute 'copyinit'
Three chickens in the green bag
Can you find the docs page on this for me? And you did __copyinit__?
Stole
Stole12mo 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