forked from rime/squirrel
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathBridgingFunctions.swift
87 lines (79 loc) · 2.35 KB
/
BridgingFunctions.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
//
// BridgingFunctions.swift
// Squirrel
//
// Created by Leo Liu on 5/11/24.
//
import Foundation
protocol DataSizeable {
// swiftlint:disable:next identifier_name
var data_size: Int32 { get set }
}
extension RimeContext_stdbool: DataSizeable {}
extension RimeTraits: DataSizeable {}
extension RimeCommit: DataSizeable {}
extension RimeStatus_stdbool: DataSizeable {}
extension RimeModule: DataSizeable {}
extension DataSizeable {
static func rimeStructInit() -> Self {
let valuePointer = UnsafeMutablePointer<Self>.allocate(capacity: 1)
// Initialize the memory to zero
memset(valuePointer, 0, MemoryLayout<Self>.size)
// Convert the pointer to a managed Swift variable
var value = valuePointer.move()
valuePointer.deallocate()
// Initialize data_size property
let offset = MemoryLayout.size(ofValue: \Self.data_size)
value.data_size = Int32(MemoryLayout<Self>.size - offset)
return value
}
mutating func setCString(_ swiftString: String, to keypath: WritableKeyPath<Self, UnsafePointer<CChar>?>) {
swiftString.withCString { cStr in
// Duplicate the string to create a persisting C string
let mutableCStr = strdup(cStr)
// Free the existing string if there is one
if let existing = self[keyPath: keypath] {
free(UnsafeMutableRawPointer(mutating: existing))
}
self[keyPath: keypath] = UnsafePointer(mutableCStr)
}
}
}
infix operator ?= : AssignmentPrecedence
// swiftlint:disable:next operator_whitespace
func ?=<T>(left: inout T, right: T?) {
if let right = right {
left = right
}
}
// swiftlint:disable:next operator_whitespace
func ?=<T>(left: inout T?, right: T?) {
if let right = right {
left = right
}
}
extension NSRange {
static let empty = NSRange(location: NSNotFound, length: 0)
}
extension NSPoint {
static func += (lhs: inout Self, rhs: Self) {
lhs.x += rhs.x
lhs.y += rhs.y
}
static func - (lhs: Self, rhs: Self) -> Self {
Self.init(x: lhs.x - rhs.x, y: lhs.y - rhs.y)
}
static func -= (lhs: inout Self, rhs: Self) {
lhs.x -= rhs.x
lhs.y -= rhs.y
}
static func * (lhs: Self, rhs: CGFloat) -> Self {
Self.init(x: lhs.x * rhs, y: lhs.y * rhs)
}
static func / (lhs: Self, rhs: CGFloat) -> Self {
Self.init(x: lhs.x / rhs, y: lhs.y / rhs)
}
var length: CGFloat {
sqrt(pow(self.x, 2) + pow(self.y, 2))
}
}