Skip to content

Instantly share code, notes, and snippets.

@aboisvert
Last active March 24, 2018 15:36
Show Gist options
  • Save aboisvert/0791b53e492ebc4020c4e1cc049d539d to your computer and use it in GitHub Desktop.
Save aboisvert/0791b53e492ebc4020c4e1cc049d539d to your computer and use it in GitHub Desktop.
type
SharedString* = object
str: cstring
proc newSharedString*(s: string): SharedString =
result = SharedString(str: cast[cstring](allocShared(s.len + 1)))
copyMem(result.str, s.cstring, s.len)
proc deallocSharedString*(s: SharedString) =
deallocShared(s.str)
proc deallocSharedString*(s: var SharedString) =
deallocShared(s.str)
s.str = nil
proc `:=`*(ss: var SharedString, s: string) =
# reassign `var SharedString` to new string value
if ss.str == nil: ss.str = cast[cstring](allocShared(s.len + 1))
else: ss.str = cast[cstring](reallocShared(ss.str, s.len + 1))
copyMem(ss.str, s.cstring, s.len)
proc `$`*(s: SharedString): string =
if s.str == nil: "" else: $s.str
converter asString*(s: SharedString): string = $s
converter fromString*(s: string): SharedString = newSharedString(s)
let s = "foo"
let s1 = newSharedString(s)
echo "s1 is " & s1
let s2: SharedString = "bar"
echo "s2 is " & s2
var s3: SharedString
echo "s3 is " & s3
var s4: SharedString = "baz"
echo "s4 is " & s4
s4 := "quux"
echo "s4 is " & s4
var s5: SharedString = "baz"
echo "s5 is " & s5
s5 := s5 & "quux"
echo "s5 is " & s5
var s6: SharedString = "something"
let s7: string = s6 # copy back
s6 := "something_else"
deallocSharedString(s6)
echo "s6 is " & s6
echo "s7 is " & s7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment