-
Notifications
You must be signed in to change notification settings - Fork 105
Expand file tree
/
Copy pathString+JNIExtensions.swift
More file actions
64 lines (59 loc) · 2.02 KB
/
String+JNIExtensions.swift
File metadata and controls
64 lines (59 loc) · 2.02 KB
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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2024 Apple Inc. and the Swift.org project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Swift.org project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import SwiftJavaJNICore
extension String {
/// Returns a version of the string correctly escaped for a JNI identifier
var escapedJNIIdentifier: String {
self.map {
if $0 == "_" {
return "_1"
} else if $0 == "/" {
return "_"
} else if $0 == ";" {
return "_2"
} else if $0 == "[" {
return "_3"
} else if $0.isASCII && ($0.isLetter || $0.isNumber) {
return String($0)
} else if let utf16 = $0.utf16.first {
// Escape any non-alphanumeric to their UTF16 hex encoding
let utf16Hex = String(format: "%04x", utf16)
return "_0\(utf16Hex)"
} else {
fatalError("Invalid JNI character: \($0)")
}
}
.joined()
}
/// Looks up self as a SwiftJava wrapped class name and converts it
/// into a `JavaType.class` if it exists in `lookupTable`.
func parseJavaClassFromSwiftJavaName(in lookupTable: [String: String]) -> JavaType? {
guard let canonicalJavaName = lookupTable[self] else {
return nil
}
let nameParts = canonicalJavaName.components(separatedBy: ".")
let javaPackageName = nameParts.dropLast().joined(separator: ".")
let javaClassName = nameParts.last!
return .class(package: javaPackageName, name: javaClassName)
}
}
extension Array where Element == String {
func joinedJavaStatements(indent: Int) -> String {
if self.count == 1 {
return "\(self.first!);"
}
let indentation = String(repeating: " ", count: indent)
return self.joined(separator: ";\n\(indentation)")
}
}