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
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Functions only intended to be called from code generated by the Rust Thrift // code generator. use anyhow::{bail, Result}; use std::fmt; // Note: `variants_by_number` must be sorted by the i32 values. pub fn enum_display( variants_by_number: &[(&str, i32)], formatter: &mut fmt::Formatter, number: i32, ) -> fmt::Result { match variants_by_number.binary_search_by_key(&number, |entry| entry.1) { Ok(i) => formatter.write_str(variants_by_number[i].0), Err(_) => write!(formatter, "{}", number), } } // Note: `variants_by_name` must be sorted by the string values. pub fn enum_from_str( variants_by_name: &[(&str, i32)], value: &str, type_name: &'static str, ) -> Result<i32> { match variants_by_name.binary_search_by_key(&value, |entry| entry.0) { Ok(i) => Ok(variants_by_name[i].1), Err(_) => bail!("Unable to parse {} as {}", value, type_name), } }