xref: /aosp_15_r20/bootable/libbootloader/gbl/libefi/src/protocol/simple_text_output.rs (revision 5225e6b173e52d2efc6bcf950c27374fd72adabc)
1 // Copyright 2024, The Android Open Source Project
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 //! Rust wrapper for `EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL`.
16 
17 use crate::efi_call;
18 use crate::protocol::{Protocol, ProtocolInfo};
19 use core::fmt::Write;
20 use efi_types::{char16_t, EfiGuid, EfiSimpleTextOutputProtocol};
21 use liberror::Result;
22 
23 /// EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL
24 pub struct SimpleTextOutputProtocol;
25 
26 impl ProtocolInfo for SimpleTextOutputProtocol {
27     type InterfaceType = EfiSimpleTextOutputProtocol;
28 
29     const GUID: EfiGuid =
30         EfiGuid::new(0x387477c2, 0x69c7, 0x11d2, [0x8e, 0x39, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b]);
31 }
32 
33 impl Protocol<'_, SimpleTextOutputProtocol> {
34     /// Wrapper of `EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL.OutputString()`
output_string(&self, msg: *mut char16_t) -> Result<()>35     pub fn output_string(&self, msg: *mut char16_t) -> Result<()> {
36         // SAFETY:
37         // `self.interface()?` guarantees `self.interface` is non-null and points to a valid object
38         // established by `Protocol::new()`.
39         // `self.interface` is input parameter and will not be retained. It outlives the call.
40         unsafe { efi_call!(self.interface()?.output_string, self.interface, msg) }
41     }
42 }
43 
44 /// Implement formatted write for `EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL`, so that we can print by
45 /// writing to it. i.e.:
46 ///
47 /// ```
48 /// let protocol: Protocol<SimpleTextOutputProtocol> = ...;
49 /// write!(protocol, "Value = {}\n", 1234);
50 /// ```
51 impl Write for Protocol<'_, SimpleTextOutputProtocol> {
write_str(&mut self, s: &str) -> core::fmt::Result52     fn write_str(&mut self, s: &str) -> core::fmt::Result {
53         for ch in s.chars() {
54             // 2 is enough for encode_utf16(). Add an additional one as NULL.
55             let mut buffer = [0u16; 3];
56             let char16_msg = ch.encode_utf16(&mut buffer[..]);
57             self.output_string(char16_msg.as_mut_ptr()).map_err(|_| core::fmt::Error {})?;
58         }
59         Ok(())
60     }
61 }
62