Message类型增加to_string方法用于格式化字符串,并增加贡献文档的一些说明

This commit is contained in:
pointer-to-bios 2024-02-19 01:43:12 +08:00
parent c52d9f4960
commit aedcb8749e
3 changed files with 20 additions and 4 deletions

View File

@ -11,3 +11,10 @@
* 等待审核代码 * 等待审核代码
若你的代码通过审核将会把你的PR合并到主分支中。 若你的代码通过审核将会把你的PR合并到主分支中。
## 需要注意的还未解决的问题
* rust中所有有关字符串格式化的宏中出现超过一个不止是`{}`的格式化占位符时内核必然崩溃。
* rust中所有有关字符串格式化的宏中出现需要调用自定义的`Debug trait`的类型时内核必然崩溃,推荐定义`ToString trait`并调用`.to_string()`后传入宏参数。
* 鉴于以上两条原因,不建议在复杂的字符串格式化任务中使用`format!()`宏。推荐通过使用`::kernel::tty::tty::MessageBuilder`构造`kernel::tty::tty::Message`对象,或使用
`message`宏,并调用此对象的`.to_string()`方法实现格式化字符串。

View File

@ -1,4 +1,3 @@
use alloc::string::ToString;
use alloc::vec; use alloc::vec;
use alloc::vec::Vec; use alloc::vec::Vec;
@ -181,7 +180,7 @@ impl<'a> Iterator for LogIterator<'a> {
let res = if let Some((time, msg)) = self.logs.first() { let res = if let Some((time, msg)) = self.logs.first() {
Some( Some(
MessageBuilder::new() MessageBuilder::new()
.message(&time.to_string()) .message(time)
.append(MessageBuilder::from_message(msg.clone())) .append(MessageBuilder::from_message(msg.clone()))
.build(), .build(),
) )

View File

@ -181,6 +181,16 @@ pub struct MessageSection {
#[derive(Clone)] #[derive(Clone)]
pub struct Message(Vec<MessageSection>); pub struct Message(Vec<MessageSection>);
impl ToString for Message {
fn to_string(&self) -> String {
let mut res = String::new();
for MessageSection { msg, .. } in self.0.iter() {
res += msg;
}
res
}
}
/// ## MessageBuilder /// ## MessageBuilder
/// ///
/// 使用链式调用模式构造一个消息. /// 使用链式调用模式构造一个消息.
@ -226,7 +236,7 @@ impl MessageBuilder {
Self { msg } Self { msg }
} }
pub fn message(mut self, msg: &str) -> Self { pub fn message<T: ToString + ?Sized>(mut self, msg: &T) -> Self {
self.msg.0.push(MessageSection { self.msg.0.push(MessageSection {
msg: msg.to_string(), msg: msg.to_string(),
fgcolor: Color(0xee, 0xee, 0xee), fgcolor: Color(0xee, 0xee, 0xee),
@ -235,7 +245,7 @@ impl MessageBuilder {
self self
} }
pub fn message_mut(&mut self, msg: &str) { pub fn message_mut<T: ToString + ?Sized>(&mut self, msg: &T) {
self.msg.0.push(MessageSection { self.msg.0.push(MessageSection {
msg: msg.to_string(), msg: msg.to_string(),
fgcolor: Color(0xee, 0xee, 0xee), fgcolor: Color(0xee, 0xee, 0xee),