有什么办法可以在Rust库中包含二进制文件或文本文件? [英] Is there any way to include binary or text files in a Rust library?

查看:498
本文介绍了有什么办法可以在Rust库中包含二进制文件或文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个库,并且我想在其中包含一些二进制(或文本)文件,这些文件中的数据将在运行时进行解析.

I am trying to create a library and I want to include some binary (or text) files in it that will have data which will be parsed at runtime.

我的目的是控制这些文件,不断进行更新,并在每次更新中更改库的版本.

My intention is to have control over these files, update them constantly and change the version of the library in each update.

可以通过货运吗?如果是这样,我如何从我的图书馆访问这些文件?

Is this possible via cargo? If so, how can I access these files from my library?

我想到的一种解决方法是包括一些.rs文件,这些文件具有结构和/或常量(例如&str),这些文件和/或常量将存储数据,但我觉得它很丑.

A workaround I thought of is to include some .rs files with structs and/or constants like &str which will store the data but I find it kind of ugly.

我已将接受的答案更改为更适合我的情况的答案,但是请查看 Shepmaster的答案这可能更适合您的情况.

I have changed the accepted answer to the one that fits more my case, however take a look at Shepmaster's answer as this can be more suitable in your case.

推荐答案

免责声明:我在评论中提到了它,但是我在这里再次重申,因为它给了我更多的阐述空间.

如Shepmaster所说,可以使用include_bytes!include_str!宏在Rust库/可执行文件中包含文字或二进制逐字记录.

As Shepmaster said, it is possible to include text or binary verbatim in a Rust library/executable using the include_bytes! and include_str! macros.

但是,对于您而言,我会避免这样做.通过将内容的解析推迟到运行时:

In your case, however, I would avoid it. By deferring the parsing of the content to run-time:

  • 您允许构建有缺陷的工件.
  • 您会产生(更多)运行时开销(解析时间).
  • 您会产生(更多)空间开销(解析代码).

Rust认识到此问题,并提供了多种旨在克服这些限制的代码生成机制:

Rust acknowledges this issue, and offers multiple mechanisms for code generation destined to overcome those limitations:

  • 宏:如果可以将逻辑编码为宏,则可以将其直接包含在源文件中
  • 插件:通电的宏,可以对任意逻辑进行编码并生成详尽的代码(请参见regex!)
  • build.rs:一个独立的"Rust脚本",运行在编译本身之前,其作用是生成.rs文件
  • macros: if the logic can be encoded into a macro, then it can be included in a source file directly
  • plugins: powered up macros, which can encode any arbitrary logic and generate elaborate code (see regex!)
  • build.rs: an independent "Rust script" running ahead of the compilation proper whose role is to generate .rs files

对于您来说,build.rs脚本听起来很合适:

In your case, the build.rs script sounds like a good fit:

  • 通过将解析代码移到此处,您可以交付更轻的工件
  • 通过提前解析,您可以交付更快的工件
  • 通过提前解析,您可以提供正确的工件

解析结果可以用不同的方式编码,从函数到静态(可能是lazy_static!),因为build.rs可以生成任何有效的Rust代码.

The result of your parsing can be encoded in different ways, from functions to statics (possibly lazy_static!), as build.rs can generate any valid Rust code.

您可以在货物中查看如何使用build.rs文档;您将在这里找到如何将其与Cargo集成以及如何创建文件(以及更多).

You can see how to use build.rs in the Cargo Documentation; you'll find there how to integrate it with Cargo and how to create files (and more).

这篇关于有什么办法可以在Rust库中包含二进制文件或文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