Skip to content
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

Fix clippy warningis & errors #4

Merged
merged 3 commits into from
Jul 20, 2021
Merged
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
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
.DS_Store
/target
*.swp

/.idea
2 changes: 1 addition & 1 deletion src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ impl From<&str> for Error {
impl<E: error::Error + 'static> From<(String, E)> for Error {
fn from((message, err): (String, E)) -> Self {
Self {
message: message,
message,
source: Some(Box::new(err)),
}
}
Expand Down
16 changes: 8 additions & 8 deletions src/format/humanreadable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,10 @@ impl HumanReadableFormatter {
if let Some(ts) = record.timestamp() {
parts.push(ts.to_string_millis());
}
if record.labels().len() > 0 {
if !record.labels().is_empty() {
parts.push(self.format_dict(record.labels(), "\t"));
}
if record.values().len() > 0 {
if !record.values().is_empty() {
parts.push(
self.format_dict(
&record
Expand All @@ -72,11 +72,11 @@ impl HumanReadableFormatter {
let mut parts = vec![format!("{}\t", vector.timestamp().to_string_millis())];

if let Some(metric) = labels.name() {
parts.push(format!("{}", metric));
parts.push(metric.to_string());
}

let labels = labels.without(&HashSet::new()); // to drop __name__
if labels.len() > 0 || labels.name().is_some() {
if !labels.is_empty() || labels.name().is_some() {
parts.push(format!("{{{}}}\t\t\t", self.format_dict(&labels, ", ")));
}

Expand All @@ -85,7 +85,7 @@ impl HumanReadableFormatter {
lines.push(parts.join(""));
}

if lines.len() == 0 {
if lines.is_empty() {
if !self.verbose {
return Ok(Vec::new());
}
Expand Down Expand Up @@ -136,11 +136,11 @@ impl HumanReadableFormatter {
let mut parts = vec![format!("{}\t", vector.timestamp().to_string_millis())];

if let Some(metric) = labels.name() {
parts.push(format!("{}", metric));
parts.push(metric.to_string());
}

let labels = labels.without(&HashSet::new()); // to drop __name__
if labels.len() > 0 || labels.name().is_some() {
if !labels.is_empty() || labels.name().is_some() {
parts.push(format!("{{{}}}\t\t\t", self.format_dict(&labels, ", ")));
}

Expand All @@ -150,7 +150,7 @@ impl HumanReadableFormatter {
}
}

if lines.len() == 0 {
if lines.is_empty() {
if !self.verbose {
return Ok(Vec::new());
}
Expand Down
2 changes: 1 addition & 1 deletion src/format/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ impl JSONFormatter {
pub fn new(verbose: bool) -> Self {
Self {
verbose,
promfmt: PromApiFormatter::new(),
promfmt: PromApiFormatter::default(),
}
}

Expand Down
6 changes: 4 additions & 2 deletions src/format/promapi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,11 +122,13 @@ impl Scalar {

pub struct PromApiFormatter {}

impl PromApiFormatter {
pub fn new() -> Self {
impl Default for PromApiFormatter {
fn default() -> Self {
Self {}
}
}

impl PromApiFormatter {
// Instant query - instant vector
// {
// "resultType": "vector",
Expand Down
14 changes: 8 additions & 6 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use structopt::StructOpt;
use pq::cliopt::CliOpt;
use pq::input::LineReader;
use pq::output::LineWriter;
use pq::runner::Runner;
use pq::runner::{Runner, RunnerOptions};
use pq::utils::time::TimeRange;

// 'json' // as is
Expand Down Expand Up @@ -38,11 +38,13 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
&opt.program,
Box::new(LineReader::new(BufReader::new(io::stdin()))),
Box::new(LineWriter::new(io::stdout())),
opt.verbose,
opt.interactive,
Some(TimeRange::new(opt.since, opt.until)?),
opt.interval,
opt.lookback,
RunnerOptions::new(
opt.verbose,
opt.interactive,
Some(TimeRange::new(opt.since, opt.until)?),
opt.interval,
opt.lookback,
),
)?;

runner.run()?;
Expand Down
4 changes: 2 additions & 2 deletions src/model/labels.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ impl LabelMatcher {
let label = label.into();
let value = value.into();

assert!(label.len() > 0);
assert!(!label.is_empty());

let re = match match_op {
MatchOp::EqlRe | MatchOp::NeqRe => {
Expand All @@ -96,7 +96,7 @@ impl LabelMatcher {
V: Into<LabelValue>,
{
let name = name.into();
assert!(name.len() > 0);
assert!(!name.is_empty());

Self {
label: NAME_LABEL.to_string(),
Expand Down
6 changes: 3 additions & 3 deletions src/output/writer.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::io::{self, Write};

pub trait Writer {
fn write(&mut self, buf: &Vec<u8>) -> io::Result<()>;
fn write(&mut self, buf: &[u8]) -> io::Result<()>;
}

pub struct LineWriter<W> {
Expand All @@ -17,7 +17,7 @@ impl<W: Write> LineWriter<W> {
}
}

pub fn with_delimiter(inner: W, delim: u8) -> Self {
pub fn new_with_delimiter(inner: W, delim: u8) -> Self {
Self { inner, delim }
}

Expand All @@ -27,7 +27,7 @@ impl<W: Write> LineWriter<W> {
}

impl<W: Write> Writer for LineWriter<W> {
fn write(&mut self, buf: &Vec<u8>) -> io::Result<()> {
fn write(&mut self, buf: &[u8]) -> io::Result<()> {
self.inner.write_all(buf)?;
self.inner.write_all(&[self.delim])
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ impl std::iter::Iterator for Decoder {
match self.strategy.decode(&line) {
Ok(DecodingResult::Tuple(v)) => Some(Ok(Entry::Tuple(line_no, v))),
Ok(DecodingResult::Dict(v)) => Some(Ok(Entry::Dict(line_no, v))),
Err(e) => return Some(Err(("line decoding failed", e).into())),
Err(e) => Some(Err(("line decoding failed", e).into())),
}
}
}
18 changes: 9 additions & 9 deletions src/parse/decoder/json.rs → src/parse/decoding/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@ use crate::error::{Error, Result};

pub struct JSONDecodingStrategy {}

impl JSONDecodingStrategy {
pub fn new() -> Self {
impl Default for JSONDecodingStrategy {
fn default() -> Self {
Self {}
}
}

impl JSONDecodingStrategy {
fn decode_tuple(&self, tuple: Vec<Value>) -> Result<DecodingResult> {
let items: Vec<String> = tuple
.iter()
Expand Down Expand Up @@ -44,16 +46,14 @@ impl JSONDecodingStrategy {
}

impl DecodingStrategy for JSONDecodingStrategy {
fn decode(&self, line: &Vec<u8>) -> Result<DecodingResult> {
fn decode(&self, line: &[u8]) -> Result<DecodingResult> {
match serde_json::from_slice(line) {
Ok(Value::Array(t)) => self.decode_tuple(t),
Ok(Value::Object(o)) => self.decode_dict(o),
Err(e) => return Err(("JSON decoding failed", e).into()),
_ => {
return Err(Error::new(
"JSON decoder supports only flat arrays and objects",
))
}
Err(e) => Err(("JSON decoding failed", e).into()),
_ => Err(Error::new(
"JSON decoder supports only flat arrays and objects",
)),
}
}
}
File renamed without changes.
2 changes: 1 addition & 1 deletion src/parse/decoder/regex.rs → src/parse/decoding/regex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ impl RegexDecodingStrategy {
}

impl DecodingStrategy for RegexDecodingStrategy {
fn decode(&self, line: &Vec<u8>) -> Result<DecodingResult> {
fn decode(&self, line: &[u8]) -> Result<DecodingResult> {
// TODO: handle named captures and return Decoded::Dict.

let caps = self.re.captures(line).ok_or("no match found")?;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@ pub enum DecodingResult {
}

pub trait DecodingStrategy {
fn decode(&self, line: &Vec<u8>) -> Result<DecodingResult>;
fn decode(&self, line: &[u8]) -> Result<DecodingResult>;
}
2 changes: 1 addition & 1 deletion src/parse/mapper/mapper.rs → src/parse/mapping/mapper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ impl Mapper {
Self {
entries,
strategy: MappingStrategy::new(mapping),
range: range.unwrap_or(TimeRange::infinity()),
range: range.unwrap_or_else(TimeRange::infinity),
}
}
}
Expand Down
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ fn parse_timestamp_field(timestamp: &str, format: Option<&str>) -> Result<Timest
Some(format) => parse_time(timestamp, format),
None => match try_parse_time(timestamp) {
Some(timestamp) => Ok(timestamp),
None => return Err(Error::new("couldn't guess time format")),
None => Err(Error::new("couldn't guess time format")),
},
}
}
8 changes: 4 additions & 4 deletions src/parse/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
mod decoder;
mod mapper;
mod decoding;
mod mapping;

pub use decoder::*;
pub use mapper::*;
pub use decoding::*;
pub use mapping::*;
10 changes: 5 additions & 5 deletions src/program.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ fn decoder_regex(input: Span) -> IResult<Decoder> {
return Ok((
rest,
Decoder::Regex {
regex: (*regex).replace(r#"\/"#, "/").to_owned(),
regex: (*regex).replace(r#"\/"#, "/"),
},
));
}
Expand Down Expand Up @@ -229,7 +229,7 @@ fn mapper(input: Span) -> IResult<Mapper> {
}
}

if fields.len() == 0 {
if fields.is_empty() {
return Err(nom::Err::Failure(ParseError::new(
"map expression must have at least one field definition (example: .1:str as some_name)"
.to_owned(),
Expand Down Expand Up @@ -267,7 +267,7 @@ fn mapper_field_dynamic(input: Span) -> IResult<MapperField> {
map(digit1, |d: Span| {
FieldLoc::Position((*d).parse::<usize>().unwrap())
}),
map(label_identifier, |n| FieldLoc::Name(n)),
map(label_identifier, FieldLoc::Name),
))(rest)
{
Ok((rest, loc)) => (rest, loc),
Expand Down Expand Up @@ -378,7 +378,7 @@ fn mapper_field_const(input: Span) -> IResult<MapperField> {
rest,
MapperField {
loc: FieldLoc::Name(name),
typ: FieldType::Const(value.to_owned()),
typ: FieldType::Const(value),
alias: None,
},
))
Expand Down Expand Up @@ -424,7 +424,7 @@ fn find_unescaped(stack: &str, needle: char) -> Option<usize> {
armed = false;
}
}
return None;
None
}

#[cfg(test)]
Expand Down
2 changes: 1 addition & 1 deletion src/query/aggregate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ impl AggregateEvaluator {
InstantVector::new(
v.timestamp(),
agg.values()
.flat_map(|top| top.into_iter().map(|v| (v.1.clone(), v.2)))
.flat_map(|top| top.iter().map(|v| (v.1.clone(), v.2)))
.collect(),
)
}
Expand Down
8 changes: 5 additions & 3 deletions src/query/binary.rs
Original file line number Diff line number Diff line change
Expand Up @@ -341,12 +341,12 @@ fn scalar_op_scalar(op: BinaryOp, lv: SampleValue, rv: SampleValue) -> SampleVal
Sub => lv - rv,

// Comparison
Eql => (lv == rv) as i64 as SampleValue,
Eql => ((lv - rv).abs() < f64::EPSILON) as i64 as SampleValue,
iximiuz marked this conversation as resolved.
Show resolved Hide resolved
Gte => (lv >= rv) as i64 as SampleValue,
Gtr => (lv > rv) as i64 as SampleValue,
Lss => (lv < rv) as i64 as SampleValue,
Lte => (lv <= rv) as i64 as SampleValue,
Neq => (lv != rv) as i64 as SampleValue,
Neq => ((lv - rv).abs() > f64::EPSILON) as i64 as SampleValue,
_ => unimplemented!(),
}
}
Expand All @@ -360,7 +360,9 @@ fn scalar_op_scalar_ex(
) -> Option<SampleValue> {
match (op.kind(), bool_modifier, scalar_op_scalar(op, lv, rv)) {
(BinaryOpKind::Comparison, false, val) if val == 0.0 => None,
(BinaryOpKind::Comparison, false, val) if val == 1.0 => Some(comp_value),
(BinaryOpKind::Comparison, false, val) if (val - 1.0).abs() < f64::EPSILON => {
Some(comp_value)
}
(_, _, val) => Some(val),
}
}
7 changes: 2 additions & 5 deletions src/query/evaluator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ impl QueryEvaluator {
verbose: bool, // TODO: remove it
) -> Result<Self> {
let interval = interval
.or(find_smallest_range(&query))
.or_else(|| find_smallest_range(&query))
.unwrap_or(DEFAULT_INTERVAL);
assert!(interval.as_secs() + (interval.subsec_nanos() as u64) > 0);

Expand Down Expand Up @@ -65,10 +65,7 @@ impl std::iter::Iterator for QueryEvaluator {
self.drained = true;
}

match self.inner.next() {
Some(v) => Some(Ok(v)),
None => None,
}
self.inner.next().map(Ok)
}
}

Expand Down
6 changes: 3 additions & 3 deletions src/query/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ impl AggOverTimeFuncEvaluator {

let samples = v
.samples()
.into_iter()
.iter()
.map(|(labels, values)| {
(
labels.without(&HashSet::new()), // trick to remove __name__
Expand All @@ -57,11 +57,11 @@ impl AggOverTimeFuncEvaluator {
MinOverTime => values
.iter()
.map(|(v, _)| *v)
.fold(SampleValue::INFINITY, |m, c| SampleValue::min(m, c)),
.fold(SampleValue::INFINITY, SampleValue::min),
MaxOverTime => values
.iter()
.map(|(v, _)| *v)
.fold(SampleValue::NEG_INFINITY, |m, c| SampleValue::max(m, c)),
.fold(SampleValue::NEG_INFINITY, SampleValue::max),
SumOverTime => values.iter().map(|(v, _)| *v).sum(),
_ => unreachable!("bug"),
},
Expand Down
Loading