use std::fmt::Write as _;
use std::fs;
use std::io::Read as _;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail};
use clap::{Args, ValueEnum};
use duet_core::time::beats_from_ticks;
use duet_core::{Grid, Note, Pitch, Position, Song};
use duet_drums::DrumGrid;
use duet_schemas::{AnyDocument, Document, Kind, Version};
use serde::Serialize;
use crate::config::Config;
use crate::drums::{ReadOptions, grid_of_song, levels_for};
use crate::io::{Format, read_with_from, same_file, song_format, tool, with_end, write_bytes};
#[derive(Clone, Copy, PartialEq, Eq, Debug, ValueEnum)]
pub enum ViewName {
Notes,
Grid,
}
impl ViewName {
fn name(self) -> &'static str {
match self {
ViewName::Notes => "notes",
ViewName::Grid => "grid",
}
}
}
const VIEW_VERSION: u32 = 1;
#[derive(Args)]
pub struct ViewArgs {
input: PathBuf,
#[arg(long = "as", value_enum)]
as_view: Option<ViewName>,
#[arg(short, long)]
output: Option<PathBuf>,
#[arg(long)]
grid: Option<Grid>,
#[arg(long)]
track: Option<String>,
#[arg(long)]
bars: Option<u32>,
#[arg(long)]
snap_levels: bool,
}
#[derive(Args)]
pub struct ApplyArgs {
view: PathBuf,
#[arg(long)]
onto: Option<PathBuf>,
#[arg(short, long)]
output: Option<PathBuf>,
#[arg(long = "as", value_enum)]
as_view: Option<ViewName>,
#[arg(long)]
grid: Option<Grid>,
#[arg(long)]
track: Option<String>,
#[arg(long)]
bars: Option<u32>,
#[arg(long)]
force: bool,
}
#[derive(Debug, Clone, PartialEq)]
struct Header {
view: ViewName,
version: u32,
kind: String,
schema: Version,
track: Option<String>,
step: Option<Grid>,
bars: Option<u32>,
digest: Option<u64>,
}
impl Header {
fn render(&self) -> String {
let mut line = format!(
"# duet {} v{} of {} {}",
self.view.name(),
self.version,
self.kind,
self.schema
);
if let Some(track) = &self.track {
let quoted = track.replace('\\', "\\\\").replace('"', "\\\"");
let _ = write!(line, " track \"{quoted}\"");
}
if let Some(step) = self.step {
let _ = write!(line, " step {step}");
}
if let Some(bars) = self.bars {
let _ = write!(line, " bars {bars}");
}
if let Some(digest) = self.digest {
let _ = write!(line, " from {digest:016x}");
}
line
}
fn parse(line: &str) -> Result<Option<Header>> {
let line = line.trim_end();
if line.starts_with("# notefmt drums v1") {
return Ok(Some(Header::of("grid", "drum-grid", DrumGrid::VERSION)));
}
if line.starts_with("# notefmt v1") {
return Ok(Some(Header::of("notes", "song", Song::VERSION)));
}
let Some(rest) = line.strip_prefix("# duet ") else {
return Ok(None);
};
let bad = |why: &str| anyhow::anyhow!("the header line '{line}' is not a view's: {why}");
let mut words = Words(rest);
let view = match words.next() {
Some("notes") => ViewName::Notes,
Some("grid") => ViewName::Grid,
other => return Err(bad(&format!("{other:?} is not a view (notes or grid)"))),
};
let version = words
.next()
.and_then(|v| v.strip_prefix('v'))
.and_then(|v| v.parse().ok())
.ok_or_else(|| bad("the view's version is v<number>"))?;
if words.next() != Some("of") {
return Err(bad("'of <kind> <version>' follows the view"));
}
let kind = words.next().ok_or_else(|| bad("no kind"))?.to_owned();
let schema = words
.next()
.ok_or_else(|| bad("no schema version"))?
.parse()
.map_err(|e| bad(&format!("{e}")))?;
let mut header = Header {
view,
version,
kind,
schema,
track: None,
step: None,
bars: None,
digest: None,
};
while let Some(word) = words.next() {
match word {
"track" => {
header.track = Some(words.quoted().ok_or_else(|| bad("track \"<name>\""))?)
}
"step" => {
let step = words.next().ok_or_else(|| bad("step <grid>"))?;
header.step = Some(step.parse().map_err(|e| bad(&format!("{e}")))?);
}
"bars" => {
let bars = words.next().and_then(|b| b.parse().ok());
header.bars = Some(bars.ok_or_else(|| bad("bars <number>"))?);
}
"from" => {
let hex = words.next().filter(|h| h.len() == 16);
let digest = hex.and_then(|h| u64::from_str_radix(h, 16).ok());
header.digest = Some(digest.ok_or_else(|| bad("from <16 hex digits>"))?);
}
other => return Err(bad(&format!("'{other}' is not part of a header"))),
}
}
Ok(Some(header))
}
fn of(view: &str, kind: &str, schema: Version) -> Header {
Header {
view: if view == "grid" {
ViewName::Grid
} else {
ViewName::Notes
},
version: 1,
kind: kind.to_owned(),
schema,
track: None,
step: None,
bars: None,
digest: None,
}
}
fn partial(&self) -> bool {
self.view == ViewName::Grid && self.kind == Song::NAME
}
fn check(&self, path: &Path) -> Result<()> {
let shown = path.display();
if self.version != VIEW_VERSION {
bail!(
"{shown} is a {} v{} view; this duet reads {} v{VIEW_VERSION}; update duet",
self.view.name(),
self.version,
self.view.name()
);
}
let reads = match (self.view, self.kind.as_str()) {
(_, k) if k == Song::NAME => Song::VERSION,
(ViewName::Grid, k) if k == DrumGrid::NAME => DrumGrid::VERSION,
(view, kind) => bail!("{shown}: a {} view is of no kind {kind}", view.name()),
};
let found = self.schema;
if found.major != reads.major {
bail!(
"{shown} is a view of {} {found}; this duet reads {} {}.x; `duet convert` reads \
it from a duet that knows {found}",
self.kind,
self.kind,
reads.major
);
}
if found.minor > reads.minor {
bail!(
"{shown} is a view of {} {found}; this duet reads {} up to {reads}; update duet",
self.kind,
self.kind
);
}
Ok(())
}
}
struct Words<'a>(&'a str);
impl<'a> Words<'a> {
fn next(&mut self) -> Option<&'a str> {
let s = self.0.trim_start();
if s.is_empty() {
return None;
}
let end = s.find(char::is_whitespace).unwrap_or(s.len());
self.0 = &s[end..];
Some(&s[..end])
}
fn quoted(&mut self) -> Option<String> {
let s = self.0.trim_start().strip_prefix('"')?;
let mut out = String::new();
let mut chars = s.char_indices();
while let Some((i, c)) = chars.next() {
match c {
'\\' => out.push(chars.next()?.1),
'"' => {
self.0 = &s[i + 1..];
return Some(out);
}
c => out.push(c),
}
}
None
}
}
fn digest<T: Serialize>(body: &T) -> Result<u64> {
let bytes = serde_json::to_vec(body)?;
Ok(bytes.iter().fold(0xcbf2_9ce4_8422_2325_u64, |hash, b| {
(hash ^ u64::from(*b)).wrapping_mul(0x0000_0100_0000_01b3)
}))
}
enum Source {
Song(Document<Song>),
Grid(Document<DrumGrid>),
}
fn text_of(path: &Path) -> Result<String> {
if path == Path::new("-") {
let mut text = String::new();
std::io::stdin()
.read_to_string(&mut text)
.context("reading standard input")?;
Ok(text)
} else {
fs::read_to_string(path).with_context(|| path.display().to_string())
}
}
fn load(path: &Path, what: &str) -> Result<Source> {
let format = song_format(path, None, what)?;
if format != Format::Duet {
let (song, from) = read_with_from(path, format, what)?;
let mut doc = Document::new(tool(), song);
doc.from = from;
return Ok(Source::Song(doc));
}
let text = text_of(path)?;
match AnyDocument::read(&text).with_context(|| path.display().to_string())? {
AnyDocument::Song(mut doc) => {
doc.body.normalize()?;
Ok(Source::Song(doc))
}
AnyDocument::DrumGrid(mut doc) => {
doc.body.normalize()?;
Ok(Source::Grid(doc))
}
other => bail!(
"{} is a {} document, which has no text view",
path.display(),
other.kind()
),
}
}
pub fn run_view(args: ViewArgs, config: &Config) -> Result<()> {
let source = load(&args.input, "duet view reads")?;
let grid_flags: Vec<&str> = [
(args.grid.is_some(), "--grid"),
(args.track.is_some(), "--track"),
(args.bars.is_some(), "--bars"),
]
.into_iter()
.filter_map(|(set, flag)| set.then_some(flag))
.collect();
let text = match (&source, args.as_view) {
(Source::Song(doc), None | Some(ViewName::Notes)) => {
if !grid_flags.is_empty() || args.snap_levels {
bail!(
"{} are for the grid view of a song's drum track (--as grid)",
if grid_flags.is_empty() {
"--snap-levels".to_owned()
} else {
grid_flags.join(", ")
}
);
}
let header = Header {
digest: Some(digest(&doc.body)?),
..Header::of("notes", Song::NAME, Song::VERSION)
};
framed(
&header,
&doc.statements,
&[],
&with_end(&doc.body, config.end)?.to_text(),
)
}
(Source::Grid(doc), None | Some(ViewName::Grid)) => {
if !grid_flags.is_empty() {
bail!(
"{} are for the grid view of a song's drum track; a drum grid has its own",
grid_flags.join(", ")
);
}
let (grid, said) = shown_levels(&doc.body, args.snap_levels)?;
let header = Header {
digest: Some(digest(&doc.body)?),
..Header::of("grid", DrumGrid::NAME, DrumGrid::VERSION)
};
framed(&header, &doc.statements, &said, &grid.to_text()?)
}
(Source::Song(doc), Some(ViewName::Grid)) => {
let Some(step) = args.grid else {
bail!(
"the grid view of a song needs --grid, the step, such as --grid 1/16; duet \
never guesses it"
);
};
let track = drum_track_name(&doc.body, args.track.as_deref(), config)?;
let options = ReadOptions {
grid: step,
track: Some(track.clone()),
bars: args.bars,
snap_levels: false,
};
let exact = grid_of_song(&doc.body, &options, config)?;
let (grid, said) = shown_levels(&exact, args.snap_levels)?;
let header = Header {
track: Some(track),
step: Some(step),
bars: args.bars,
digest: Some(digest(&doc.body)?),
..Header::of("grid", Song::NAME, Song::VERSION)
};
framed(&header, &doc.statements, &said, &grid.to_text()?)
}
(Source::Grid(_), Some(ViewName::Notes)) => bail!(
"{} is a drum-grid document, and the notes view is of a song; duet drums render makes \
a song of a grid",
args.input.display()
),
};
match &args.output {
Some(path) => write_bytes(path, text.as_bytes()),
None => write_bytes(Path::new("-"), text.as_bytes()),
}
}
fn shown_levels(grid: &DrumGrid, snap: bool) -> Result<(DrumGrid, Vec<String>)> {
if !snap {
return Ok((levels_for(grid.clone(), false)?, Vec::new()));
}
let snapped = grid.snapped_to_levels();
let moved = crate::drums::moved_velocities(grid, &snapped);
let said = if moved == 0 {
Vec::new()
} else {
vec![format!(
"this view shows {moved} velocities snapped to the levels; apply --onto keeps them \
exact where their level is unchanged"
)]
};
Ok((snapped, said))
}
fn framed(header: &Header, statements: &[String], said: &[String], body: &str) -> String {
let mut out = header.render();
out.push('\n');
for line in statements.iter().chain(said) {
let _ = writeln!(out, "# {line}");
}
out.push_str(body);
out
}
fn drum_track_name(song: &Song, named: Option<&str>, config: &Config) -> Result<String> {
if let Some(name) = named {
return Ok(name.to_owned());
}
let channel = config.lanes.channel();
let on: Vec<&str> = song
.tracks
.iter()
.filter(|t| t.channel == channel)
.map(|t| t.name.as_str())
.collect();
match on.as_slice() {
[one] => Ok((*one).to_owned()),
[] => bail!(
"the song has no track on channel {channel}, the drum channel; name it with --track"
),
several => bail!(
"the song has {} tracks on channel {channel} ({}); name the one to show with --track",
several.len(),
several.join(", ")
),
}
}
pub fn run_apply(args: ApplyArgs, config: &Config) -> Result<()> {
let text = text_of(&args.view)?;
let shown = args.view.display();
let header = Header::parse(text.lines().next().unwrap_or(""))?;
if let Some(header) = &header {
header.check(&args.view)?;
if let Some(asked) = args.as_view
&& asked != header.view
{
bail!(
"{shown} is a {} view by its header line, not a {} view",
header.view.name(),
asked.name()
);
}
let given: Vec<&str> = [
(args.grid.is_some(), "--grid"),
(args.track.is_some(), "--track"),
(args.bars.is_some(), "--bars"),
]
.into_iter()
.filter_map(|(set, flag)| set.then_some(flag))
.collect();
if !given.is_empty() {
bail!(
"{shown} names its part in its header line; {} are for a view with no header",
given.join(", ")
);
}
}
let Some(view) = header.as_ref().map(|h| h.view).or(args.as_view) else {
bail!(
"{shown} has no header line saying what view it is; name it with --as notes or --as \
grid"
);
};
match (&args.onto, &args.output) {
(None, None) => bail!(
"apply needs --onto <document>, the document the view was rendered from, or -o \
<new.duet> for a new document"
),
(None, Some(output)) => apply_new(&text, view, header.as_ref(), output, &args, config),
(Some(onto), output) => {
let output = output.clone().unwrap_or_else(|| onto.clone());
apply_onto(&text, view, header.as_ref(), onto, &output, &args, config)
}
}
}
fn apply_new(
text: &str,
view: ViewName,
header: Option<&Header>,
output: &Path,
args: &ApplyArgs,
config: &Config,
) -> Result<()> {
let partial =
header.is_some_and(Header::partial) || args.grid.is_some() || args.track.is_some();
refuse_named_output(output)?;
let bytes = match view {
ViewName::Grid if partial => bail!(
"{} is a grid view of one track of a song, which is lossy: it makes no document of \
its own; apply it --onto the song it was rendered from",
args.view.display()
),
ViewName::Notes => {
let mut song = Song::from_text(text)?;
song.normalize()?;
Document::new(tool(), with_end(&song, config.end)?).write()?
}
ViewName::Grid => {
let grid = read_grid_view(text, config)?;
Document::new(tool(), grid).write()?
}
};
write_bytes(output, bytes.as_bytes())
}
fn refuse_named_output(output: &Path) -> Result<()> {
if output != Path::new("-") && song_format(output, None, "apply writes")? != Format::Duet {
bail!("{}: apply writes a document, a .duet", output.display());
}
Ok(())
}
fn read_grid_view(text: &str, config: &Config) -> Result<DrumGrid> {
for notice in &config.text_notices {
eprintln!("duet: {notice}");
}
Ok(DrumGrid::from_text_in(text, &config.text_lanes)?)
}
fn apply_onto(
text: &str,
view: ViewName,
header: Option<&Header>,
onto: &Path,
output: &Path,
args: &ApplyArgs,
config: &Config,
) -> Result<()> {
if song_format(onto, None, "apply --onto changes")? != Format::Duet || onto == Path::new("-") {
bail!(
"{}: --onto names the document to change, a .duet",
onto.display()
);
}
refuse_named_output(output)?;
if args.view != Path::new("-") && same_file(&args.view, onto) {
bail!(
"{} is the view itself, not the document it was rendered from",
onto.display()
);
}
let source = load(onto, "apply --onto reads")?;
let now = match &source {
Source::Song(doc) => digest(&doc.body)?,
Source::Grid(doc) => digest(&doc.body)?,
};
if let Some(was) = header.and_then(|h| h.digest)
&& was != now
{
if !args.force {
bail!(
"{} has changed since the view was rendered: the view is from {was:016x}, and \
the document is now {now:016x}; render the view again, or pass --force to apply \
it anyway",
onto.display()
);
}
eprintln!(
"duet: applying over {}, which has changed since the view was rendered ({was:016x}, \
now {now:016x}), as --force asks",
onto.display()
);
}
let partial = header.map_or(
view == ViewName::Grid && matches!(source, Source::Song(_)),
Header::partial,
);
let bytes = match (source, view) {
(Source::Song(mut doc), ViewName::Notes) => {
let mut song = Song::from_text(text)?;
song.normalize()?;
doc.body = song;
doc.tool = tool();
doc.write()?
}
(Source::Grid(mut doc), ViewName::Grid) if !partial => {
let shown = read_grid_view(text, config)?;
doc.body = keep_exact(&doc.body, shown);
doc.body.check()?;
doc.tool = tool();
doc.write()?
}
(Source::Song(mut doc), ViewName::Grid) => {
let (track, step, bars) = match header {
Some(h) => (h.track.clone(), h.step, h.bars),
None => (args.track.clone(), args.grid, args.bars),
};
let Some(step) = step else {
bail!(
"{} has no header line naming its step; a grid view of a song needs --grid to \
be placed",
args.view.display()
);
};
let track = drum_track_name(&doc.body, track.as_deref(), config)?;
let shown = read_grid_view(text, config)?;
merge_track(&mut doc.body, &shown, &track, step, bars, config)?;
doc.tool = tool();
doc.write()?
}
(source, view) => {
let kind = match source {
Source::Song(_) => Song::NAME,
Source::Grid(_) => DrumGrid::NAME,
};
bail!(
"{} is a {} view, and {} is a {kind} document it cannot be applied onto",
args.view.display(),
header.map_or_else(
|| view.name().to_owned(),
|h| format!("{} view of a {}", h.view.name(), h.kind)
),
onto.display()
)
}
};
write_bytes(output, bytes.as_bytes())
}
fn keep_exact(source: &DrumGrid, mut shown: DrumGrid) -> DrumGrid {
if shown.lanes != source.lanes
|| shown.bar_steps != source.bar_steps
|| shown.levels != source.levels
{
return shown;
}
let levels = source.levels;
for (cell, exact) in shown.vel.data_mut().iter_mut().zip(source.vel.data()) {
if *cell == levels.nearest(*exact) {
*cell = *exact;
}
}
shown
}
fn merge_track(
song: &mut Song,
shown: &DrumGrid,
track: &str,
step: Grid,
bars: Option<u32>,
config: &Config,
) -> Result<()> {
let source = DrumGrid::from_song(
&with_end(song, config.end)?,
step,
&config.lanes,
Some(track),
bars,
)?
.snapped_to_levels();
refuse_unplaceable(&source, shown)?;
let map = song.time_map()?;
let step_ticks = step.step_ticks(song.ticks_per_quarter)?;
let beats = beats_from_ticks(step_ticks, song.ticks_per_quarter);
let columns = source.steps();
let mut ticks = Vec::with_capacity(columns);
for (i, steps) in source.bar_steps.iter().enumerate() {
let start = map.tick(Position::bar(i as u32 + 1))?;
ticks.extend((0..u64::from(*steps)).map(|s| start + s * step_ticks));
}
let Some(drums) = song.tracks.iter_mut().find(|t| t.name == track) else {
bail!("the song has no track named \"{track}\"");
};
for (lane_index, lane) in source.lanes.iter().enumerate() {
for (column, tick) in ticks.iter().enumerate() {
let was = source.vel.data()[lane_index * columns + column];
let now = shown.vel.data()[lane_index * columns + column];
if was == now {
continue;
}
let at = |n: &Note| n.pitch.midi() == lane.key && map.tick(n.at).ok() == Some(*tick);
match (was, now) {
(0, vel) => {
let place = drums
.notes
.iter()
.position(|n| map.tick(n.at).is_ok_and(|t| t > *tick))
.unwrap_or(drums.notes.len());
drums.notes.insert(
place,
Note::new(map.position(*tick), Pitch::new(lane.key)?, beats, vel),
);
}
(_, 0) => drums.notes.retain(|n| !at(n)),
(_, vel) => {
if let Some(note) = drums.notes.iter_mut().find(|n| at(n)) {
note.vel = vel;
}
}
}
}
}
song.check_end()?;
Ok(())
}
fn refuse_unplaceable(source: &DrumGrid, shown: &DrumGrid) -> Result<()> {
let read_only = "a partial view shows it read-only; change it in the notes view, which shows \
the whole song";
let (a, b) = (source.conductor(), shown.conductor());
let fields: [(&str, String, String); 9] = [
("title", format!("{:?}", a.title), format!("{:?}", b.title)),
(
"tpq",
a.ticks_per_quarter.to_string(),
b.ticks_per_quarter.to_string(),
),
(
"tempo",
format!("{:?}", a.tempo_bpm),
format!("{:?}", b.tempo_bpm),
),
("time", a.time_sig.to_string(), b.time_sig.to_string()),
("key", format!("{:?}", a.key), format!("{:?}", b.key)),
(
"a tempo change",
format!("{:?}", a.tempo_changes),
format!("{:?}", b.tempo_changes),
),
(
"a time change",
format!("{:?}", a.time_changes),
format!("{:?}", b.time_changes),
),
(
"a key change",
format!("{:?}", a.key_changes),
format!("{:?}", b.key_changes),
),
(
"end",
source.stated_end().to_string(),
shown.stated_end().to_string(),
),
];
for (what, song, view) in fields {
if song != view {
bail!(
"the view changes the song's {what} (the song's is {song}, the view's {view}); {read_only}"
);
}
}
if source.grid != shown.grid {
bail!(
"the view's step is {}, but it was rendered at {}; {read_only}",
shown.grid,
source.grid
);
}
if source.channel != shown.channel {
bail!(
"the view's channel is {}, but the track's is {}; {read_only}",
shown.channel,
source.channel
);
}
let names = |g: &DrumGrid| {
g.lanes
.iter()
.map(|l| format!("{} ({})", l.name, l.key))
.collect::<Vec<_>>()
.join(", ")
};
if shown.lanes != source.lanes {
bail!(
"the view lists the lanes {}, but the track plays {}; a partial view cannot add or \
remove a lane",
names(shown),
names(source)
);
}
if shown.bar_steps != source.bar_steps {
bail!(
"the view shows {} bars, but the track runs to {}; a partial view cannot add or remove \
a bar",
shown.bar_count(),
source.bar_count()
);
}
if shown.levels != source.levels {
bail!("the view changes the velocity levels; {read_only}");
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_header_line_round_trips() {
let header = Header {
track: Some("The \"Kit\"".into()),
step: Some("1/8t".parse().unwrap()),
bars: Some(4),
digest: Some(0x0b7e_33c1_9a5d_2f84),
..Header::of("grid", "song", Version::new(1, 0))
};
let line = header.render();
assert_eq!(
line,
"# duet grid v1 of song 1.0 track \"The \\\"Kit\\\"\" step 1/8t bars 4 from 0b7e33c19a5d2f84"
);
assert_eq!(Header::parse(&line).unwrap(), Some(header));
let notes = Header::parse("# duet notes v1 of song 1.0 from 3f9a1c0d5e2b7a41")
.unwrap()
.unwrap();
assert_eq!(
(notes.view, notes.digest),
(ViewName::Notes, Some(0x3f9a_1c0d_5e2b_7a41))
);
}
#[test]
fn todays_lines_read_as_v1_of_1_0_and_others_as_no_header() {
let notes = Header::parse("# notefmt v1: positions are bar.beat.tick")
.unwrap()
.unwrap();
assert_eq!(
(notes.view, notes.kind.as_str(), notes.digest),
(ViewName::Notes, "song", None)
);
let grid = Header::parse("# notefmt drums v1: one row per lane")
.unwrap()
.unwrap();
assert_eq!(
(grid.view, grid.kind.as_str()),
(ViewName::Grid, "drum-grid")
);
assert_eq!(Header::parse("tpq 480").unwrap(), None);
assert_eq!(Header::parse("# a comment").unwrap(), None);
for bad in [
"# duet tab v1 of song 1.0",
"# duet notes 1 of song 1.0",
"# duet notes v1 of song",
"# duet notes v1 of song 1.0 from xyz",
"# duet notes v1 of song 1.0 colour red",
] {
assert!(Header::parse(bad).is_err(), "{bad}");
}
}
#[test]
fn a_newer_view_or_schema_version_is_refused_by_name() {
let path = Path::new("x.notes");
let check = |line: &str| {
Header::parse(line)
.unwrap()
.unwrap()
.check(path)
.map_err(|e| e.to_string())
};
assert!(check("# duet notes v1 of song 1.0").is_ok());
let err = check("# duet notes v2 of song 1.0").unwrap_err();
assert!(
err.contains("notes v2 view; this duet reads notes v1"),
"{err}"
);
let err = check("# duet notes v1 of song 1.4").unwrap_err();
assert!(
err.contains("view of song 1.4; this duet reads song up to 1.0"),
"{err}"
);
let err = check("# duet notes v1 of song 2.0").unwrap_err();
assert!(
err.contains("song 1.x") && err.contains("duet convert"),
"{err}"
);
let err = check("# duet grid v1 of lute-tab 1.0").unwrap_err();
assert!(err.contains("no kind lute-tab"), "{err}");
}
#[test]
fn the_digest_is_fnv_1a() {
let fnv = |bytes: &[u8]| {
bytes.iter().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| {
(h ^ u64::from(*b)).wrapping_mul(0x0000_0100_0000_01b3)
})
};
assert_eq!(fnv(b""), 0xcbf2_9ce4_8422_2325);
assert_eq!(fnv(b"a"), 0xaf63_dc4c_8601_ec8c);
assert_eq!(digest(&"a").unwrap(), fnv(b"\"a\""));
}
}