summary refs log tree commit diff
path: root/usb_util/src/endpoint_descriptor.rs
blob: f1ca2291ab86a56833e72b8e06b6e91d9376b48c (plain) (blame)
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
// Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use super::types::{EndpointDirection, EndpointType};
use bindings::libusb_endpoint_descriptor;
use std::ops::Deref;

/// EndpointDescriptor wraps libusb_endpoint_descriptor.
pub struct EndpointDescriptor<'a>(&'a libusb_endpoint_descriptor);

const ENDPOINT_DESCRIPTOR_DIRECTION_MASK: u8 = 1 << 7;
const ENDPOINT_DESCRIPTOR_NUMBER_MASK: u8 = 0xf;
const ENDPOINT_DESCRIPTOR_ATTRIBUTES_TYPE_MASK: u8 = 0x3;

impl<'a> EndpointDescriptor<'a> {
    // Create new endpoint descriptor.
    pub fn new(descriptor: &libusb_endpoint_descriptor) -> EndpointDescriptor {
        EndpointDescriptor(descriptor)
    }

    // Get direction of this endpoint.
    pub fn get_direction(&self) -> EndpointDirection {
        let direction = self.0.bEndpointAddress & ENDPOINT_DESCRIPTOR_DIRECTION_MASK;
        if direction > 0 {
            EndpointDirection::DeviceToHost
        } else {
            EndpointDirection::HostToDevice
        }
    }

    // Get endpoint number.
    pub fn get_endpoint_number(&self) -> u8 {
        self.0.bEndpointAddress & ENDPOINT_DESCRIPTOR_NUMBER_MASK
    }

    // Get endpoint type.
    pub fn get_endpoint_type(&self) -> Option<EndpointType> {
        let ep_type = self.0.bmAttributes & ENDPOINT_DESCRIPTOR_ATTRIBUTES_TYPE_MASK;
        match ep_type {
            0 => Some(EndpointType::Control),
            1 => Some(EndpointType::Isochronous),
            2 => Some(EndpointType::Bulk),
            3 => Some(EndpointType::Interrupt),
            _ => None,
        }
    }
}

impl<'a> Deref for EndpointDescriptor<'a> {
    type Target = libusb_endpoint_descriptor;

    fn deref(&self) -> &libusb_endpoint_descriptor {
        self.0
    }
}