duplicate 0.2.2

The attribute macro `duplicate` can duplicate an item with variable substitution.
Documentation

duplicate

Attribute macro for code duplication with substitution.

Motivation

If you find yourself in need of copying a block of code and then making some small changes to fit the new use case, this crate is for you.

The duplicate attribute macro will duplicate an item any number of times while inserting custom code in the designated places in each duplicate.

For an in-depth explanation of the syntax and features, see the documentation.

Example

use duplicate::duplicate;

/// Trait we want to implement for u8, u16, and u32
trait IsMax {
  /// Returns true if self is its maximum possible value.
  fn is_max(&self) -> bool;
}

#[duplicate(
  int_type  max_value;
  [ u8 ]    [ 255 ];
  [ u16 ]   [ 65_535 ];
  [ u32 ]   [ 4_294_967_295 ];
)]
impl IsMax for int_type {
  fn is_max(&self) -> bool {
    *self == max_value
  }
}

assert!(!42u8.is_max());
assert!(!42u16.is_max());
assert!(!42u32.is_max());

Expands to:

use duplicate::duplicate;

/// Trait we want to implement for u8, u16, and u32
trait IsMax {
  /// Returns true if self is its maximum possible value.
  fn is_max(&self) -> bool;
}

impl IsMax for u8 {
  fn is_max(&self) -> bool {
    *self == 255
  }
}
impl IsMax for u16 {
  fn is_max(&self) -> bool {
    *self == 65_535
  }
}
impl IsMax for u32 {
  fn is_max(&self) -> bool {
    *self == 4_294_967_295
  }
}

assert!(!42u8.is_max());
assert!(!42u16.is_max());
assert!(!42u32.is_max());

Changelog

This project adheres to Semantic Versioning. During initial development (with versions 0.y.z), bumps to the minor version (y) signify breaking changes.

Added

  • Short syntax now supports nested macro invocations. Can only be used after the initial list of substitution identifiers. See #2.

Changed

  • Updated documentation. The short syntax is now used for the primary examples.
  • Crate readme license section no longer includes paragraph on the licensing of contibutions.

Fixed

  • Fixed an issue where #[duplicate(..)] would throw an error if it was generated by a macro expansion. It would fail if a substitution identifier originated from a macro variable. This is caused by the variable's expansion sometimes being wrapped in a group with no delimiters, which duplicate couldn't handle.

This changelog format is based on Keep a Changelog and shows only the changes since the previous version. See the full changelog for changes to all released versions.

License