rust_util/
lib.rs

1// Copyright 2022 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use fidl_fidl_clientsuite::FidlErrorKind;
6
7/// Classify a [`fidl::Error`] as a [`FidlErrorKind`] that can be returned in a
8/// dynsuite client test.
9pub fn classify_error(error: fidl::Error) -> FidlErrorKind {
10    match error {
11        fidl::Error::InvalidBoolean
12        | fidl::Error::InvalidHeader
13        | fidl::Error::IncompatibleMagicNumber(_)
14        | fidl::Error::UnsupportedWireFormatVersion
15        | fidl::Error::InvalidResponseOrdinal { .. }
16        | fidl::Error::Invalid
17        | fidl::Error::OutOfRange { .. }
18        | fidl::Error::OutOfHandles
19        | fidl::Error::ExtraBytes
20        | fidl::Error::ExtraHandles
21        | fidl::Error::NonZeroPadding { .. }
22        | fidl::Error::MaxRecursionDepth
23        | fidl::Error::NotNullable
24        | fidl::Error::UnexpectedNullRef
25        | fidl::Error::Utf8Error
26        | fidl::Error::InvalidBitsValue
27        | fidl::Error::InvalidEnumValue
28        | fidl::Error::UnknownUnionTag
29        | fidl::Error::InvalidPresenceIndicator
30        | fidl::Error::InvalidInlineBitInEnvelope
31        | fidl::Error::InvalidInlineMarkerInEnvelope
32        | fidl::Error::InvalidNumBytesInEnvelope
33        | fidl::Error::InvalidHostHandle
34        | fidl::Error::IncorrectHandleSubtype { .. }
35        | fidl::Error::MissingExpectedHandleRights { .. } => FidlErrorKind::DecodingError,
36
37        fidl::Error::UnknownOrdinal { .. }
38        | fidl::Error::InvalidResponseTxid { .. }
39        | fidl::Error::UnexpectedSyncResponse => FidlErrorKind::UnexpectedMessage,
40
41        fidl::Error::UnsupportedMethod { .. } => FidlErrorKind::UnknownMethod,
42
43        fidl::Error::ClientChannelClosed { .. } => FidlErrorKind::ChannelPeerClosed,
44
45        _ => FidlErrorKind::OtherError,
46    }
47}
48
49/// Returns the FIDL method name for a request/event enum value.
50// TODO(https://fxbug.dev/42078541): Provide this in FIDL bindings.
51pub fn method_name(request_or_event: &impl std::fmt::Debug) -> String {
52    let mut string = format!("{:?}", request_or_event);
53    let len = string.find('{').unwrap_or(string.len());
54    let len = string[..len].trim_end().len();
55    string.truncate(len);
56    assert!(
57        string.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'),
58        "failed to parse the method name from {:?}",
59        request_or_event
60    );
61    string
62}