Skip to content

fix: Take Into<Cow> instead of &str #232

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 12 additions & 11 deletions src/level.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@

use crate::renderer::stylesheet::Stylesheet;
use crate::snippet::{ERROR_TXT, HELP_TXT, INFO_TXT, NOTE_TXT, WARNING_TXT};
use crate::Title;
use crate::{OptionCow, Title};
use anstyle::Style;
use std::borrow::Cow;

/// Default `error:` [`Level`]
pub const ERROR: Level<'_> = Level {
Expand Down Expand Up @@ -38,7 +39,7 @@ pub const HELP: Level<'_> = Level {
/// [`Title`] severity level
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Level<'a> {
pub(crate) name: Option<Option<&'a str>>,
pub(crate) name: Option<Option<Cow<'a, str>>>,
pub(crate) level: LevelInner,
}

Expand All @@ -56,9 +57,9 @@ impl<'a> Level<'a> {
/// not allowed to be passed to this function.
///
/// </div>
pub fn text(self, text: Option<&'a str>) -> Level<'a> {
pub fn text(self, text: impl Into<OptionCow<'a>>) -> Level<'a> {
Level {
name: Some(text),
name: Some(text.into().0),
level: self.level,
}
}
Expand All @@ -72,11 +73,11 @@ impl<'a> Level<'a> {
/// not allowed to be passed to this function.
///
/// </div>
pub fn title(self, title: &'a str) -> Title<'a> {
pub fn title(self, title: impl Into<Cow<'a, str>>) -> Title<'a> {
Title {
level: self,
id: None,
title,
title: title.into(),
is_pre_styled: false,
}
}
Expand All @@ -89,18 +90,18 @@ impl<'a> Level<'a> {
/// used to normalize untrusted text before it is passed to this function.
///
/// </div>
pub fn pre_styled_title(self, title: &'a str) -> Title<'a> {
pub fn pre_styled_title(self, title: impl Into<Cow<'a, str>>) -> Title<'a> {
Title {
level: self,
id: None,
title,
title: title.into(),
is_pre_styled: true,
}
}

pub(crate) fn as_str(&self) -> &'a str {
match (self.name, self.level) {
(Some(Some(name)), _) => name,
pub(crate) fn as_str(&'a self) -> &'a str {
match (&self.name, self.level) {
(Some(Some(name)), _) => name.as_ref(),
(Some(None), _) => "",
(None, LevelInner::Error) => ERROR_TXT,
(None, LevelInner::Warning) => WARNING_TXT,
Expand Down
56 changes: 28 additions & 28 deletions src/renderer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -229,14 +229,14 @@ impl Renderer {
.find_map(|s| match &s {
Element::Cause(cause) => {
if cause.markers.iter().any(|m| m.kind.is_primary()) {
Some(cause.path)
Some(cause.path.as_ref())
} else {
None
}
}
Element::Origin(origin) => {
if origin.primary {
Some(Some(origin.path))
Some(Some(&origin.path))
} else {
None
}
Expand All @@ -248,8 +248,8 @@ impl Renderer {
.elements
.iter()
.find_map(|s| match &s {
Element::Cause(cause) => Some(cause.path),
Element::Origin(origin) => Some(Some(origin.path)),
Element::Cause(cause) => Some(cause.path.as_ref()),
Element::Origin(origin) => Some(Some(&origin.path)),
_ => None,
})
.unwrap_or_default(),
Expand All @@ -269,7 +269,7 @@ impl Renderer {
let mut max_depth = 0;
for e in &group.elements {
if let Element::Cause(cause) = e {
let source_map = SourceMap::new(cause.source, cause.line_start);
let source_map = SourceMap::new(&cause.source, cause.line_start);
let (depth, annotated_lines) =
source_map.annotated_lines(cause.markers.clone(), cause.fold);
max_depth = max(max_depth, depth);
Expand Down Expand Up @@ -340,7 +340,7 @@ impl Renderer {
}
Element::Suggestion(suggestion) => {
let source_map =
SourceMap::new(suggestion.source, suggestion.line_start);
SourceMap::new(&suggestion.source, suggestion.line_start);
self.emit_suggestion_default(
&mut buffer,
suggestion,
Expand Down Expand Up @@ -426,10 +426,10 @@ impl Renderer {
let labels_inner = cause
.markers
.iter()
.filter_map(|ann| match ann.label {
.filter_map(|ann| match &ann.label {
Some(msg) if ann.kind.is_primary() => {
if !msg.trim().is_empty() {
Some(msg.to_owned())
Some(msg.to_string())
} else {
None
}
Expand All @@ -442,11 +442,11 @@ impl Renderer {
labels = Some(labels_inner);
}

if let Some(path) = cause.path {
let mut origin = Origin::new(path);
if let Some(path) = &cause.path {
let mut origin = Origin::new(path.as_ref());
origin.primary = true;

let source_map = SourceMap::new(cause.source, cause.line_start);
let source_map = SourceMap::new(&cause.source, cause.line_start);
let (_depth, annotated_lines) =
source_map.annotated_lines(cause.markers.clone(), cause.fold);

Expand Down Expand Up @@ -531,7 +531,7 @@ impl Renderer {
if title.level.name != Some(None) {
buffer.append(buffer_msg_line_offset, title.level.as_str(), label_style);
label_width += title.level.as_str().len();
if let Some(Id { id: Some(id), url }) = title.id {
if let Some(Id { id: Some(id), url }) = &title.id {
buffer.append(buffer_msg_line_offset, "[", label_style);
if let Some(url) = url.as_ref() {
buffer.append(
Expand Down Expand Up @@ -575,9 +575,9 @@ impl Renderer {
});

let (title_str, style) = if title.is_pre_styled {
(title.title.to_owned(), ElementStyle::NoStyle)
(title.title.to_string(), ElementStyle::NoStyle)
} else {
(normalize_whitespace(title.title), title_element_style)
(normalize_whitespace(&title.title), title_element_style)
};
for (i, text) in title_str.lines().enumerate() {
if i != 0 {
Expand Down Expand Up @@ -654,7 +654,7 @@ impl Renderer {
format!("{}:{}:{}", origin.path, line, col)
}
(Some(line), None) => format!("{}:{}", origin.path, line),
_ => origin.path.to_owned(),
_ => origin.path.to_string(),
};

buffer.append(buffer_msg_line_offset, &str, ElementStyle::LineAndColumn);
Expand All @@ -671,17 +671,17 @@ impl Renderer {
buffer: &mut StyledBuffer,
max_line_num_len: usize,
snippet: &Snippet<'_, Annotation<'_>>,
primary_path: Option<&str>,
primary_path: Option<&Cow<'_, str>>,
sm: &SourceMap<'_>,
annotated_lines: &[AnnotatedLineInfo<'_>],
multiline_depth: usize,
is_cont: bool,
) {
if let Some(path) = snippet.path {
let mut origin = Origin::new(path);
if let Some(path) = &snippet.path {
let mut origin = Origin::new(path.as_ref());
// print out the span location and spacer before we print the annotated source
// to do this, we need to know if this span will be primary
let is_primary = primary_path == Some(origin.path);
let is_primary = primary_path == Some(&origin.path);

if is_primary {
origin.primary = true;
Expand Down Expand Up @@ -1394,7 +1394,7 @@ impl Renderer {
} else {
(pos + 2, annotation.start.display.saturating_sub(left))
};
if let Some(label) = annotation.label {
if let Some(label) = &annotation.label {
buffer.puts(line_offset + pos, code_offset + col, label, style);
}
}
Expand Down Expand Up @@ -1535,7 +1535,7 @@ impl Renderer {
suggestion: &Snippet<'_, Patch<'_>>,
max_line_num_len: usize,
sm: &SourceMap<'_>,
primary_path: Option<&str>,
primary_path: Option<&Cow<'_, str>>,
is_cont: bool,
) {
let suggestions = sm.splice_lines(suggestion.markers.clone());
Expand All @@ -1558,8 +1558,8 @@ impl Renderer {
ElementStyle::LineNumber,
);
}
if suggestion.path != primary_path {
if let Some(path) = suggestion.path {
if suggestion.path.as_ref() != primary_path {
if let Some(path) = suggestion.path.as_ref() {
let (loc, _) = sm.span_to_locations(parts[0].span.clone());
// --> file.rs:line:col
// |
Expand Down Expand Up @@ -1781,7 +1781,7 @@ impl Renderer {
// ...or trailing spaces. Account for substitutions containing unicode
// characters.
let sub_len: usize = str_width(if is_whitespace_addition {
part.replacement
&part.replacement
} else {
part.replacement.trim()
});
Expand All @@ -1802,7 +1802,7 @@ impl Renderer {
let padding: usize = max_line_num_len + 3;
for p in underline_start..underline_end {
if matches!(show_code_change, DisplaySuggestion::Underline)
&& is_different(sm, part.replacement, part.span.clone())
&& is_different(sm, &part.replacement, part.span.clone())
{
// If this is a replacement, underline with `~`, if this is an addition
// underline with `+`.
Expand Down Expand Up @@ -1903,7 +1903,7 @@ impl Renderer {
}

// length of the code after substitution
let full_sub_len = str_width(part.replacement) as isize;
let full_sub_len = str_width(&part.replacement) as isize;

// length of the code to be substituted
let snippet_len = span_end_pos as isize - span_start_pos as isize;
Expand Down Expand Up @@ -2631,7 +2631,7 @@ pub(crate) struct LineAnnotation<'a> {
pub kind: AnnotationKind,

/// Optional label to display adjacent to the annotation.
pub label: Option<&'a str>,
pub label: Option<Cow<'a, str>>,

/// Is this a single line, multiline or multiline span minimized down to a
/// smaller span.
Expand All @@ -2658,7 +2658,7 @@ impl LineAnnotation<'_> {
}

pub(crate) fn has_label(&self) -> bool {
if let Some(label) = self.label {
if let Some(label) = &self.label {
// Consider labels with no text as effectively not being there
// to avoid weird output with unnecessary vertical lines, like:
//
Expand Down
11 changes: 6 additions & 5 deletions src/renderer/source_map.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::renderer::{char_width, is_different, num_overlap, LineAnnotation, LineAnnotationType};
use crate::{Annotation, AnnotationKind, Patch};
use std::borrow::Cow;
use std::cmp::{max, min};
use std::ops::Range;

Expand Down Expand Up @@ -453,14 +454,14 @@ impl<'a> SourceMap<'a> {
.replacement
.split('\n')
.next()
.unwrap_or(part.replacement)
.unwrap_or(&part.replacement)
.chars()
.map(|c| match c {
'\t' => 4,
_ => 1,
})
.sum();
if !is_different(self, part.replacement, part.span.clone()) {
if !is_different(self, &part.replacement, part.span.clone()) {
// Account for cases where we are suggesting the same code that's already
// there. This shouldn't happen often, but in some cases for multipart
// suggestions it's much easier to handle it here than in the origin.
Expand All @@ -470,7 +471,7 @@ impl<'a> SourceMap<'a> {
end: (cur_lo.char as isize + acc + len) as usize,
});
}
buf.push_str(part.replacement);
buf.push_str(&part.replacement);
// Account for the difference between the width of the current code and the
// snippet being suggested, so that the *later* suggestions are correctly
// aligned on the screen. Note that cur_hi and cur_lo can be on different
Expand Down Expand Up @@ -514,7 +515,7 @@ pub(crate) struct MultilineAnnotation<'a> {
pub start: Loc,
pub end: Loc,
pub kind: AnnotationKind,
pub label: Option<&'a str>,
pub label: Option<Cow<'a, str>>,
pub overlaps_exactly: bool,
pub highlight_source: bool,
}
Expand Down Expand Up @@ -555,7 +556,7 @@ impl<'a> MultilineAnnotation<'a> {
},
end: self.end,
kind: self.kind,
label: self.label,
label: self.label.clone(),
annotation_type: LineAnnotationType::MultilineEnd(self.depth),
highlight_source: self.highlight_source,
}
Expand Down
Loading