# avcloudy/bencode architecture

> Architecture diagram of the GitHub repository avcloudy/bencode, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-03-12). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/avcloudy/bencode
- Repository: https://github.com/avcloudy/bencode

## Overview

##### Project type & purpose (what you’re diagramming)

Key signals:
- `Package.swift` ⇒ SPM package
- `Sources/Bencode/*` ⇒ single library module named **Bencode**
- Async initializer `Bencode(file:)` ⇒ filesystem I/O path
- `Tests/BencodeTests` + `.torrent` fixtures ⇒ verification against real-world torrent data

##### File structure analysis (map folders to architectural components)

- **SPM Package**
- `Package.swift` (build + target definition)
- **Library Module: Bencode**
- `Sources/Bencode/Bencode.swift` (core type + public API, likely the central “domain model”)
- `Sources/Bencode/Bencoder.swift` (encoding logic: Bencode → bytes)
- `Sources/Bencode/BencodeError.swift` (typed error model)
- **Test Suite**
- `Tests/BencodeTests/BencodeTests.swift` (unit/integration tests)
- `Tests/BencodeTests/Resources/*.torrent` (real torrent fixtures)

This structure strongly suggests a **single-module, layered internal design**:
- Public facade (`Bencode` type) delegates to:
- Decoder/parsing logic (likely in `Bencode.swift` or split across helper code)
- Encoder logic (`Bencoder`)
- Error typing (`BencodeError`)

##### README insights that should appear
- Construction paths:
- `Bencode(file: URL)` **async** → reads file → parses bytes
- `Bencode(bencodedString:)` → converts string → parses
- `Bencode(data: Data)` → parses directly
- Access pattern:
- Subscript-like access `bencode["info"]`, `metadata["announce-list"]`, indexing lists `announceList?[0]`
- Hashing:
- `infoDict.hexHashed` (indicates a hashing function over bencoded output; in torrent world this is typically SHA-1 of the `info` dictionary’s encoded bytes)
- Output:
- `bencode.encoded` returns `Data`

##### Client Code (External)
- “macOS torrent client / tracker tool / any Swift app”
- Calls into the library

##### Bencode Module (Library)
- **Public API / Facade:** `Bencode` (from `Bencode.swift`)
- **Decoder / Parser:** (wherever parsing lives; if not separate file, represent as “Parser” subcomponent within the module)
- **Encoder:** `Bencoder` (from `Bencoder.swift`)
- **Error Types:** `BencodeError` (from `BencodeError.swift`)
- **Hashing Utility:** (represent as “Hasher” or “hexHashed” capability; may be extension(s) in `Bencode.swift`)

##### System Resources / Dependencies
- **File System** (only for the async `Bencode(file:)` path)
- **Swift Standard Library / Foundation**
- `Data`, `URL`, string encoding, etc.

##### Test Harness
- `BencodeTests`
- Fixture `.torrent` resources

**Primary decode flows**
- Client → `Bencode(file: URL)` → File System → `Data` → Parser → `Bencode` in-memory structure
- Client → `Bencode(data: Data)` → Parser → `Bencode` structure
- Client → `Bencode(bencodedString:)` → String→Data conversion → Parser → `Bencode` structure

**Primary encode flow**
- Client → `bencode.encoded` → `Bencoder` → `Data` (bytes)

**Hash flow**
- Client → `bencode["info"].hexHashed` → (Hasher) → digest string

**Error flow**
- Parser / Encoder → throws `BencodeError` → Client handles typed errors

**Tests**
- Tests → call same public API → use fixture `.torrent` data → assert structure / encoded output / hashes / errors

##### Important patterns/design principles
For this project, emphasize:

- **Facade pattern:** `Bencode` as the single “user-facing” entrypoint that hides parsing/encoding complexity.
- **Separation of concerns:**
- Parsing/decoding vs encoding in `Bencoder`
- Typed errors in `BencodeError`
- **Async I/O boundary:** `Bencode(file:)` is async and is the boundary between “external world” (filesystem) and pure parsing logic.
- **Pure-data core:** once constructed from `Data`, most operations should be deterministic and side-effect free (encode, hash, indexing).

