@@ -305,7 +305,7 @@ extension Environment {
305305 //
306306 // Converter functions
307307 //
308- func toString ( _ value: EmacsValue ) throws -> String {
308+ func toBytesArray ( _ value: EmacsValue ) throws -> [ CChar ] {
309309 var len = 0
310310 // The first call to `copy_string_contents` is needed to determine
311311 // the actual length of the string...
@@ -316,7 +316,10 @@ extension Environment {
316316 // ...and use it again with that buffer to fill.
317317 let _ = try pointee. copy_string_contents ( raw, value. raw, & buf, & len)
318318 // Swift owns this memory know, nothing to be worried about!
319- return String ( cString: buf)
319+ return buf
320+ }
321+ func toString( _ value: EmacsValue ) throws -> String {
322+ return String ( cString: try toBytesArray ( value) )
320323 }
321324 func toInt( _ value: EmacsValue ) throws -> Int {
322325 try Int ( check ( pointee. extract_integer ( raw, value. raw) ) )
@@ -345,16 +348,10 @@ extension Environment {
345348 try check ( pointee. get_user_ptr ( raw, value. raw) ) !
346349 }
347350 func toData( _ value: EmacsValue ) throws -> Data {
348- var len = 0
349- // The first call to `copy_string_contents` is needed to determine
350- // the actual length of the string...
351- let _ = try check (
352- pointee. copy_string_contents ( raw, value. raw, nil , & len) )
353- // ...then allocate the buffer of the right size...
354- var buf = [ CChar] ( repeating: 0 , count: len)
355- // ...and use it again with that buffer to fill.
356- let _ = try pointee. copy_string_contents ( raw, value. raw, & buf, & len)
357- // Swift owns this memory know, nothing to be worried about!
358- return Data ( bytes: buf, count: len)
351+ var buf = try toBytesArray ( value)
352+ // Emacs `copy_string_contents` include the last null byte,
353+ // we remove that when convert back to Data.
354+ buf. removeLast ( )
355+ return Data ( bytes: buf, count: buf. count)
359356 }
360357}
0 commit comments