Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / third_party / betocore / np_adv / examples / fmt / mod.rs
mod.rs84 lines · 2.4 KiBRaw
| 1 | // Copyright 2024 Google LLC |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | pub fn cpp_bytes(bytes: &[u8]) -> impl std::fmt::Display + '_ { |
| 16 | display_bytes("0x", bytes) |
| 17 | } |
| 18 | |
| 19 | pub fn java_bytes(bytes: &[u8]) -> impl std::fmt::Display + '_ { |
| 20 | display_bytes("(byte) 0x", bytes) |
| 21 | } |
| 22 | |
| 23 | pub fn display_bytes<'a>(prefix: &'a str, bytes: &'a [u8]) -> impl std::fmt::Display + 'a { |
| 24 | use std::fmt; |
| 25 | |
| 26 | struct DisplayBytes<'a> { |
| 27 | prefix: &'a str, |
| 28 | bytes: &'a [u8], |
| 29 | } |
| 30 | |
| 31 | impl fmt::Display for DisplayBytes<'_> { |
| 32 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 33 | let prefix = self.prefix; |
| 34 | |
| 35 | write!(f, "{{")?; |
| 36 | |
| 37 | let mut first = true; |
| 38 | for byte in self.bytes { |
| 39 | if !first { |
| 40 | write!(f, ", ")?; |
| 41 | } else { |
| 42 | first = false; |
| 43 | } |
| 44 | write!(f, "{prefix}{byte:02X}")?; |
| 45 | } |
| 46 | |
| 47 | write!(f, "}}")?; |
| 48 | Ok(()) |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | DisplayBytes { prefix, bytes } |
| 53 | } |
| 54 | |
| 55 | pub fn java_static<'a>(name: &'a str, bytes: &'a [u8]) -> impl std::fmt::Display + 'a { |
| 56 | use std::fmt; |
| 57 | |
| 58 | struct JavaStatic<'a>(&'a str, &'a [u8]); |
| 59 | |
| 60 | impl fmt::Display for JavaStatic<'_> { |
| 61 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 62 | let JavaStatic(name, bytes) = *self; |
| 63 | write!(f, "public static final byte[] {name} = {};", java_bytes(bytes)) |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | JavaStatic(name, bytes) |
| 68 | } |
| 69 | |
| 70 | pub fn cpp_static<'a>(name: &'a str, bytes: &'a [u8]) -> impl std::fmt::Display + 'a { |
| 71 | use std::fmt; |
| 72 | |
| 73 | struct CppStatic<'a>(&'a str, &'a [u8]); |
| 74 | |
| 75 | impl fmt::Display for CppStatic<'_> { |
| 76 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 77 | let CppStatic(name, bytes) = *self; |
| 78 | let len = bytes.len(); |
| 79 | write!(f, "constexpr std::array<uint8_t, {len}> {name} = {};", cpp_bytes(bytes)) |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | CppStatic(name, bytes) |
| 84 | } |