Skip to content

Commit

Permalink
Merge pull request #5 from alta/ydnar/swift-format
Browse files Browse the repository at this point in the history
chore: switch to Apple swift-format
  • Loading branch information
ydnar committed Jun 15, 2024
2 parents 6dcdffb + d345206 commit 09315a6
Show file tree
Hide file tree
Showing 14 changed files with 129 additions and 74 deletions.
35 changes: 7 additions & 28 deletions .github/workflows/swift.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,51 +5,30 @@ on:
branches:
- main
paths:
- ".github/workflows/swift.yaml"
- "**.swift"
- "**/Package.resolved"
- "Package.resolved"
pull_request:
paths:
- ".github/workflows/swift.yaml"
- "**.swift"
- "**/Package.resolved"
- "Package.resolved"

jobs:
format:
name: Check SwiftFormat
name: Format
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Checkout repo
uses: actions/checkout@v3
uses: actions/checkout@v4
with:
submodules: recursive

- name: Install SwiftFormat
- name: Install swift-format
uses: Cyberbeni/install-swift-tool@v2
with:
url: https://github.com/nicklockwood/SwiftFormat
url: https://github.com/apple/swift-format

- name: Format Swift code
run: swiftformat --verbose .
run: swift-format -r -i ./

- name: Verify formatted code is unchanged
run: git diff --exit-code HEAD -w -G'(^[^# /])|(^#\w)|(^\s+[^#/])' # Ignore whitespace and comments

test:
name: Test Swift packages
runs-on: ${{ matrix.os }}
timeout-minutes: 10
strategy:
matrix:
os:
- macos-latest
- ubuntu-latest
steps:
- name: Checkout repo
uses: actions/checkout@v3
with:
submodules: recursive

- name: Run tests
run: swift test --enable-test-discovery
34 changes: 34 additions & 0 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
name: Test

on:
push:
branches:
- main
paths:
- ".github/workflows/test.yaml"
- ".gitmodules"
- "**.swift"
- "Package.resolved"
pull_request:
paths:
- ".github/workflows/test.yaml"
- ".gitmodules"
- "**.swift"
- "Package.resolved"

jobs:
test:
name: Test
runs-on: macos-latest
timeout-minutes: 10
steps:
- name: Checkout repo
uses: actions/checkout@v4
with:
submodules: recursive

- name: Test
run: swift test

- name: Generate release build
run: swift build -c release
13 changes: 13 additions & 0 deletions .swift-format
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"version": 1,
"lineLength": 2048,
"indentation": {
"tabs": 1
},
"tabWidth": 4,
"maximumBlankLines": 1,
"respectsExistingLineBreaks": true,
"lineBreakBeforeControlFlowKeywords": true,
"lineBreakBeforeEachArgument": false,
"prioritizeKeepingFunctionOutputTogether": true
}
6 changes: 0 additions & 6 deletions .swiftformat

This file was deleted.

