AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / user-14681457

Fee's questions

Martin Hope
Fee
Asked: 2024-10-26 04:19:18 +0800 CST

测试 bytemuck 铸造对齐问题

  • 6

我有以下带有转换逻辑的结构:

enum TagType {
  DOUBLE,
  BYTE,
}

impl TagType {
  /// byte-size actually
  fn size(&self) -> usize {
    match self {
      TagType::DOUBLE => 8,
      TagType::BYTE => 1,
    }
  }
}
/// Entry with buffered data.
///
/// Should not be used for tags where the data fits in the offset field
/// byte-order of the data should be native-endian in this buffer
#[derive(Debug, PartialEq, Clone)]
pub struct BufferedEntry {
    pub tag_type: TagType,
    pub count: u64,
    pub data: Vec<u8>,
}

impl<'a> TryFrom<&'a BufferedEntry> for &'a [f64] {
    type Error = ();

    fn try_from(val: &'a BufferedEntry) -> Result<Self, Self::Error> {
        if val.data.len() != val.tag_type.size() * usize::try_from(val.count)? {
            return Err(());
        }
        match val.tag_type {
            TagType::DOUBLE => Ok(bytemuck::cast_slice(&val.data()[..])),
            _ => Err(()),
        }
    }
}

现在,如果输入向量未正确对齐到 8 字节边界,这将导致 panic,而我无法做到这一点。或者,rkyv 有AlignedVec,这应该正是我需要的。然而,问题是:我该如何测试这一点?例如,我该如何编写一个分配非 64 对齐向量的测试?

rust
  • 1 个回答
  • 56 Views
Martin Hope
Fee
Asked: 2024-10-24 00:27:06 +0800 CST

每次创建未来时,`pub fn long(&self) -> impl Future<Output = ()> + 'static` 是否会泄露数据?

  • 6

基本上,基于这个答案:

pub fn long() -> impl Future<Output = ()> + 'static {
  let s = String::from("what is the answer?");
  async move {
     // `s` gets moved into this block
     println!("{s}");
  }
}

#[tokio::main]
async fn main() {
    let future = long(); // Create the future
    future.await; // Await the future, it will complete, and `s` will be dropped
}

我的问题是,这个'static界限是否会在每次创建未来时泄漏数据?或者'static这里的界限是否意味着特征实现必须是静态的?(例如,函数定义在内存中)。到目前为止,我有:

  1. 问 ChatGPT:它说awaiting 放弃了未来
  2. 书中这段话没有回答。
  3. 阅读《rustonomicon》中关于终身强制的规定
  4. 阅读 类似的 问题

我主要想概念化“静态”的需要和效果;代码已经可以运行了。

背景

我有一个阅读器可以读取某些部分,而对于另一个阅读器,它可能需要先加载其他数据才能继续。我想到最好的办法是:

type Image = Vec<u8>;
#[async_trait]
trait Reader {
    async fn read_into_buffer(&self, offset: u32, buf: &mut [u8]) {
       sleep(2);
       buf.fill(42);
    }
}

struct Decoder<R: Reader> {
  reader: Arc<R>,
  images: HashMap<u32, Arc<Image>>,
}

impl<R> Decoder<R> {
  fn decode_chunk(&self, overview: u32, chunk: usize) -> Result<(),impl Future<Output = Vec<u8>> {
    if let Some(im) = self.images.get(overview) {
      // cheap clones because they are Arcs
      let image = im.clone()
      let r = self.reader.clone()
      async move {
        // don't mention `self` in here
        let buf = vec![0; 42];
        let offset = image[chunk];
        r.read_into_buffer(offset, buf);
        buf
      }
    } else {
        Err(())
    }
  }

  async fn load_overview(&mut self, offset: u32) {
    let buf = vec![0;42];
    self.reader.read_into_buffer(offset, buf).await;
    self.images.insert(offset, buf);
  }
}

可以这样使用:

decoder.load_overview(42).await;
let chunk_1 = decoder.decode_chunk(42, 13).unwrap(); // no await'ing
let chunk_2_err = decoder.decode_chunk(13).unwrap_err(); // chunk 13 isn't loaded
decoder.load_overview(13).await;
let chunk_2 = decoder.decode_chunk(13, 13).unwrap();
let res = (chunk_1.await, chunk_2.await)
asynchronous
  • 1 个回答
  • 64 Views
Martin Hope
Fee
Asked: 2024-01-30 22:31:28 +0800 CST

如何从函数返回“impl Display”

  • 5

我正在努力了解如何正确实现结构的任何类型的替代显示或特征。

struct Fraction {
  numerator: u32,
  denominator: u32
}

impl Fraction {
  fn unicode(&self) -> impl Display {
   // should I use named function or Closure?
   // Where does f come from?
   // can I re-use self?
   // How can I implement a trait that has multiple required functions or `type Output =`?
    fn fmt(&self, f: std::fmt::Formatter) -> std::fmt::Result {
       write!("{}⁄{}", self.numerator, self.denominator)
    } // <- this returns `()`
  }
}

这是行不通的,因为fn fmt作为函数定义,不会返回任何内容。使用未命名的闭包:

impl Fraction {
  fn unicode(&self) -> impl Display {
   // should I use named function or Closure?
   // Where does f come from?
   // can I re-use self?
   // How can I implement a trait that has multiple required functions or `type Output =`?
    |s: &Self, f: std::fmt::Formatter| -> std::fmt::Result {
       write!("{}⁄{}", self.numerator, self.denominator)
    } // <- this returns `()`
  }
}

// somewhere else:
impl Display for Fraction {
  fn fmt(&self, f: std::fmt::Formatter) -> std::fmt::Result {
    write!("{}/{}", self.numerator, self.denominator)
    //        ^-- ASCII '/'
  }
}

说:

error[E0277]: `{closure@src/fraction/generic_fraction.rs:422:9: 422:57}` doesn't implement `std::fmt::Display`
   --> src/fraction/generic_fraction.rs:418:39
    |
418 |     fn display_mixed<'a>(&'a self) -> impl 'a + fmt::Display 
    |                                       ^^^^^^^^^^^^^^^^^^^^^^ `{closure@src/fraction/generic_fraction.rs:422:9: 422:57}` cannot be formatted with the default formatter
    |
    = help: the trait `std::fmt::Display` is not implemented for closure `{closure@src/fraction/generic_fraction.rs:422:9: 422:57}`
    = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead

类似问题:

  • 返回迭代器(或任何其他特征)的正确方法是什么?
  • impl用作函数的参数类型或返回类型时意味着什么?

与返回迭代器(我发现的大多数文档都是关于此的)相反,我试图在函数块中实现我的特征。因此我找不到文档。也许这是错误的做法/思考方式?

rust
  • 1 个回答
  • 52 Views

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve