The missing compound borrowing for Rust.

Overview

borrowme

github crates.io docs.rs build status

The missing compound borrowing for Rust.

Rust comes with two sibling traits which that can convert from owned to borrowed: ToOwned, Borrow and BorrowMut.

These can convert most simple types such as &str to and from String. But lets think of this in a broader perspective. How to we convert a type that has lifetimes, to one which does not? This crate defines its own ToOwned, Borrow and BorrowMut traits which serve a similar purpose to the ones in std but are implemented so that they can do this not only for simple references but also for compound types which receives lifetimes.

To help us implement these traits the #[borrowme] attribute macro is provided (see this section for why it's not a derive).

#[borrowme]
#[derive(Clone)]
#[borrowed_attr(derive(Copy))]
struct Word<'a> {
    text: &'a str,
}

From this we get the following types and implementations:

#[derive(Clone, Copy)]
struct Word<'a> {
    text: &'a str,
}

#[derive(Clone)]
struct OwnedWord {
    text: String,
}

impl borrowme::ToOwned for Word<'_> {
    type Owned = OwnedWord;

    fn to_owned(&self) -> OwnedWord {
        /* .. */
    }
}

impl borrowme::Borrow for OwnedWord {
    type Target<'a> = Word<'a>;

    fn borrow(&self) -> Word<'_> {
        /* .. */
    }
}

By itself this isn't much, but here's the big trick. Types using this crate can be composed and converted into their borrowed or owned counterparts as needed:

use std::collections::HashMap;

#[borrowme]
struct Word<'a> {
    text: &'a str,
}

#[borrowme]
struct Dictionary<'a> {
    words: HashMap<&'a str, Word<'a>>,
}

let dictionary = Dictionary {
    /* .. */
};

let owned_dictionary: OwnedDictionary = borrowme::to_owned(&dictionary);
let dictionary2: Dictionary<'_> = borrowme::borrow(&owned_dictionary);

You might also like...
Learn to write Rust procedural macros [Rust Latam conference, Montevideo Uruguay, March 2019]
Learn to write Rust procedural macros [Rust Latam conference, Montevideo Uruguay, March 2019]

Rust Latam: procedural macros workshop This repo contains a selection of projects designed to learn to write Rust procedural macros — Rust code that g

The Rust Compiler Collection is a collection of compilers for various languages, written with The Rust Programming Language.

rcc The Rust Compiler Collection is a collection of compilers for various languages, written with The Rust Programming Language. Compilers Language Co

Integra8 rust integration test framework Rust with a focus on productivity, extensibility, and speed.

integra8 Integra8 rust integration test framework Rust with a focus on productivity, extensibility, and speed. | This repo is in a "work in progress"

Neofetch but in Rust (rust-toml-fetch)
Neofetch but in Rust (rust-toml-fetch)

rtfetch Configuration Recompile each time you change the config file logo = "arch.logo" # in src/assets. info = [ "", "", "yellow{host_n

Rust Sandbox [code for 15 concepts of Rust language]

Rust-Programming-Tutorial Rust Sandbox [code for 15 concepts of Rust language]. The first time I've been introduced to Rust was on January 2022, you m

TypeRust - simple Rust playground where you can build or run your Rust code and share it with others

Rust playground Welcome to TypeRust! This is a simple Rust playground where you can build or run your Rust code and share it with others. There are a

Rust Imaging Library: A high-level Rust imaging crate.

ril Rust Imaging Library: A performant and high-level Rust imaging crate. Documentation • Crates.io • Discord What's this? This is a Rust crate design

In this repository you can find modules with code and comments that explain rust syntax and all about Rust lang.
In this repository you can find modules with code and comments that explain rust syntax and all about Rust lang.

Learn Rust What is this? In this repository you can find modules with code and comments that explain rust syntax and all about Rust lang. This is usef

Game Boy Emulator written in Rust, as a way to fully grasp the Rust programming language

Flan's Game Boy Emulator Game Boy Emulator written in Rust, as a way to get hands-on with the Rust programming language, and creating a proper project

