Skip to content

Commit 13486ad

Browse files
citrus-lemonSavchenkoValeriy
authored andcommitted
fix Data conversion and generic impl for data and string
1 parent bdd6fa0 commit 13486ad

File tree

2 files changed

+14
-15
lines changed

2 files changed

+14
-15
lines changed

Source/Swift/Conversion.swift

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -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
}

test/swift-module-test.el

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,10 @@
2424

2525
(ert-deftest swift-module:check-data-conversion ()
2626
:tags '(emacs-28 emacs-29 emacs-30)
27-
(let ((d1 "\000\000\000\001\000"))
28-
(should (string= d1 (swift-data d1)))))
27+
(let ((d1 "\000\000\000\001\000")
28+
(d2 ""))
29+
(should (string= d1 (swift-data d1)))
30+
(should (string= d2 (swift-data d2)))))
2931

3032
(ert-deftest swift-module:check-incorrect-num-of-args ()
3133
:tags '(emacs-all)

0 commit comments

Comments
 (0)