11 changes: 9 additions & 2 deletions .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
{
// List of extensions which should be recommended for users of this workspace.
// See http://go.microsoft.com/fwlink/?LinkId=827846 to learn about workspace recommendations.
// Extension identifier format: ${publisher}.${name}. Example: vscode.csharp
"recommendations": [
"davidanson.vscode-markdownlint",
"eamodio.gitlens",
"eriklynd.json-tools",
"foxundermoon.shell-format",
"redhat.vscode-yaml",
"stkb.rewrap",
"vknabel.vscode-swiftformat",
"vknabel.vscode-apple-swift-format",
"xaver.clang-format",
]
],
// List of extensions recommended by VS Code that should not be recommended for users of this workspace.
"unwantedRecommendations": []
}
41 changes: 36 additions & 5 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,33 +1,52 @@
{
// Editor
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
"source.fixAll.eslint": "explicit"
},
"editor.detectIndentation": false,
"editor.formatOnSave": true,
"editor.insertSpaces": false,
"editor.tabSize": 8,
"editor.tabSize": 4,
"files.eol": "\n",
//
// Files
"files.exclude": {
"**/.build": true,
"**/.git": true,
// "Sources/Copus": true,
},
"files.associations": {},
"files.insertFinalNewline": true,
"files.watcherExclude": {
"**/.git/objects/**": true,
"**/.git/subtree-cache/**": true,
},
"files.trimTrailingWhitespace": true,
//
// HTML
"html.format.contentUnformatted": "pre,code,textarea,script",
"html.format.unformatted": "pre,code,textarea,script,wbr",
//
// JSON
"[json]": {
"editor.defaultFormatter": "vscode.json-language-features",
},
"[jsonc]": {
"editor.defaultFormatter": "vscode.json-language-features",
},
//
// Make
"[makefile]": {
"editor.tabSize": 4
},
//
// Markdown
"[markdown]": {
"editor.rulers": [
80
],
"editor.codeActionsOnSave": {
"source.fixAll.markdownlint": true
"source.fixAll.markdownlint": "explicit"
}
},
"markdown.preview.breaks": true,
Expand All @@ -41,7 +60,7 @@
// Property Lists
"[plist]": {
"editor.formatOnSave": true,
"editor.tabSize": 8,
"editor.tabSize": 4,
},
//
// Shell
Expand All @@ -51,8 +70,9 @@
//
// Swift
"[swift]": {
"editor.detectIndentation": true,
"editor.insertSpaces": false,
"editor.tabSize": 8,
"editor.tabSize": 4,
},
//
// YAML
Expand All @@ -67,4 +87,15 @@
"strings": true
}
},
"[github-actions-workflow]": {
"editor.autoIndent": "keep",
"editor.detectIndentation": true,
"editor.insertSpaces": true,
"editor.tabSize": 2,
"editor.quickSuggestions": {
"other": true,
"comments": false,
"strings": true
}
}
}
2 changes: 1 addition & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ let package = Package(
.library(
name: "RTP",
targets: ["RTP"]
),
)
],
dependencies: [],
targets: [
Expand Down
6 changes: 4 additions & 2 deletions Sources/RTP/Connection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -50,14 +50,16 @@
if let error = error {
print("Error receiving UDP packet: \(error)")
return
} else if let data = data {
}
else if let data = data {
// print("⬇️ Received UDP packet of size: \(data.count)")

do {
let packet = try Packet(from: data)
// print("🅿️ Parsed RTP packet: \(packet)")
self?.receiverBlock(packet)
} catch {
}
catch {
print("Error handling RTP: \(error)")
return
}
Expand Down
6 changes: 3 additions & 3 deletions Sources/RTP/Data+Extensions.swift
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import Foundation

internal extension Data {
extension Data {
// big returns a big-endian integer of type T extracted from the bytes at the specified offset.
func big<T: FixedWidthInteger>(at offset: Int) -> T {
var value: T = 0
withUnsafeMutablePointer(to: &value) {
self.copyBytes(to: UnsafeMutableBufferPointer(start: $0, count: 1), from: offset ..< offset + MemoryLayout<T>.size)
self.copyBytes(to: UnsafeMutableBufferPointer(start: $0, count: 1), from: offset..<offset + MemoryLayout<T>.size)
}
return T(bigEndian: value)
}
Expand All @@ -14,7 +14,7 @@ internal extension Data {
func little<T: FixedWidthInteger>(at offset: Int) -> T {
var value: T = 0
withUnsafeMutablePointer(to: &value) {
self.copyBytes(to: UnsafeMutableBufferPointer(start: $0, count: 1), from: offset ..< offset + MemoryLayout<T>.size)
self.copyBytes(to: UnsafeMutableBufferPointer(start: $0, count: 1), from: offset..<offset + MemoryLayout<T>.size)
}
return T(littleEndian: value)
}
Expand Down
4 changes: 2 additions & 2 deletions Sources/RTP/FixedWidthInteger+Extensions.swift
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import Foundation

public extension FixedWidthInteger {
extension FixedWidthInteger {
// random is a convenience function to generate a random value of the concrete type in [min,max]
static func random() -> Self {
public static func random() -> Self {
Self.random(in: .min ... .max)
}
}
23 changes: 9 additions & 14 deletions Sources/RTP/Packet.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public struct Packet {
public let padding: UInt8

var payloadWithoutPadding: Data {
payload[0 ..< payload.count - Int(padding)]
payload[0..<payload.count - Int(padding)]
}

var encodedSize: Int {
Expand Down Expand Up @@ -81,9 +81,7 @@ public struct Packet {
}
let hasPadding = (data[0] & Self.paddingMask) != 0
let hasExtension = (data[0] & Self.extensionMask) != 0
let sizeWithPaddingAndExtension = Self.headerSize +
(hasPadding ? 1 : 0) +
(hasExtension ? Extension.headerSize : 0)
let sizeWithPaddingAndExtension = Self.headerSize + (hasPadding ? 1 : 0) + (hasExtension ? Extension.headerSize : 0)

// Parse second octet
marker = (data[Self.markerOffset] & Self.markerMask) != 0
Expand All @@ -106,10 +104,11 @@ public struct Packet {

// Parse optional CSRCs in octets 13+
if csrcCount > 0 {
csrcs = (0 ..< csrcCount).map {
csrcs = (0..<csrcCount).map {
data.big(at: Self.csrcOffset + $0)
}
} else {
}
else {
csrcs = nil
}

Expand All @@ -130,14 +129,10 @@ public struct Packet {
var data = Data(capacity: encodedSize)

// Encode first octect (version, padding, extension)
data.append(contentsOf: [(Self.version << 6 & Self.versionMask) |
(padding > 0 ? Self.paddingMask : 0) |
(`extension` != nil ? Self.extensionMask : 0) |
(UInt8(csrcs?.count ?? 0) & Self.csrcCountMask)])
data.append(contentsOf: [(Self.version << 6 & Self.versionMask) | (padding > 0 ? Self.paddingMask : 0) | (`extension` != nil ? Self.extensionMask : 0) | (UInt8(csrcs?.count ?? 0) & Self.csrcCountMask)])

// Encode second octet
data.append(contentsOf: [(marker ? Self.markerMask : 0) |
(payloadType.rawValue & Self.payloadTypeMask)])
data.append(contentsOf: [(marker ? Self.markerMask : 0) | (payloadType.rawValue & Self.payloadTypeMask)])

// Encode sequence number
data.append(contentsOf: [UInt8(sequenceNumber >> 8 & 0xFF), UInt8(sequenceNumber & 0xFF)])
Expand All @@ -150,7 +145,7 @@ public struct Packet {

// Encode CSRCs
if let csrcs = csrcs {
for i in 0 ..< csrcs.count {
for i in 0..<csrcs.count {
data.append(contentsOf: [UInt8(csrcs[i] >> 24 & 0xFF), UInt8(csrcs[i] >> 16 & 0xFF), UInt8(csrcs[i] >> 8 & 0xFF), UInt8(csrcs[i] & 0xFF)])
}
}
Expand Down Expand Up @@ -203,7 +198,7 @@ public struct Extension {
throw EncodingError.extensionDataTooSmall(size)
}

payload = data[Self.headerSize ..< size]
payload = data[Self.headerSize..<size]
}
}

Expand Down
2 changes: 1 addition & 1 deletion Tests/RTPTests/ConnectionTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
XCTAssertEqual(conn.conn.state, .cancelled)
conn.conn.restart()
sleep(1)
XCTAssertEqual(conn.conn.state, .cancelled) // NWConnection instances cannot be restarted once cancelled
XCTAssertEqual(conn.conn.state, .cancelled) // NWConnection instances cannot be restarted once cancelled
}
}

Expand Down
10 changes: 5 additions & 5 deletions Tests/RTPTests/PacketTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ import XCTest
class PacketTests: XCTestCase {
func testInitWithData() throws {
let bytes: [UInt8] = [
2 << 6, // Version 2, no marker or extension
111, // Opus payload type
0, 123, // Sequence number 123
0, 0, 0, 1, // Timestamp 1
0, 255, 255, 255, // SSRC 0x00FFFFFF
2 << 6, // Version 2, no marker or extension
111, // Opus payload type
0, 123, // Sequence number 123
0, 0, 0, 1, // Timestamp 1
0, 255, 255, 255, // SSRC 0x00FFFFFF
]

let packet = try RTP.Packet(from: Data(bytes))
Expand Down
Loading

0 comments on commit 09315a6

Please sign in to comment.