##### Relevant technologies
- **Swift 6.2 / async/await**
- **SPM package**
- **Foundation (`Data`, `URL`)**
- **Bencode encoding format** (binary/text hybrid format used by BitTorrent)

To be maximally accurate and detailed for this codebase, include all of the following nodes:

- **Client App**
- calls `Bencode(...)` initializers
- reads properties/subscripts
- calls `.encoded` and `.hexHashed`
- **Bencode (Facade / Model)**
- represents variants: `int`, `string(Data)`, `list`, `dict([Data: Bencode])`
- **Decoder/Parser**
- consumes `Data` sequentially
- outputs `Bencode` structure
- throws `BencodeError`
- **Bencoder**
- consumes `Bencode`
- outputs `Data`
- **Hasher**
- consumes encoded bytes of a `Bencode` value (esp. `info` dict)
- outputs hex string
- **BencodeError**
- enumerates parse/encode errors (show at least `badKey` since README mentions it)
- **File System (async path)**
- only used by `Bencode(file:)`
- **Tests**
- `BencodeTests`
- `.torrent` fixtures (Fedora, Debian)

## Diagram (Mermaid)

```mermaid
flowchart TD
    %% =========================
    %% External / Clients
    %% =========================
    Client["Client Code (External)\nSwift app / torrent tool"]:::external

    subgraph "System Resources / Dependencies"
        Foundation["Foundation\nData / URL / String encoding"]:::dep
        FS[("File System")]:::external
        BencodeFormat["Bencode Format\n(BitTorrent)"]:::note
    end

    %% =========================
    %% SPM Package / Build
    %% =========================
    subgraph "SPM Package"
        Package["Package.swift\n(SPM manifest)"]:::build
        TargetDir["Target: Bencode\n(Sources/Bencode)"]:::module
        TestTargetDir["Test Target: BencodeTests\n(Tests/BencodeTests)"]:::test
    end

    Package -->|"definesTargets"| TargetDir
    Package -->|"definesTestTargets"| TestTargetDir

    %% =========================
    %% Library Module: Bencode
    %% =========================
    subgraph "Library Module: Bencode"
        BencodeFacade["Bencode (Facade + Core Model)\n- init(file: URL) async\n- init(data: Data)\n- init(bencodedString: String)\n- subscript/access\n- encoded: Data\n- hexHashed"]:::api

        subgraph "Public API Surface"
            InitFile["Bencode(file: URL) async"]:::api
            InitData["Bencode(data: Data)"]:::api
            InitString["Bencode(bencodedString: String)"]:::api
            Accessors["Accessors\nsubscript/keyPath + list indexing"]:::api
            EncodedProp["encoded -> Data"]:::api
            HexHashedProp["hexHashed -> String"]:::api
        end

        subgraph "Internal Components"
            Parser["Decoder / Parser\n(consumes Data sequentially)"]:::internal
            Encoder["Bencoder\n(Bencode -> Data)"]:::internal
            Hasher["Hasher\n(digest of encoded bytes)\n(info dict)"]:::internal
            Err["BencodeError\n(typed errors e.g., badKey)"]:::error
        end

        BencodeTree["In-memory Bencode Tree\nint / string(Data) / list / dict([Data: Bencode])"]:::model
    end

    %% Tie facade to API nodes (conceptual)
    BencodeFacade -.->|"exposes"| InitFile
    BencodeFacade -.->|"exposes"| InitData
    BencodeFacade -.->|"exposes"| InitString
    BencodeFacade -.->|"exposes"| Accessors
    BencodeFacade -.->|"exposes"| EncodedProp
    BencodeFacade -.->|"exposes"| HexHashedProp

    %% Dependencies
    BencodeFacade -.->|"uses"| Foundation
    InitString -.->|"stringToData"| Foundation
    InitData -.->|"acceptsData"| Foundation
    InitFile -.->|"usesURL"| Foundation

    %% Decode flows
    Client -->|"calls"| InitFile
    InitFile -->|"asyncRead"| FS
    FS -->|"Data(bencodedBytes)"| Parser

    Client -->|"calls"| InitData
    InitData -->|"Data(bencodedBytes)"| Parser

    Client -->|"calls"| InitString
    InitString -->|"toData(utf8)"| Parser

    Parser -->|"builds"| BencodeTree
    Parser -->|"returns"| BencodeFacade

    %% Error flow
    Parser -->|"throws"| Err
    Encoder -->|"throws"| Err
    Err -->|"propagatesTo"| Client

    %% Access / operations
    Client -->|"reads"| Accessors
    Accessors -->|"navigates"| BencodeTree

    Client -->|"calls"| EncodedProp
    EncodedProp -->|"delegates"| Encoder
    Encoder -->|"Data(bencodedBytes)"| Foundation
    Encoder -->|"returnsBytesTo"| EncodedProp
    EncodedProp -->|"returnsDataTo"| Client

    Client -->|"calls"| HexHashedProp
    HexHashedProp -->|"encodesInfoDict"| Encoder
    Encoder -->|"bytes"| Hasher
    Hasher -->|"hexDigest"| HexHashedProp
    HexHashedProp -->|"returnsStringTo"| Client

    %% Format note
    Parser -.->|"parses"| BencodeFormat
    Encoder -.->|"emits"| BencodeFormat

    %% =========================
    %% Tests
    %% =========================
    subgraph "Test Suite: BencodeTests"
        TestsNode["BencodeTests\n(unit + integration)"]:::test
        Fixtures[("Resources/*.torrent\n(Fedora, Debian, etc.)")]:::fixture
    end

    Fixtures -->|"fixtureData"| TestsNode
    TestsNode -->|"callsPublicAPI"| BencodeFacade
    TestsNode -->|"verifiesDecode/Encode/Hash/Errors"| BencodeTree
    TestsNode -->|"expectsThrows"| Err

    %% =========================
    %% Click Events (from mapping)
    %% =========================
    click Package "https://github.com/avcloudy/bencode/blob/main/Package.swift"
    click TargetDir "https://github.com/avcloudy/bencode/tree/main/Sources/Bencode/"
    click BencodeFacade "https://github.com/avcloudy/bencode/blob/main/Sources/Bencode/Bencode.swift"
    click Encoder "https://github.com/avcloudy/bencode/blob/main/Sources/Bencode/Bencoder.swift"
    click Err "https://github.com/avcloudy/bencode/blob/main/Sources/Bencode/BencodeError.swift"
    click TestTargetDir "https://github.com/avcloudy/bencode/tree/main/Tests/BencodeTests/"
    click TestsNode "https://github.com/avcloudy/bencode/blob/main/Tests/BencodeTests/BencodeTests.swift"
    click Fixtures "https://github.com/avcloudy/bencode/tree/main/Tests/BencodeTests/Resources/"

    %% =========================
    %% Styles
    %% =========================
    classDef external fill:#E8F4FF,stroke:#1E5AA8,stroke-width:1.5px,color:#0B2A4A
    classDef dep fill:#E9FFF1,stroke:#1F7A3B,stroke-width:1.5px,color:#0E3A1D
    classDef build fill:#FFF4E5,stroke:#B26A00,stroke-width:1.5px,color:#4A2B00
    classDef module fill:#F2ECFF,stroke:#5A3DB8,stroke-width:1.5px,color:#2A1B5E
    classDef api fill:#DCEEFF,stroke:#2563EB,stroke-width:1.5px,color:#0B2A4A
    classDef internal fill:#F2F4F7,stroke:#475569,stroke-width:1.5px,color:#111827
    classDef model fill:#E6FFFB,stroke:#0F766E,stroke-width:1.5px,color:#083344
    classDef error fill:#FFE4E6,stroke:#BE123C,stroke-width:1.5px,color:#4C0519
    classDef test fill:#F0FDF4,stroke:#166534,stroke-width:1.5px,color:#052E16
    classDef fixture fill:#ECFCCB,stroke:#3F6212,stroke-width:1.5px,color:#1A2E05
    classDef note fill:#FFF7ED,stroke:#9A3412,stroke-width:1.5px,color:#431407
```
