usb-ids-1.2025.1/.cargo_vcs_info.json0000644000000001360000000000100126320ustar { "git": { "sha1": "d02dcfc57ed48fe1b5fad5c2e06f06db07dede6e" }, "path_in_vcs": "" }usb-ids-1.2025.1/.github/dependabot.yml000064400000000000000000000003061046102023000156110ustar 00000000000000version: 2 updates: - package-ecosystem: cargo directory: "/" schedule: interval: weekly - package-ecosystem: github-actions directory: / schedule: interval: weekly usb-ids-1.2025.1/.github/workflows/ci.yml000064400000000000000000000011551046102023000161370ustar 00000000000000name: CI on: push: branches: - main pull_request: jobs: lint: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Format run: cargo fmt && git diff --exit-code - name: Lint run: | rustup update rustup component add clippy cargo clippy -- -D warnings test: strategy: matrix: platform: ["ubuntu-latest", "macos-latest", "windows-latest"] runs-on: ${{ matrix.platform }} steps: - uses: actions/checkout@v4 - name: Build run: cargo build - name: Test run: cargo test usb-ids-1.2025.1/.github/workflows/release.yml000064400000000000000000000011361046102023000171630ustar 00000000000000on: push: tags: - 'v*' name: release jobs: create-release: name: create GitHub release runs-on: ubuntu-latest permissions: contents: write steps: - name: Release uses: softprops/action-gh-release@v2 with: prerelease: ${{ contains(github.ref, 'pre') || contains(github.ref, 'rc') }} publish: needs: - create-release runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: publish to crates.io run: | echo ${{ secrets.CRATES_IO_TOKEN }} | cargo login cargo publish usb-ids-1.2025.1/.github/workflows/usbids-updater.yml000064400000000000000000000013651046102023000205020ustar 00000000000000name: check for updates to usb.ids on: schedule: - cron: '0 12 * * *' jobs: check-usbids: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: try to update usb.ids run: | curl -o src/usb.ids https://usb-ids.gowdy.us/usb.ids - name: create PR uses: peter-evans/create-pull-request@v7 with: commit-message: "[BOT] update usb.ids" branch: update-usbids branch-suffix: timestamp title: "[BOT] update usb.ids" body: | This is an automated pull request, updating `usb.ids` after a detected change. Please review manually before merging. assignees: "woodruffw" reviewers: "woodruffw" usb-ids-1.2025.1/.gitignore000064400000000000000000000000231046102023000134050ustar 00000000000000/target Cargo.lock usb-ids-1.2025.1/CHANGELOG.md000064400000000000000000000101061046102023000132310ustar 00000000000000# Changelog All notable changes to `usb-ids` will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [Unreleased] - ReleaseDate ## [1.2025.1] - 2025-01-15 ## [1.2024.5] - 2024-12-09 ## [1.2024.4] - 2024-07-08 ## [1.2024.3] - 2024-04-26 ## [1.2024.2] - 2024-01-31 ## [1.2024.1] - 2024-01-21 ## [1.2023.7] - 2023-11-19 * Support for additional identities in the USB ID repository has been expanded significantly; see the docs for additional new APIs. [#50](https://github.com/woodruffw/usb-ids.rs/pull/50) ## [1.2023.6] - 2023-10-18 ## [1.2023.5] - 2023-08-25 ## [1.2023.4] - 2023-08-19 ## [1.2023.3] - 2023-08-05 ## [1.2023.2] - 2023-04-30 ## [1.2023.1] - 2023-04-24 ## [1.2023.0] - 2023-01-18 * The date-style versioning used by this crate is now (`v1.YYYY.SEQUENCE`), where `1` indicates the current API version, `YYYY` is the current year, and `SEQUENCE` is an increasing sequence number for the year. This was changed to prevent versions that would otherwise be illegal in the crate ecosystem, like `v1.2023.0117`. ## [1.2022.1224] - 2022-12-25 ### Changed * The date-style versioning used by this crate is now (`v1.YYYY.MMDD`), where `1` indicates the current API version and `YYYY.MMDD` is the date of release. ## [2022.12.24] - 2022-12-25 **YANKED**. ### Changed * This crate now uses date-style versioning (`vYYYY.MM.DD`) and is considered stable. This release contains the usb.ids database as of `2022-12-15 20:34:08`. ## [0.2.5] - 2022-11-29 ## [0.2.4] - 2022-09-09 ## [0.2.3] - 2022-09-09 ## [0.2.2] - 2022-03-29 ### Changed * DB: Updates to the USB DB (+146, -15) ## [0.2.1] - 2021-07-03 ## [0.2.0] - 2021-06-24 ## [0.1.0] - 2021-06-24 ## [0.0.3] - 2021-01-31 ### Added * Routine DB update (2021-01-29 20:34:11) ## [0.0.2] - 2020-12-26 ### Added * Added `Device::from_vid_pid`. ## [0.0.1] - 2020-12-26 ### Added * This is the initial release of `usb-ids`. [Unreleased]: https://github.com/woodruffw/usb-ids.rs/compare/v1.2025.1...HEAD [1.2025.1]: https://github.com/woodruffw/usb-ids.rs/compare/v1.2024.5...v1.2025.1 [1.2024.5]: https://github.com/woodruffw/usb-ids.rs/compare/v1.2024.4...v1.2024.5 [1.2024.4]: https://github.com/woodruffw/usb-ids.rs/compare/v1.2024.3...v1.2024.4 [1.2024.3]: https://github.com/woodruffw/usb-ids.rs/compare/v1.2024.2...v1.2024.3 [1.2024.2]: https://github.com/woodruffw/usb-ids.rs/compare/v1.2024.1...v1.2024.2 [1.2024.1]: https://github.com/woodruffw/usb-ids.rs/compare/v1.2023.7...v1.2024.1 [1.2023.7]: https://github.com/woodruffw/usb-ids.rs/compare/v1.2023.6...v1.2023.7 [1.2023.6]: https://github.com/woodruffw/usb-ids.rs/compare/v1.2023.5...v1.2023.6 [1.2023.5]: https://github.com/woodruffw/usb-ids.rs/compare/v1.2023.4...v1.2023.5 [1.2023.4]: https://github.com/woodruffw/usb-ids.rs/compare/v1.2023.3...v1.2023.4 [1.2023.3]: https://github.com/woodruffw/usb-ids.rs/compare/v1.2023.2...v1.2023.3 [1.2023.2]: https://github.com/woodruffw/usb-ids.rs/compare/v1.2023.1...v1.2023.2 [1.2023.1]: https://github.com/woodruffw/usb-ids.rs/compare/v1.2023.0...v1.2023.1 [1.2023.0]: https://github.com/woodruffw/usb-ids.rs/compare/v1.2022.1224...v1.2023.0 [1.2022.1224]: https://github.com/woodruffw/usb-ids.rs/compare/v2022.12.24...v1.2022.1224 [2022.12.24]: https://github.com/woodruffw/usb-ids.rs/compare/v0.2.5...v2022.12.24 [0.2.5]: https://github.com/woodruffw/usb-ids.rs/compare/v0.2.4...v0.2.5 [0.2.4]: https://github.com/woodruffw/usb-ids.rs/compare/v0.2.3...v0.2.4 [0.2.3]: https://github.com/woodruffw/usb-ids.rs/compare/v0.2.2...v0.2.3 [0.2.2]: https://github.com/woodruffw/usb-ids.rs/compare/v0.2.1...v0.2.2 [0.2.1]: https://github.com/woodruffw/usb-ids.rs/compare/v0.2.0...v0.2.1 [0.2.0]: https://github.com/woodruffw/usb-ids.rs/compare/v0.1.0...v0.2.0 [0.1.0]: https://github.com/woodruffw/usb-ids.rs/compare/v0.0.3...v0.1.0 [0.0.3]: https://github.com/woodruffw/usb-ids.rs/compare/v0.0.2...v0.0.3 [0.0.2]: https://github.com/woodruffw/usb-ids.rs/compare/v0.0.1...v0.0.2 [0.0.1]: https://github.com/woodruffw/usb-ids.rs/releases/tag/v0.0.1 usb-ids-1.2025.1/Cargo.toml0000644000000042210000000000100106270ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "usb-ids" version = "1.2025.1" authors = ["William Woodruff "] build = "build.rs" autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "Rust wrappers for the USB ID Repository" homepage = "https://github.com/woodruffw/usb-ids.rs" readme = "README.md" keywords = ["usb"] categories = ["hardware-support"] license = "MIT" repository = "https://github.com/woodruffw/usb-ids.rs" [package.metadata.release] publish = false push = true [[package.metadata.release.pre-release-replacements]] exactly = 2 file = "CHANGELOG.md" replace = "{{version}}" search = "Unreleased" [[package.metadata.release.pre-release-replacements]] exactly = 1 file = "CHANGELOG.md" replace = "{{date}}" search = "ReleaseDate" [[package.metadata.release.pre-release-replacements]] exactly = 1 file = "CHANGELOG.md" replace = "...{{tag_name}}" search = '\.\.\.HEAD' [[package.metadata.release.pre-release-replacements]] exactly = 1 file = "CHANGELOG.md" replace = """ ## [Unreleased] - ReleaseDate""" search = "" [[package.metadata.release.pre-release-replacements]] exactly = 1 file = "CHANGELOG.md" replace = """ [Unreleased]: https://github.com/woodruffw/usb-ids.rs/compare/{{tag_name}}...HEAD""" search = "" [lib] name = "usb_ids" path = "src/lib.rs" [dependencies.phf] version = "0.11" [build-dependencies.nom] version = "7.0" default-features = false [build-dependencies.phf_codegen] version = "0.11" [build-dependencies.proc-macro2] version = "1.0" [build-dependencies.quote] version = "1.0" [badges.maintenance] status = "actively-developed" usb-ids-1.2025.1/Cargo.toml.orig0000644000000027460000000000100116000ustar [package] name = "usb-ids" description = "Rust wrappers for the USB ID Repository" license = "MIT" version = "1.2025.1" authors = ["William Woodruff "] edition = "2018" readme = "README.md" homepage = "https://github.com/woodruffw/usb-ids.rs" repository = "https://github.com/woodruffw/usb-ids.rs" keywords = ["usb"] categories = ["hardware-support"] [build-dependencies] nom = { version = "7.0", default-features = false } phf_codegen = "0.11" quote = "1.0" proc-macro2 = "1.0" [dependencies] phf = "0.11" [badges] maintenance = { status = "actively-developed" } [package.metadata.release] publish = false # handled by GitHub Actions push = true [[package.metadata.release.pre-release-replacements]] file = "CHANGELOG.md" search = "Unreleased" replace = "{{version}}" exactly = 2 [[package.metadata.release.pre-release-replacements]] file = "CHANGELOG.md" search = "ReleaseDate" replace = "{{date}}" exactly = 1 [[package.metadata.release.pre-release-replacements]] file = "CHANGELOG.md" search = "\\.\\.\\.HEAD" replace = "...{{tag_name}}" exactly = 1 [[package.metadata.release.pre-release-replacements]] file = "CHANGELOG.md" search = "" replace = "\n\n## [Unreleased] - ReleaseDate" exactly = 1 [[package.metadata.release.pre-release-replacements]] file = "CHANGELOG.md" search = "" replace = "\n[Unreleased]: https://github.com/woodruffw/usb-ids.rs/compare/{{tag_name}}...HEAD" exactly = 1 usb-ids-1.2025.1/Cargo.toml.orig000064400000000000000000000027461046102023000143220ustar 00000000000000[package] name = "usb-ids" description = "Rust wrappers for the USB ID Repository" license = "MIT" version = "1.2025.1" authors = ["William Woodruff "] edition = "2018" readme = "README.md" homepage = "https://github.com/woodruffw/usb-ids.rs" repository = "https://github.com/woodruffw/usb-ids.rs" keywords = ["usb"] categories = ["hardware-support"] [build-dependencies] nom = { version = "7.0", default-features = false } phf_codegen = "0.11" quote = "1.0" proc-macro2 = "1.0" [dependencies] phf = "0.11" [badges] maintenance = { status = "actively-developed" } [package.metadata.release] publish = false # handled by GitHub Actions push = true [[package.metadata.release.pre-release-replacements]] file = "CHANGELOG.md" search = "Unreleased" replace = "{{version}}" exactly = 2 [[package.metadata.release.pre-release-replacements]] file = "CHANGELOG.md" search = "ReleaseDate" replace = "{{date}}" exactly = 1 [[package.metadata.release.pre-release-replacements]] file = "CHANGELOG.md" search = "\\.\\.\\.HEAD" replace = "...{{tag_name}}" exactly = 1 [[package.metadata.release.pre-release-replacements]] file = "CHANGELOG.md" search = "" replace = "\n\n## [Unreleased] - ReleaseDate" exactly = 1 [[package.metadata.release.pre-release-replacements]] file = "CHANGELOG.md" search = "" replace = "\n[Unreleased]: https://github.com/woodruffw/usb-ids.rs/compare/{{tag_name}}...HEAD" exactly = 1 usb-ids-1.2025.1/LICENSE000064400000000000000000000021251046102023000124270ustar 00000000000000The MIT License (MIT) Copyright (c) 2022 William Woodruff Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. usb-ids-1.2025.1/README.md000064400000000000000000000014211046102023000126770ustar 00000000000000usb-ids ======= [![CI](https://github.com/woodruffw/usb-ids.rs/actions/workflows/ci.yml/badge.svg)](https://github.com/woodruffw/usb-ids.rs/actions/workflows/ci.yml) [![Crates.io](https://img.shields.io/crates/v/usb-ids)](https://crates.io/crates/usb-ids) Cross-platform Rust wrappers for the [USB ID Repository](http://www.linux-usb.org/usb-ids.html). This library bundles the USB ID database, allowing platforms other than Linux to query it as a source of canonical USB metadata. ## Usage Iterating over all known vendors: ```rust use usb_ids::Vendors; for vendor in Vendors::iter() { for device in vendor.devices() { println!("vendor: {}, device: {}", vendor.name(), device.name()); } } ``` See [the documentation](https://docs.rs/usb-ids) for more details. usb-ids-1.2025.1/build.rs000064400000000000000000000607601046102023000131000ustar 00000000000000use std::env; use std::fs; use std::io::{BufRead, BufReader, BufWriter, Write}; use std::path::Path; use phf_codegen::Map; use quote::quote; /* This build script contains a "parser" for the USB ID database. * "Parser" is in scare-quotes because it's really a line matcher with a small amount * of context needed for pairing nested entities (e.g. devices) with their parents (e.g. vendors). */ // these are the definitions for the generated maps that will be written to the source file const VENDOR_PROLOGUE: &str = "static USB_IDS: phf::Map = "; const CLASS_PROLOGUE: &str = "static USB_CLASSES: phf::Map = "; const AUDIO_TERMINAL_PROLOGUE: &str = "static USB_AUDIO_TERMINALS: phf::Map = "; const HID_ID_PROLOGUE: &str = "static USB_HID_IDS: phf::Map = "; const HID_R_PROLOGUE: &str = "static USB_HID_R_TYPES: phf::Map = "; const BIAS_PROLOGUE: &str = "static USB_BIASES: phf::Map = "; const PHY_PROLOGUE: &str = "static USB_PHYS: phf::Map = "; const HUT_PROLOGUE: &str = "static USB_HUTS: phf::Map = "; const LANG_PROLOGUE: &str = "static USB_LANGS: phf::Map = "; const HID_CC_PROLOGUE: &str = "static USB_HID_CCS: phf::Map = "; const TERMINAL_PROLOGUE: &str = "static USB_VIDEO_TERMINALS: phf::Map = "; trait CgEntry { fn id(&self) -> T; } struct CgVendor { id: u16, name: String, devices: Vec, } struct CgDevice { id: u16, name: String, interfaces: Vec, } struct CgClass { id: u8, name: String, sub_classes: Vec, } type CgSubClass = CgParentType; struct CgParentType { id: T, name: String, children: Vec, } impl> CgEntry for CgParentType { fn id(&self) -> T { self.id } } struct CgType { id: T, name: String, } impl CgEntry for CgType { fn id(&self) -> T { self.id } } type CgInterface = CgType; type CgProtocol = CgType; type CgAtType = CgType; type CgHidType = CgType; type CgRType = CgType; type CgRBiasType = CgType; type CgPhyType = CgType; type CgHidUsage = CgType; type CgHut = CgParentType; type CgDialect = CgType; type CgLang = CgParentType; type CgCountryCode = CgType; type CgTerminalType = CgType; /// Parser state parses only the type for the current section, this is because some /// parsers are ambiguous without context; device.interface == subclass.protocol for example. enum ParserState { Vendors(Map, Option, u16), Classes(Map, Option, u8), AtType(Map, Option), HidType(Map, Option), RType(Map, Option), BiasType(Map, Option), PhyType(Map, Option), HutType(Map, Option), Lang(Map, Option), CountryCode(Map, Option), TerminalType(Map, Option), } impl ParserState { /// Return the prologue string for the current state; the type definition fn prologue_str(&self) -> &'static str { match self { ParserState::Vendors(_, _, _) => VENDOR_PROLOGUE, ParserState::Classes(_, _, _) => CLASS_PROLOGUE, ParserState::AtType(_, _) => AUDIO_TERMINAL_PROLOGUE, ParserState::HidType(_, _) => HID_ID_PROLOGUE, ParserState::RType(_, _) => HID_R_PROLOGUE, ParserState::BiasType(_, _) => BIAS_PROLOGUE, ParserState::PhyType(_, _) => PHY_PROLOGUE, ParserState::HutType(_, _) => HUT_PROLOGUE, ParserState::Lang(_, _) => LANG_PROLOGUE, ParserState::CountryCode(_, _) => HID_CC_PROLOGUE, ParserState::TerminalType(_, _) => TERMINAL_PROLOGUE, } } /// Emit any pending entries to the map fn emit(&mut self) { match self { ParserState::Vendors(m, Some(vendor), _) => { m.entry(vendor.id, "e!(#vendor).to_string()); } ParserState::Classes(m, Some(class), _) => { m.entry(class.id, "e!(#class).to_string()); } ParserState::AtType(m, Some(t)) | ParserState::TerminalType(m, Some(t)) => { m.entry(t.id(), "e!(#t).to_string()); } ParserState::HidType(m, Some(t)) | ParserState::RType(m, Some(t)) | ParserState::BiasType(m, Some(t)) | ParserState::CountryCode(m, Some(t)) | ParserState::PhyType(m, Some(t)) => { m.entry(t.id(), "e!(#t).to_string()); } ParserState::HutType(m, Some(t)) => { m.entry(t.id, "e!(#t).to_string()); } ParserState::Lang(m, Some(t)) => { m.entry(t.id, "e!(#t).to_string()); } _ => {} } } /// Detects the next state based on the header line /// /// Not very efficient but since it only checks # lines and required length it is not terrible fn next_from_header(&mut self, line: &str, output: &mut impl Write) -> Option { if line.len() < 7 || !line.starts_with('#') { return None; } match &line[..7] { "# C cla" => { self.finalize(output); Some(ParserState::Classes(Map::::new(), None, 0u8)) } "# AT te" => { self.finalize(output); Some(ParserState::AtType(Map::::new(), None)) } "# HID d" => { self.finalize(output); Some(ParserState::HidType(Map::::new(), None)) } "# R ite" => { self.finalize(output); Some(ParserState::RType(Map::::new(), None)) } "# BIAS " => { self.finalize(output); Some(ParserState::BiasType(Map::::new(), None)) } "# PHY i" => { self.finalize(output); Some(ParserState::PhyType(Map::::new(), None)) } "# HUT h" => { self.finalize(output); Some(ParserState::HutType(Map::::new(), None)) } "# L lan" => { self.finalize(output); Some(ParserState::Lang(Map::::new(), None)) } "# HCC c" => { self.finalize(output); Some(ParserState::CountryCode(Map::::new(), None)) } "# VT te" => { self.finalize(output); Some(ParserState::TerminalType(Map::::new(), None)) } _ => None, } } /// Process a line of input for the current state fn process(&mut self, line: &str) { if line.is_empty() || line.starts_with('#') { return; } // Switch parser state based on line prefix and current state // this relies on ordering of classes and types in the file... match self { ParserState::Vendors(m, ref mut curr_vendor, ref mut curr_device_id) => { if let Ok((name, id)) = parser::vendor(line) { if let Some(cv) = curr_vendor { m.entry(cv.id, "e!(#cv).to_string()); } // Set our new vendor as the current vendor. *curr_vendor = Some(CgVendor { id, name: name.into(), devices: vec![], }); // We should always have a current vendor; failure here indicates a malformed input. } else { let curr_vendor = curr_vendor .as_mut() .expect("No parent vendor whilst parsing vendors"); if let Ok((name, id)) = parser::device(line) { curr_vendor.devices.push(CgDevice { id, name: name.into(), interfaces: vec![], }); *curr_device_id = id; } else if let Ok((name, id)) = parser::interface(line) { let curr_device = curr_vendor .devices .iter_mut() .find(|d| d.id == *curr_device_id) .expect("No parent device whilst parsing interfaces"); curr_device.interfaces.push(CgInterface { id, name: name.into(), }); } } } ParserState::Classes(m, ref mut curr_class, ref mut curr_class_id) => { if let Ok((name, id)) = parser::class(line) { if let Some(cv) = curr_class { m.entry(cv.id, "e!(#cv).to_string()); } // Set our new class as the current class. *curr_class = Some(CgClass { id, name: name.into(), sub_classes: vec![], }); } else { let curr_class = curr_class .as_mut() .expect("No parent class whilst parsing classes"); if let Ok((name, id)) = parser::sub_class(line) { curr_class.sub_classes.push(CgSubClass { id, name: name.into(), children: vec![], }); *curr_class_id = id; } else if let Ok((name, id)) = parser::protocol(line) { let curr_device = curr_class .sub_classes .iter_mut() .find(|d| d.id == *curr_class_id) .expect("No parent sub-class whilst parsing protocols"); curr_device.children.push(CgProtocol { id, name: name.into(), }); } } } ParserState::AtType(m, ref mut current) => { let (name, id) = parser::audio_terminal_type(line).expect("Invalid audio terminal line"); if let Some(cv) = current { m.entry(cv.id, "e!(#cv).to_string()); } // Set our new class as the current class. *current = Some(CgAtType { id, name: name.into(), }); } ParserState::HidType(m, ref mut current) => { let (name, id) = parser::hid_type(line).expect("Invalid hid type line"); if let Some(cv) = current { m.entry(cv.id, "e!(#cv).to_string()); } // Set our new class as the current class. *current = Some(CgHidType { id, name: name.into(), }); } ParserState::RType(m, ref mut current) => { let (name, id) = parser::hid_item_type(line).expect("Invalid hid item type line"); if let Some(cv) = current { m.entry(cv.id, "e!(#cv).to_string()); } // Set our new class as the current class. *current = Some(CgRType { id, name: name.into(), }); } ParserState::BiasType(m, ref mut current) => { let (name, id) = parser::bias_type(line).expect("Invalid bias type line"); if let Some(cv) = current { m.entry(cv.id, "e!(#cv).to_string()); } // Set our new class as the current class. *current = Some(CgRBiasType { id, name: name.into(), }); } ParserState::PhyType(m, ref mut current) => { let (name, id) = parser::phy_type(line).expect("Invalid phy type line"); if let Some(cv) = current { m.entry(cv.id, "e!(#cv).to_string()); } // Set our new class as the current class. *current = Some(CgPhyType { id, name: name.into(), }); } ParserState::HutType(m, ref mut current) => { if let Ok((name, id)) = parser::hut_type(line) { if let Some(cv) = current { m.entry(cv.id, "e!(#cv).to_string()); } // Set our new class as the current class. *current = Some(CgHut { id, name: name.into(), children: vec![], }); } else { let curr_hut = current.as_mut().expect("No parent hut whilst parsing huts"); if let Ok((name, id)) = parser::hid_usage_name(line) { curr_hut.children.push(CgHidUsage { id, name: name.into(), }); } } } ParserState::Lang(m, ref mut current) => { if let Ok((name, id)) = parser::language(line) { if let Some(cv) = current { m.entry(cv.id, "e!(#cv).to_string()); } // Set our new class as the current class. *current = Some(CgLang { id, name: name.into(), children: vec![], }); } else { let curr_lang = current .as_mut() .expect("No parent lang whilst parsing langs"); if let Ok((name, id)) = parser::dialect(line) { curr_lang.children.push(CgDialect { id, name: name.into(), }); } } } ParserState::CountryCode(m, ref mut current) => { let (name, id) = parser::country_code(line).expect("Invalid country code line"); if let Some(cv) = current { m.entry(cv.id, "e!(#cv).to_string()); } // Set our new class as the current class. *current = Some(CgCountryCode { id, name: name.into(), }); } ParserState::TerminalType(m, ref mut current) => { let (name, id) = parser::terminal_type(line).expect("Invalid terminal type line"); if let Some(cv) = current { m.entry(cv.id, "e!(#cv).to_string()); } // Set our new class as the current class. *current = Some(CgTerminalType { id, name: name.into(), }); } } } /// Emit the prologue and map to the output file. /// /// Should only be called once per state, used before switching. fn finalize(&mut self, output: &mut impl Write) { // Emit any pending contained within self.emit(); // Write the prologue writeln!(output, "{}", self.prologue_str()).unwrap(); // And the map itself match self { ParserState::Vendors(m, _, _) => { writeln!(output, "{};", m.build()).unwrap(); } ParserState::Classes(m, _, _) => { writeln!(output, "{};", m.build()).unwrap(); } ParserState::AtType(m, _) | ParserState::TerminalType(m, _) => { writeln!(output, "{};", m.build()).unwrap(); } ParserState::HidType(m, _) | ParserState::RType(m, _) | ParserState::BiasType(m, _) | ParserState::CountryCode(m, _) | ParserState::PhyType(m, _) => { writeln!(output, "{};", m.build()).unwrap(); } ParserState::HutType(m, _) => { writeln!(output, "{};", m.build()).unwrap(); } ParserState::Lang(m, _) => { writeln!(output, "{};", m.build()).unwrap(); } } } /// Return the next state for the current state based on the standard ordering of the file /// /// Not as robust as the next_from_header but at lot less overhead. The issue is reliably detecting the end of a section; # comments are not reliable as there are some '# typo?' strings #[allow(dead_code)] fn next(&mut self, output: &mut impl Write) -> Option { self.finalize(output); match self { ParserState::Vendors(_, _, _) => { Some(ParserState::Classes(Map::::new(), None, 0u8)) } ParserState::Classes(_, _, _) => Some(ParserState::AtType(Map::::new(), None)), ParserState::AtType(_, _) => Some(ParserState::HidType(Map::::new(), None)), ParserState::HidType(_, _) => Some(ParserState::RType(Map::::new(), None)), ParserState::RType(_, _) => Some(ParserState::BiasType(Map::::new(), None)), ParserState::BiasType(_, _) => Some(ParserState::PhyType(Map::::new(), None)), ParserState::PhyType(_, _) => Some(ParserState::HutType(Map::::new(), None)), ParserState::HutType(_, _) => Some(ParserState::Lang(Map::::new(), None)), ParserState::Lang(_, _) => Some(ParserState::CountryCode(Map::::new(), None)), ParserState::CountryCode(_, _) => { Some(ParserState::TerminalType(Map::::new(), None)) } ParserState::TerminalType(_, _) => None, } } } #[allow(clippy::redundant_field_names)] fn main() { let out_dir = env::var_os("OUT_DIR").unwrap(); let src_path = Path::new("src/usb.ids"); let dest_path = Path::new(&out_dir).join("usb_ids.cg.rs"); let input = { let f = fs::File::open(src_path).unwrap(); BufReader::new(f) }; let mut output = { let f = fs::File::create(dest_path).unwrap(); BufWriter::new(f) }; // Parser state machine starts with vendors (first in file) let mut parser_state: ParserState = ParserState::Vendors(Map::::new(), None, 0u16); #[allow(clippy::lines_filter_map_ok)] for line in input.lines().flatten() { // Check for a state change based on the header comments if let Some(next_state) = parser_state.next_from_header(&line, &mut output) { parser_state = next_state; } // Process line for current parser parser_state.process(&line); } // Last call for last parser in file parser_state.finalize(&mut output); println!("cargo:rerun-if-changed=build.rs"); println!("cargo:rerun-if-changed=src/usb.ids"); } mod parser { use std::num::ParseIntError; use nom::bytes::complete::{tag, take}; use nom::character::complete::{hex_digit1, tab}; use nom::combinator::{all_consuming, map_parser, map_res}; use nom::sequence::{delimited, terminated}; use nom::IResult; fn id(size: usize, from_str_radix: F) -> impl Fn(&str) -> IResult<&str, T> where F: Fn(&str, u32) -> Result, { move |input| { map_res(map_parser(take(size), all_consuming(hex_digit1)), |input| { from_str_radix(input, 16) })(input) } } pub fn vendor(input: &str) -> IResult<&str, u16> { let id = id(4, u16::from_str_radix); terminated(id, tag(" "))(input) } pub fn device(input: &str) -> IResult<&str, u16> { let id = id(4, u16::from_str_radix); delimited(tab, id, tag(" "))(input) } pub fn interface(input: &str) -> IResult<&str, u8> { let id = id(2, u8::from_str_radix); delimited(tag("\t\t"), id, tag(" "))(input) } pub fn class(input: &str) -> IResult<&str, u8> { let id = id(2, u8::from_str_radix); delimited(tag("C "), id, tag(" "))(input) } pub fn sub_class(input: &str) -> IResult<&str, u8> { let id = id(2, u8::from_str_radix); delimited(tab, id, tag(" "))(input) } pub fn protocol(input: &str) -> IResult<&str, u8> { let id = id(2, u8::from_str_radix); delimited(tag("\t\t"), id, tag(" "))(input) } pub fn audio_terminal_type(input: &str) -> IResult<&str, u16> { let id = id(4, u16::from_str_radix); delimited(tag("AT "), id, tag(" "))(input) } pub fn hid_type(input: &str) -> IResult<&str, u8> { let id = id(2, u8::from_str_radix); delimited(tag("HID "), id, tag(" "))(input) } pub fn hid_item_type(input: &str) -> IResult<&str, u8> { let id = id(2, u8::from_str_radix); delimited(tag("R "), id, tag(" "))(input) } pub fn bias_type(input: &str) -> IResult<&str, u8> { let id = id(1, u8::from_str_radix); delimited(tag("BIAS "), id, tag(" "))(input) } pub fn phy_type(input: &str) -> IResult<&str, u8> { let id = id(2, u8::from_str_radix); delimited(tag("PHY "), id, tag(" "))(input) } pub fn hut_type(input: &str) -> IResult<&str, u8> { let id = id(2, u8::from_str_radix); delimited(tag("HUT "), id, tag(" "))(input) } pub fn hid_usage_name(input: &str) -> IResult<&str, u16> { let id = id(3, u16::from_str_radix); delimited(tab, id, tag(" "))(input) } pub fn language(input: &str) -> IResult<&str, u16> { let id = id(4, u16::from_str_radix); delimited(tag("L "), id, tag(" "))(input) } pub fn dialect(input: &str) -> IResult<&str, u8> { let id = id(2, u8::from_str_radix); delimited(tab, id, tag(" "))(input) } pub fn country_code(input: &str) -> IResult<&str, u8> { let id = id(2, u8::from_str_radix); delimited(tag("HCC "), id, tag(" "))(input) } pub fn terminal_type(input: &str) -> IResult<&str, u16> { let id = id(4, u16::from_str_radix); delimited(tag("VT "), id, tag(" "))(input) } } impl quote::ToTokens for CgVendor { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { let CgVendor { id: vendor_id, name, devices, } = self; let devices = devices.iter().map(|CgDevice { id, name, interfaces }| { quote!{ Device { vendor_id: #vendor_id, id: #id, name: #name, interfaces: &[#(#interfaces),*] } } }); tokens.extend(quote! { Vendor { id: #vendor_id, name: #name, devices: &[#(#devices),*] } }); } } impl quote::ToTokens for CgClass { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { let CgClass { id: class_id, name, sub_classes, } = self; let sub_classes = sub_classes.iter().map(|CgSubClass { id, name, children }| { quote! { SubClass { class_id: #class_id, id: #id, name: #name, protocols: &[#(#children),*] } } }); tokens.extend(quote! { Class { id: #class_id, name: #name, sub_classes: &[#(#sub_classes),*] } }); } } impl quote::ToTokens for CgParentType { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { let CgParentType { id, name, children } = self; tokens.extend(quote! { UsbIdWithChildren { id: #id, name: #name, children: &[#(#children),*] } }); } } impl quote::ToTokens for CgType { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { let CgType { id, name } = self; tokens.extend(quote! { UsbId { id: #id, name: #name } }); } } usb-ids-1.2025.1/src/lib.rs000064400000000000000000000545541046102023000133420ustar 00000000000000//! //! Rust wrappers for the [USB ID Repository](http://www.linux-usb.org/usb-ids.html). //! //! The USB ID Repository is the canonical source of USB device information for most //! Linux userspaces; this crate vendors the USB ID database to allow non-Linux hosts to //! access the same canonical information. //! //! # Usage //! //! Iterating over all known vendors: //! //! ```rust //! use usb_ids::Vendors; //! //! for vendor in Vendors::iter() { //! for device in vendor.devices() { //! println!("vendor: {}, device: {}", vendor.name(), device.name()); //! } //! } //! ``` //! //! Iterating over all known classes: //! //! ```rust //! use usb_ids::Classes; //! //! for class in Classes::iter() { //! println!("class: {}", class.name()); //! for subclass in class.sub_classes() { //! println!("\tsubclass: {}", subclass.name()); //! for protocol in subclass.protocols() { //! println!("\t\tprotocol: {}", protocol.name()); //! } //! } //! } //! ``` //! //! See the individual documentation for each structure for more details. //! #![warn(missing_docs)] include!(concat!(env!("OUT_DIR"), "/usb_ids.cg.rs")); /// Represents a generic USB ID in the USB database. /// /// Not designed to be used directly; use one of the type aliases instead. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct UsbId { id: T, name: &'static str, } impl UsbId { /// Returns the type's ID. pub fn id(&self) -> T { self.id } /// Returns the type's name. pub fn name(&self) -> &'static str { self.name } } /// Represents a generic USB ID in the USB database with children IDs. /// /// Not designed to be used directly; use one of the type aliases instead. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct UsbIdWithChildren { id: T, name: &'static str, children: &'static [C], } impl UsbIdWithChildren { /// Returns the type's ID. pub fn id(&self) -> T { self.id } /// Returns the type's name. pub fn name(&self) -> &'static str { self.name } /// Returns an iterator over the type's children. fn children(&self) -> impl Iterator { self.children.iter() } } /// An abstraction for iterating over all vendors in the USB database. pub struct Vendors; impl Vendors { /// Returns an iterator over all vendors in the USB database. pub fn iter() -> impl Iterator { USB_IDS.values() } } /// An abstraction for iterating over all classes in the USB database. pub struct Classes; impl Classes { /// Returns an iterator over all classes in the USB database. pub fn iter() -> impl Iterator { USB_CLASSES.values() } } /// An abstraction for iterating over all languages in the USB database. /// /// ``` /// use usb_ids::Languages; /// for language in Languages::iter() { /// println!("language: {}", language.name()); /// for dialect in language.dialects() { /// println!("\tdialect: {}", dialect.name()); /// } /// } /// ``` pub struct Languages; impl Languages { /// Returns an iterator over all languages in the USB database. pub fn iter() -> impl Iterator { USB_LANGS.values() } } /// An abstraction for iterating over all HID usage pages in the USB database. /// /// ``` /// use usb_ids::HidUsagePages; /// /// for page in HidUsagePages::iter() { /// println!("page: {}", page.name()); /// for usage in page.usages() { /// println!("\tusage: {}", usage.name()); /// } /// } /// ``` pub struct HidUsagePages; impl HidUsagePages { /// Returns an iterator over all HID usage pages in the USB database. pub fn iter() -> impl Iterator { USB_HUTS.values() } } /// Represents a USB device vendor in the USB database. /// /// Every device vendor has a vendor ID, a pretty name, and a /// list of associated [`Device`]s. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Vendor { id: u16, name: &'static str, devices: &'static [Device], } impl Vendor { /// Returns the vendor's ID. pub fn id(&self) -> u16 { self.id } /// Returns the vendor's name. pub fn name(&self) -> &'static str { self.name } /// Returns an iterator over the vendor's [`Device`]s. pub fn devices(&self) -> impl Iterator { self.devices.iter() } } /// Represents a single device in the USB database. /// /// Every device has a corresponding vendor, a device ID, a pretty name, /// and a list of associated [`Interface`]s. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Device { vendor_id: u16, id: u16, name: &'static str, interfaces: &'static [Interface], } impl Device { /// Returns the [`Device`] corresponding to the given vendor and product IDs, /// or `None` if no such device exists in the DB. /// /// ``` /// use usb_ids::Device; /// let device = Device::from_vid_pid(0x1d6b, 0x0003).unwrap(); /// assert_eq!(device.name(), "3.0 root hub"); /// ``` pub fn from_vid_pid(vid: u16, pid: u16) -> Option<&'static Device> { let vendor = Vendor::from_id(vid); vendor.and_then(|v| v.devices().find(|d| d.id == pid)) } /// Returns the [`Vendor`] that this device belongs to. /// /// Looking up a vendor by device is cheap (`O(1)`). pub fn vendor(&self) -> &'static Vendor { USB_IDS.get(&self.vendor_id).unwrap() } /// Returns a tuple of (vendor id, device/"product" id) for this device. /// /// This is convenient for interactions with other USB libraries. pub fn as_vid_pid(&self) -> (u16, u16) { (self.vendor_id, self.id) } /// Returns the device's ID. pub fn id(&self) -> u16 { self.id } /// Returns the device's name. pub fn name(&self) -> &'static str { self.name } /// Returns an iterator over the device's [`Interface`]s. /// /// **NOTE**: The USB database does not include interface information for /// most devices. This list is not authoritative. pub fn interfaces(&self) -> impl Iterator { self.interfaces.iter() } } /// Represents an interface to a USB device in the USB database. /// /// Every interface has an interface ID (which is an index on the device) /// and a pretty name. /// /// **NOTE**: The USB database is not a canonical or authoritative source /// of interface information for devices. Users who wish to discover interfaces /// on their USB devices should query those devices directly. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Interface { id: u8, name: &'static str, } impl Interface { /// Returns the interface's ID. pub fn id(&self) -> u8 { self.id } /// Returns the interface's name. pub fn name(&self) -> &'static str { self.name } } /// Represents a USB device class in the USB database. /// /// Every device class has a class ID, a pretty name, and a /// list of associated [`SubClass`]s. /// /// ``` /// use usb_ids::{Class, Classes, FromId}; /// let class = Class::from_id(0x03).unwrap(); /// assert_eq!(class.name(), "Human Interface Device"); /// ``` #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Class { id: u8, name: &'static str, sub_classes: &'static [SubClass], } impl Class { /// Returns the class's ID. pub fn id(&self) -> u8 { self.id } /// Returns the class's name. pub fn name(&self) -> &'static str { self.name } /// Returns an iterator over the class's [`SubClass`]s. pub fn sub_classes(&self) -> impl Iterator { self.sub_classes.iter() } } /// Represents a class subclass in the USB database. Subclasses are part of the /// USB class code triplet (base class, subclass, protocol). /// /// Contained within a [`Class`] and may contain a list of associated /// [`Protocol`]s. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct SubClass { class_id: u8, id: u8, name: &'static str, protocols: &'static [Protocol], } impl SubClass { /// Returns the [`SubClass`] corresponding to the given class and subclass IDs, /// or `None` if no such subclass exists in the DB. /// /// ``` /// use usb_ids::SubClass; /// let subclass = SubClass::from_cid_scid(0x02, 0x03).unwrap(); /// assert_eq!(subclass.name(), "Telephone"); /// /// assert!(SubClass::from_cid_scid(0x3c, 0x02).is_none()); /// ``` pub fn from_cid_scid(class_id: u8, id: u8) -> Option<&'static Self> { let class = Class::from_id(class_id); class.and_then(|c| c.sub_classes().find(|s| s.id == id)) } /// Returns the [`Class`] that this subclass belongs to. /// /// Looking up a class by subclass is cheap (`O(1)`). /// /// ``` /// use usb_ids::SubClass; /// let subclass = SubClass::from_cid_scid(0x02, 0x03).unwrap(); /// let class = subclass.class(); /// assert_eq!(class.id(), 0x02); /// ``` pub fn class(&self) -> &'static Class { USB_CLASSES.get(&self.class_id).unwrap() } /// Returns a tuple of (class id, subclass id) for this subclass. /// /// This is convenient for interactions with other USB libraries. pub fn as_cid_scid(&self) -> (u8, u8) { (self.class_id, self.id) } /// Returns the subclass' ID. pub fn id(&self) -> u8 { self.id } /// Returns the subclass' name. pub fn name(&self) -> &'static str { self.name } /// Returns an iterator over the subclasses's [`Protocol`]s. /// /// **NOTE**: The USB database nor USB-IF includes protocol information for /// all subclassess. This list is not authoritative. pub fn protocols(&self) -> impl Iterator { self.protocols.iter() } } /// These are tags for UsbId type aliases to make them unique and allow a /// [`FromId`] for each alias. The values are arbitrary but must be unique. /// /// [`std::marker::PhantomData`] would be nicer but was unable to figure out a /// generic way to add the _tag: PhantomData in the ToToken trait /// implementation within build.rs const PROTOCOL_TAG: u8 = 0; const AT_TAG: u8 = 1; const HID_TAG: u8 = 2; const HID_TYPE_TAG: u8 = 3; const HID_USAGE_TAG: u8 = 4; const BIAS_TAG: u8 = 5; const PHY_TAG: u8 = 6; const DIALECT_TAG: u8 = 7; const HCC_TAG: u8 = 8; const VT_TAG: u8 = 9; /// Represents a subclass protocol in the USB database. /// /// Protocols are part of the USB class code triplet (base class, subclass, /// protocol), contained within a [`SubClass`]. pub type Protocol = UsbId; impl Protocol { /// Returns the [`Protocol`] corresponding to the given class, subclass, and protocol IDs, /// or `None` if no such protocol exists in the DB. /// /// ``` /// use usb_ids::Protocol; /// let protocol = Protocol::from_cid_scid_pid(0x02, 0x02, 0x05).unwrap(); /// assert_eq!(protocol.name(), "AT-commands (3G)"); /// ``` pub fn from_cid_scid_pid(class_id: u8, subclass_id: u8, id: u8) -> Option<&'static Self> { let subclass = SubClass::from_cid_scid(class_id, subclass_id); subclass.and_then(|s| s.protocols().find(|p| p.id == id)) } } /// Represents an audio terminal type in the USB database. /// /// ``` /// use usb_ids::{AudioTerminal, FromId}; /// let audio_terminal = AudioTerminal::from_id(0x0201).unwrap(); /// assert_eq!(audio_terminal.name(), "Microphone"); /// ``` pub type AudioTerminal = UsbId; /// Represents a HID descriptor type in the USB database. /// /// ``` /// use usb_ids::{Hid, FromId}; /// let hid = Hid::from_id(0x22).unwrap(); /// assert_eq!(hid.name(), "Report"); /// ``` pub type Hid = UsbId; /// Represents a HID descriptor item type in the USB database. /// /// ``` /// use usb_ids::{HidItemType, FromId}; /// let hid_item_type = HidItemType::from_id(0xb4).unwrap(); /// assert_eq!(hid_item_type.name(), "Pop"); /// ``` pub type HidItemType = UsbId; /// Represents a HID usage page in the USB database. /// /// Every HID usage page has a usage page ID, a pretty name, and a list of /// associated [`HidUsage`]s. /// /// ``` /// use usb_ids::{HidUsagePage, FromId}; /// let hid_usage_page = HidUsagePage::from_id(0x01).unwrap(); /// assert_eq!(hid_usage_page.name(), "Generic Desktop Controls"); /// /// for usage in hid_usage_page.usages() { /// println!("usage: {}", usage.name()); /// } /// ``` pub type HidUsagePage = UsbIdWithChildren; impl HidUsagePage { /// Returns an iterator over the page's [`HidUsage`]s. pub fn usages(&self) -> impl Iterator { self.children() } } /// Represents a HID usage type in the USB database. /// /// ``` /// use usb_ids::{HidUsage, HidUsagePage, FromId}; /// /// let hid_usage_page = HidUsagePage::from_id(0x01).unwrap(); /// for usage in hid_usage_page.usages() { /// println!("usage: {}", usage.name()); /// } /// ``` pub type HidUsage = UsbId; impl HidUsage { /// Returns the [`HidUsage`] corresponding to the given usage page and usage ID, /// or `None` if no such usage exists in the DB. /// /// ``` /// use usb_ids::HidUsage; /// let hid_usage = HidUsage::from_pageid_uid(0x01, 0x002).unwrap(); /// assert_eq!(hid_usage.name(), "Mouse"); /// ``` pub fn from_pageid_uid(page_id: u8, id: u16) -> Option<&'static Self> { let page = HidUsagePage::from_id(page_id)?; page.children().find(|u| u.id() == id) } } /// Represents physical descriptor bias type in the USB database. /// /// ``` /// use usb_ids::{Bias, FromId}; /// let bias = Bias::from_id(0x02).unwrap(); /// assert_eq!(bias.name(), "Left Hand"); /// ``` pub type Bias = UsbId; /// Represents physical descriptor item type in the USB database. /// /// ``` /// use usb_ids::{Phy, FromId}; /// let phy = Phy::from_id(0x25).unwrap(); /// assert_eq!(phy.name(), "Fifth Toe"); /// ``` pub type Phy = UsbId; /// Represents a language type in the USB database. /// /// Languages have a language ID, a pretty name, and a list of associated /// [`Dialect`]s. /// /// ``` /// use usb_ids::{Language, FromId}; /// let language = Language::from_id(0x000c).unwrap(); /// assert_eq!(language.name(), "French"); /// /// for dialect in language.dialects() { /// println!("dialect: {}", dialect.name()); /// } /// ``` pub type Language = UsbIdWithChildren; impl Language { /// Returns an iterator over the language's [`Dialect`]s. pub fn dialects(&self) -> impl Iterator { self.children() } } /// Represents a language dialect in the USB database. /// /// ``` /// use usb_ids::{Dialect, Language, FromId}; /// let lang = Language::from_id(0x0007).unwrap(); /// /// println!("language: {}", lang.name()); /// for dialect in lang.dialects() { /// println!("\tdialect: {}", dialect.name()); /// } /// ``` pub type Dialect = UsbId; impl Dialect { /// Returns the [`Dialect`] corresponding to the given language and dialect IDs, /// or `None` if no such dialect exists in the DB. /// /// ``` /// use usb_ids::Dialect; /// let dialect = Dialect::from_lid_did(0x0007, 0x02).unwrap(); /// assert_eq!(dialect.name(), "Swiss"); /// ``` pub fn from_lid_did(language_id: u16, id: u8) -> Option<&'static Self> { let language = Language::from_id(language_id)?; language.children().find(|d| d.id() == id) } } /// Represents a HID descriptor country code in the USB database. /// /// ``` /// use usb_ids::{HidCountryCode, FromId}; /// let hid_country_code = HidCountryCode::from_id(0x29).unwrap(); /// assert_eq!(hid_country_code.name(), "Switzerland"); /// ``` pub type HidCountryCode = UsbId; /// Represents a video class terminal type in the USB database. /// /// ``` /// use usb_ids::{VideoTerminal, FromId}; /// let video_terminal = VideoTerminal::from_id(0x0101).unwrap(); /// assert_eq!(video_terminal.name(), "USB Streaming"); /// ``` pub type VideoTerminal = UsbId; /// A convenience trait for retrieving a top-level entity (like a [`Vendor`]) from the USB /// database by its unique ID. /// /// ``` /// use usb_ids::{FromId, Vendor}; /// let vendor = Vendor::from_id(0x1d6b).unwrap(); /// assert_eq!(vendor.name(), "Linux Foundation"); /// ``` pub trait FromId { /// Returns the entity corresponding to `id`, or `None` if none exists. fn from_id(id: T) -> Option<&'static Self>; } impl FromId for Vendor { fn from_id(id: u16) -> Option<&'static Self> { USB_IDS.get(&id) } } impl FromId for Class { fn from_id(id: u8) -> Option<&'static Self> { USB_CLASSES.get(&id) } } impl FromId for AudioTerminal { fn from_id(id: u16) -> Option<&'static Self> { USB_AUDIO_TERMINALS.get(&id) } } impl FromId for Hid { fn from_id(id: u8) -> Option<&'static Self> { USB_HID_IDS.get(&id) } } impl FromId for HidItemType { fn from_id(id: u8) -> Option<&'static Self> { USB_HID_R_TYPES.get(&id) } } impl FromId for HidUsagePage { fn from_id(id: u8) -> Option<&'static Self> { USB_HUTS.get(&id) } } impl FromId for Bias { fn from_id(id: u8) -> Option<&'static Self> { USB_BIASES.get(&id) } } impl FromId for Phy { fn from_id(id: u8) -> Option<&'static Self> { USB_PHYS.get(&id) } } impl FromId for Language { fn from_id(id: u16) -> Option<&'static Self> { USB_LANGS.get(&id) } } impl FromId for HidCountryCode { fn from_id(id: u8) -> Option<&'static Self> { USB_HID_CCS.get(&id) } } impl FromId for VideoTerminal { fn from_id(id: u16) -> Option<&'static Self> { USB_VIDEO_TERMINALS.get(&id) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_from_id() { let vendor = Vendor::from_id(0x1d6b).unwrap(); assert_eq!(vendor.name(), "Linux Foundation"); assert_eq!(vendor.id(), 0x1d6b); } #[test] fn test_vendor_devices() { let vendor = Vendor::from_id(0x1d6b).unwrap(); for device in vendor.devices() { assert_eq!(device.vendor(), vendor); assert!(!device.name().is_empty()); } } #[test] fn test_from_vid_pid() { let device = Device::from_vid_pid(0x1d6b, 0x0003).unwrap(); assert_eq!(device.name(), "3.0 root hub"); let (vid, pid) = device.as_vid_pid(); assert_eq!(vid, device.vendor().id()); assert_eq!(pid, device.id()); let device2 = Device::from_vid_pid(vid, pid).unwrap(); assert_eq!(device, device2); let last_device = Device::from_vid_pid(0xffee, 0x0100).unwrap(); assert_eq!( last_device.name(), "Card Reader Controller RTS5101/RTS5111/RTS5116" ); } #[test] fn test_class_from_id() { let class = Class::from_id(0x03).unwrap(); assert_eq!(class.name(), "Human Interface Device"); assert_eq!(class.id(), 0x03); } #[test] fn test_subclass_from_cid_scid() { let subclass = SubClass::from_cid_scid(0x03, 0x01).unwrap(); assert_eq!(subclass.name(), "Boot Interface Subclass"); assert_eq!(subclass.id(), 0x01); } #[test] fn test_protocol_from_cid_scid_pid() { let protocol = Protocol::from_cid_scid_pid(0x03, 0x01, 0x01).unwrap(); assert_eq!(protocol.name(), "Keyboard"); assert_eq!(protocol.id(), 0x01); let protocol = Protocol::from_cid_scid_pid(0x07, 0x01, 0x03).unwrap(); assert_eq!(protocol.name(), "IEEE 1284.4 compatible bidirectional"); assert_eq!(protocol.id(), 0x03); let protocol = Protocol::from_cid_scid_pid(0xff, 0xff, 0xff).unwrap(); // check last entry for parsing assert_eq!(protocol.name(), "Vendor Specific Protocol"); assert_eq!(protocol.id(), 0xff); } #[test] fn test_at_from_id() { let at = AudioTerminal::from_id(0x0713).unwrap(); assert_eq!(at.name(), "Synthesizer"); assert_eq!(at.id(), 0x0713); } #[test] fn test_hid_from_id() { let hid = Hid::from_id(0x23).unwrap(); assert_eq!(hid.name(), "Physical"); assert_eq!(hid.id(), 0x23); } #[test] fn test_hid_type_from_id() { let hid_type = HidItemType::from_id(0xc0).unwrap(); assert_eq!(hid_type.name(), "End Collection"); assert_eq!(hid_type.id(), 0xc0); } #[test] fn test_bias_from_id() { let bias = Bias::from_id(0x04).unwrap(); assert_eq!(bias.name(), "Either Hand"); assert_eq!(bias.id(), 0x04); } #[test] fn test_phy_from_id() { let phy = Phy::from_id(0x27).unwrap(); assert_eq!(phy.name(), "Cheek"); assert_eq!(phy.id(), 0x27); } #[test] fn test_hid_usages_from_id() { let hid_usage_page = HidUsagePage::from_id(0x0d).unwrap(); assert_eq!(hid_usage_page.name(), "Digitizer"); assert_eq!(hid_usage_page.id(), 0x0d); let hid_usage = HidUsage::from_pageid_uid(0x0d, 0x01).unwrap(); assert_eq!(hid_usage.name(), "Digitizer"); assert_eq!(hid_usage.id(), 0x01); } #[test] fn test_language_from_id() { let language = Language::from_id(0x0007).unwrap(); assert_eq!(language.name(), "German"); assert_eq!(language.id(), 0x0007); let dialect = language.dialects().find(|d| d.id() == 0x02).unwrap(); assert_eq!(dialect.name(), "Swiss"); assert_eq!(dialect.id(), 0x02); } #[test] fn test_hid_country_code_from_id() { let hid_country_code = HidCountryCode::from_id(0x29).unwrap(); assert_eq!(hid_country_code.name(), "Switzerland"); assert_eq!(hid_country_code.id(), 0x29); let hid_country_code = HidCountryCode::from_id(0x00).unwrap(); assert_eq!(hid_country_code.name(), "Not supported"); } #[test] fn test_video_terminal_from_id() { let video_terminal = VideoTerminal::from_id(0x0100).unwrap(); assert_eq!(video_terminal.name(), "USB Vendor Specific"); assert_eq!(video_terminal.id(), 0x0100); let video_terminal = VideoTerminal::from_id(0x0403).unwrap(); assert_eq!(video_terminal.name(), "Component Video"); } }