Skip to content

Commit

Permalink
FieldData: Add hex conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
scchn committed Jan 16, 2024
1 parent 6e420b1 commit e8e652a
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 3 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/swift.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,6 @@ jobs:
steps:
- uses: actions/checkout@v3
- name: Build
run: swift build -v
run: swift build
- name: Run tests
run: swift test -v
run: swift test
16 changes: 15 additions & 1 deletion Sources/ZPLBuilder/Commands/FieldData.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,13 @@

import Foundation

/// The ^FD command defines the data string for a field.
extension FieldData {
#if canImport(CoreFoundation.CFString) && canImport(CoreFoundation.CFStringEncodingExt)
public static var big5Encoding: String.Encoding = .big5
#endif
}

/// The ^FD command defines the data string for a field.
/// The field data can be any printable character except those used as command prefixes (^ and ~).
///
/// # Field Data
Expand All @@ -32,4 +38,12 @@ public struct FieldData: ZPLCommandConvertible {
public init(text: String) {
self.text = text
}

public init(text: String, encoding: String.Encoding, indicator: Character) {
self.text = text.data(using: encoding)?
.map {
String(format:"\(indicator)%02X", $0)
}
.joined() ?? ""
}
}
19 changes: 19 additions & 0 deletions Sources/ZPLBuilder/_Extensions/String+Big5.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
//
// String+Big5.swift
//
//
// Created by 陳世爵 on 2024/1/16.
//

#if canImport(CoreFoundation.CFString) && canImport(CoreFoundation.CFStringEncodingExt)
import Foundation

extension String.Encoding {
static var big5: String.Encoding {
let _encoding = CFStringEncoding(CFStringEncodings.big5.rawValue)
let encoding = CFStringConvertEncodingToNSStringEncoding(_encoding)

return .init(rawValue: encoding)
}
}
#endif
11 changes: 11 additions & 0 deletions Tests/ZPLBuilderTests/ZPLCommandTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,15 @@ class ZPLCommandTests: XCTestCase {
let cmd = HostDirectoryList(deviceLocation: .e, objectName: "*", extension: "FNT")
XCTAssertEqual(cmd.command, "^HWE:*.FNT")
}

#if canImport(CoreFoundation.CFString) && canImport(CoreFoundation.CFStringEncodingExt)
func test_field_data() {
let cmd = FieldData(text: "TEST哈囉ㄏㄚˋ啦", encoding: FieldData.big5Encoding, indicator: "_")

XCTAssertEqual(
"^FD_54_45_53_54_AB_A2_C5_6F_A3_7E_A3_AB_A3_BF_B0_D5",
cmd.command
)
}
#endif
}

0 comments on commit e8e652a

Please sign in to comment.