From e0c197cab4fb8ffeb87ca56be850894be2ec7e25 Mon Sep 17 00:00:00 2001 From: Nick Cameron Date: Sat, 5 Sep 2015 18:26:28 +1200 Subject: [PATCH] Single line unsafe blocks --- src/expr.rs | 15 ++++++++++++++- tests/source/expr.rs | 8 ++++++++ tests/target/expr.rs | 6 ++++++ 3 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/expr.rs b/src/expr.rs index aac13f552d0..3a8b9c9ab4b 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -262,13 +262,26 @@ impl Rewrite for ast::Block { // Extract comment between unsafe and block start. let trimmed = &snippet[6..open_pos].trim(); - if !trimmed.is_empty() { + let prefix = if !trimmed.is_empty() { // 9 = "unsafe {".len(), 7 = "unsafe ".len() let budget = try_opt!(width.checked_sub(9)); format!("unsafe {} ", rewrite_comment(trimmed, true, budget, offset + 7)) } else { "unsafe ".to_owned() + }; + + if is_simple_block(self, context.codemap) && prefix.len() < width { + let body = + self.expr.as_ref().unwrap().rewrite(context, width - prefix.len(), offset); + if let Some(ref expr_str) = body { + let result = format!("{}{{ {} }}", prefix, expr_str); + if result.len() <= width && !result.contains('\n') { + return Some(result); + } + } } + + prefix } ast::BlockCheckMode::PopUnsafeBlock(..) | ast::BlockCheckMode::DefaultBlock => { diff --git a/tests/source/expr.rs b/tests/source/expr.rs index 0bb46086ca8..bf9a8359aad 100644 --- a/tests/source/expr.rs +++ b/tests/source/expr.rs @@ -93,6 +93,14 @@ fn baz() { unsafe { // Regular unsafe block } + + unsafe { + foo() + } + + unsafe { + foo(); + } } // Test some empty blocks. diff --git a/tests/target/expr.rs b/tests/target/expr.rs index e2ed9c598ce..9bfe51e0b26 100644 --- a/tests/target/expr.rs +++ b/tests/target/expr.rs @@ -130,6 +130,12 @@ fn baz() { unsafe { // Regular unsafe block } + + unsafe { foo() } + + unsafe { + foo(); + } } // Test some empty blocks.