Comments
  • Support for borrowed Vecs

    Support for borrowed Vecs

    I have the following struct which I need an owned version of.

    #[borrowme]
    #[derive(Clone)]
    pub struct Vector<'v, 't> {
        data: &'v [f32], // Or &'v Vec<f32>
        term: &'t str,
    }
    

    But I get the following error message:

     --> src/vector.rs:3:1
      |
    3 | #[borrowme]
      | ^^^^^^^^^^^ expected `&[f32]`, found `Vec<_>`
      |
      = note: expected reference `&[f32]`
                    found struct `Vec<_>`
      = note: this error originates in the attribute macro `borrowme` (in Nightly builds, run with -Z macro-backtrace for more info)
    
    error[E0277]: the trait bound `f32: borrowme::Borrow` is not satisfied
     --> src/vector.rs:3:1
      |
    3 | #[borrowme]
      | ^^^^^^^^^^^ the trait `borrowme::Borrow` is not implemented for `f32`
      |
    
    question 
    opened by JojiiOfficial 1
  • Add support for BorrowMut

    Add support for BorrowMut

    This introduces and adds support for deriving BorrowMut if mutable access is required. Mutable access is determined if a mutable reference is observed in the field type or if #[borrowme(mut)] is specified.

    A type can either implement Borrow or BorrowMut, borrowed fields are supported for BorrowMut implementations but not vice versa.

    Since compositional types do not have a mutable reference, the #[borrowme(mut)] attribute is required to make these work.

    #[borrowme]
    struct Inner<'a> {
        text: &'static str,
        lang: &'a mut String,
    }
    
    #[borrowme]
    struct BorrowMutStruct<'a> {
        text: &'a str,
        #[borrowme(mut)]
        inner: Inner<'a>,
    }
    
    enhancement 
    opened by udoprog 0
  • Remove prefix support in favor of full name

    Remove prefix support in favor of full name

    This replaces the #[borrowme(prefix = <ident>)] container attribute with #[borrowme(name = <ident>)] since the latter makes much more sense. There is very little value in overriding only part of the name if you're making the effort to override it anyways.

    enhancement 
    opened by udoprog 0
Releases(0.0.13)
  • 0.0.13(May 2, 2023)

    Crate documentation is available on https://docs.rs/borrowme

    First release I'm somewhat happy with. I've landed most of the features I think people will want. After this releases will be spaced more apart and switch to minor releases so that backwards compatible patches can be uploaded.

    Thanks to everyone who've provided feedback so far!

    Source code(tar.gz)
    Source code(zip)
Owner
John-John Tedro
Same username on Telegram, Twitter. setbac on Discord and Twitch. Hit me up if you want to talk!
John-John Tedro
The missing batteries of Rust

stdx - The missing batteries of Rust New to Rust and don't yet know what crates to use? stdx has the best crates. Current revision: stdx 0.119.0-rc, f

Brian Anderson 1.9k Jan 8, 2023
Leetcode Solutions in Rust, Advent of Code Solutions in Rust and more

RUST GYM Rust Solutions Leetcode Solutions in Rust AdventOfCode Solutions in Rust This project demostrates how to create Data Structures and to implem

Larry Fantasy 635 Jan 3, 2023
Simple autoclicker written in Rust, to learn the Rust language.

RClicker is an autoclicker written in Rust, written to learn more about the Rust programming language. RClicker was was written by me to learn more ab

null 7 Nov 15, 2022
Rust programs written entirely in Rust

mustang Programs written entirely in Rust Mustang is a system for building programs built entirely in Rust, meaning they do not depend on any part of

Dan Gohman 561 Dec 26, 2022
Rust 核心库和标准库的源码级中文翻译,可作为 IDE 工具的智能提示 (Rust core library and standard library translation. can be used as IntelliSense for IDE tools)

Rust 标准库中文版 这是翻译 Rust 库 的地方, 相关源代码来自于 https://github.com/rust-lang/rust。 如果您不会说英语,那么拥有使用中文的文档至关重要,即使您会说英语,使用母语也仍然能让您感到愉快。Rust 标准库是高质量的,不管是新手还是老手,都可以从中

wtklbm 493 Jan 4, 2023
A library for extracting #[no_mangle] pub extern "C" functions (https://docs.rust-embedded.org/book/interoperability/rust-with-c.html#no_mangle)

A library for extracting #[no_mangle] pub extern "C" functions In order to expose a function with C binary interface for interoperability with other p

Dmitrii - Demenev 0 Feb 17, 2022
clone of grep cli written in Rust. From Chapter 12 of the Rust Programming Language book

minigrep is a clone of the grep cli in rust Minigrep will find a query string in a file. To test it out, clone the project and run cargo run body poem

Raunak Singh 1 Dec 14, 2021
Rust-blog - Educational blog posts for Rust beginners

pretzelhammer's Rust blog ?? I write educational content for Rust beginners and Rust advanced beginners. My posts are listed below in reverse chronolo

kirill 5.2k Jan 1, 2023
The ray tracer challenge in rust - Repository to follow my development of "The Raytracer Challenge" book by Jamis Buck in the language Rust

The Ray Tracer Challenge This repository contains all the code written, while step by implementing Ray Tracer, based on the book "The Ray Tracer Chall

Jakob Westhoff 54 Dec 25, 2022
Learn-rust-the-hard-way - "Learn C The Hard Way" by Zed Shaw Converted to Rust

Learn Rust The Hard Way This is an implementation of Zed Shaw's Learn X The Hard Way for the Rust Programming Language. Installing Rust TODO: Instruct

Ryan Levick 309 Dec 8, 2022