Created
          May 9, 2025 11:57 
        
      - 
      
- 
        Save coderdan/868f9553ccbb9704c6c00cec1fa385e8 to your computer and use it in GitHub Desktop. 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | <?xml version="1.0" encoding="utf-8"?> | |
| <feed xmlns="http://www.w3.org/2005/Atom" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:re="http://purl.org/atompub/rank/1.0"> | |
| <title type="text">Active questions tagged rust - Stack Overflow</title> | |
| <link rel="self" href="https://stackoverflow.com/feeds/tag/rust" type="application/atom+xml" /> | |
| <link rel="alternate" href="https://stackoverflow.com/questions/tagged/?tagnames=rust&sort=active" type="text/html" /> | |
| <subtitle>most recent 30 from stackoverflow.com</subtitle> | |
| <updated>2025-05-09T11:56:01Z</updated> | |
| <id>https://stackoverflow.com/feeds/tag/rust</id> | |
| <creativeCommons:license>https://creativecommons.org/licenses/by-sa/4.0/rdf</creativeCommons:license> | |
| <entry> | |
| <id>https://stackoverflow.com/q/79614066</id> | |
| <re:rank scheme="https://stackoverflow.com">0</re:rank> | |
| <title type="text">Wrap AsyncRead cause ConnectionClose</title> | |
| <category scheme="https://stackoverflow.com/tags" term="asynchronous" /> | |
| <category scheme="https://stackoverflow.com/tags" term="rust" /> | |
| <category scheme="https://stackoverflow.com/tags" term="api-gateway" /> | |
| <category scheme="https://stackoverflow.com/tags" term="rust-tokio" /> | |
| <author> | |
| <name>Yuyang Lu</name> | |
| <uri>https://stackoverflow.com/users/27996148</uri> | |
| </author> | |
| <link rel="alternate" href="https://stackoverflow.com/questions/79614066/wrap-asyncread-cause-connectionclose" /> | |
| <published>2025-05-09T11:53:54Z</published> | |
| <updated>2025-05-09T11:53:54Z</updated> | |
| <summary type="html"> | |
| <p>I am wrapping the AsyncRead by the function of Bandwidth Controling, it will read the bytes from buf firstly and try to acquire the tokens from upstream_control buckets. We assume the poll_read is Ready if it has acquired the enough tokens.</p>
<p>Once it need tokens more than upstream_control buckets can support, it will caused Poll::Pending, which is as we wish. However, when it acquire the tokens, the connection closed for no reason, not the client close the connection. If the request can obtain sufficient tokens at once, there will be no problem, that is, there is no need for Poll::Pending.</p>
<p>I am confused about it, hoping somebody could help me.</p>
<p>the reply of curl is:</p>
<pre><code>* upload completely sent off: 18 bytes
* Empty reply from server
* shutting down connection #0
curl: (52) Empty reply from server
</code></pre>
<p>the Rust code is:</p>
<pre class="lang-rust prettyprint-override"><code>impl&lt;T&gt; AsyncRead for BandwidthControlStream&lt;T&gt;
where
 T: AsyncStream,
{
 fn poll_read(
 self: Pin&lt;&amp;mut Self&gt;,
 cx: &amp;mut Context&lt;'_&gt;,
 buf: &amp;mut ReadBuf&lt;'_&gt;,
 ) -&gt; Poll&lt;io::Result&lt;()&gt;&gt; {
 let this = self.project();
 
 if !*this.has_acquire_upstream {
 ready!(this.inner.poll_read(cx, buf))?;
 *this.has_acquire_upstream = true;
 }
 loop {
 if let Some(acquire) = this.upstream_acquire {
 match Pin::new(acquire).poll(cx){
 Poll::Ready(_) =&gt; {
 *this.upstream_acquire = None;
 *this.has_acquire_upstream = false;
 return Poll::Ready(Ok(()));
 },
 Poll::Pending =&gt; {
 counter!(*METRIC_BLOCK_BAND_UP).increment(1);
 return Poll::Pending;
 },
 }
 } else {
 let size = buf.filled().len();
 if size &lt;= 0 {
 *this.has_acquire_upstream = false;
 return Poll::Ready(Ok(()));
 }
 *this.upstream_acquire =
 Some(Box::pin(this.upstream_control.clone().acquire_owned(size)));
 continue;
 }
 }
 }
}
</code></pre>
<p>The Connection closed for no reason if need Pending for more tokens.</p>
 | |
| </summary> | |
| </entry> | |
| <entry> | |
| <id>https://stackoverflow.com/q/79603776</id> | |
| <re:rank scheme="https://stackoverflow.com">0</re:rank> | |
| <title type="text">std::fmt::Display implementation does not get padded</title> | |
| <category scheme="https://stackoverflow.com/tags" term="rust" /> | |
| <category scheme="https://stackoverflow.com/tags" term="format" /> | |
| <category scheme="https://stackoverflow.com/tags" term="tostring" /> | |
| <author> | |
| <name>sampathsris</name> | |
| <uri>https://stackoverflow.com/users/1461424</uri> | |
| </author> | |
| <link rel="alternate" href="https://stackoverflow.com/questions/79603776/stdfmtdisplay-implementation-does-not-get-padded" /> | |
| <published>2025-05-02T16:38:45Z</published> | |
| <updated>2025-05-09T10:16:25Z</updated> | |
| <summary type="html"> | |
| <p>I have implemented <code>std::fmt::Display</code> for my struct and I have followed the <a href="https://doc.rust-lang.org/std/fmt/trait.Display.html#examples" rel="nofollow noreferrer">example from the <code>Display</code>'s documentation</a> almost verbatim. However, when I try to pad the string representation, it does not get properly padded.</p>
<pre class="lang-rust prettyprint-override"><code>use std::fmt::{Display, Formatter, Result};

struct Point {
 x: i32,
 y: i32,
}

impl Display for Point {
 fn fmt(&amp;self, f: &amp;mut Formatter&lt;'_&gt;) -&gt; Result {
 write!(f, &quot;({}, {})&quot;, self.x, self.y)
 }
}


fn main() {
 let origin = Point { x: 0, y: 0 };
 assert_eq!(format!(&quot;{origin}&quot;), &quot;(0, 0)&quot;); // No padding, works!
 assert_eq!(format!(&quot;{origin:&gt;8}&quot;), &quot; (0, 0)&quot;); // Padded, fails!
 // assertion `left == right` failed
 // left: &quot;(0, 0)&quot;
 // right: &quot; (0, 0)&quot;
}
</code></pre>
<p>Why does this happen, and how can I make my implementation of <code>Display</code> to behave as I intend?</p>
 | |
| </summary> | |
| </entry> | |
| <entry> | |
| <id>https://stackoverflow.com/q/79613252</id> | |
| <re:rank scheme="https://stackoverflow.com">0</re:rank> | |
| <title type="text">How can I restart my running program everytime I save it? [closed]</title> | |
| <category scheme="https://stackoverflow.com/tags" term="rust" /> | |
| <category scheme="https://stackoverflow.com/tags" term="restart" /> | |
| <category scheme="https://stackoverflow.com/tags" term="bevy" /> | |
| <author> | |
| <name>Ben Lloyd</name> | |
| <uri>https://stackoverflow.com/users/18740506</uri> | |
| </author> | |
| <link rel="alternate" href="https://stackoverflow.com/questions/79613252/how-can-i-restart-my-running-program-everytime-i-save-it" /> | |
| <published>2025-05-08T22:24:38Z</published> | |
| <updated>2025-05-09T09:06:34Z</updated> | |
| <summary type="html"> | |
| <p>I have a program running with <code>cargo run</code> and it opens my application which continuously ran til I stopped it. However, I have the problem of every time I edit and save the code, I need to do multiple things to close it; switching tabs, pressing <code>Escape</code> to close the game, running the command again with <code>UpArrowKey</code> in my terminal. Is there an easy way to do this?</p>
 | |
| </summary> | |
| </entry> | |
| <entry> | |
| <id>https://stackoverflow.com/q/79613802</id> | |
| <re:rank scheme="https://stackoverflow.com">0</re:rank> | |
| <title type="text">Write the output of a large iterator to a file</title> | |
| <category scheme="https://stackoverflow.com/tags" term="file" /> | |
| <category scheme="https://stackoverflow.com/tags" term="rust" /> | |
| <category scheme="https://stackoverflow.com/tags" term="io" /> | |
| <category scheme="https://stackoverflow.com/tags" term="iterator" /> | |
| <author> | |
| <name>Pioneer_11</name> | |
| <uri>https://stackoverflow.com/users/16895246</uri> | |
| </author> | |
| <link rel="alternate" href="https://stackoverflow.com/questions/79613802/write-the-output-of-a-large-iterator-to-a-file" /> | |
| <published>2025-05-09T09:01:47Z</published> | |
| <updated>2025-05-09T09:01:47Z</updated> | |
| <summary type="html"> | |
| <p>I'm looking to write an iterator <code>Item = u8</code> to a file. The iterator has a large len so collecting the iterator and then writing the resulting vector isn't very efficient.</p>
<p>I'm thinking of collecting chunks of the iterator and writing chunk by chunk but that also doesn't seem particularly efficient, is there a better/more efficient way to do it (Ideally something which allows me to pipe the iterator strait into a <code>Bufwriter</code> or similar)?</p>
<p>Thanks</p>
 | |
| </summary> | |
| </entry> | |
| <entry> | |
| <id>https://stackoverflow.com/q/79613762</id> | |
| <re:rank scheme="https://stackoverflow.com">-4</re:rank> | |
| <title type="text">Language suggestions for tools based on C library [closed]</title> | |
| <category scheme="https://stackoverflow.com/tags" term="c" /> | |
| <category scheme="https://stackoverflow.com/tags" term="rust" /> | |
| <category scheme="https://stackoverflow.com/tags" term="lua" /> | |
| <category scheme="https://stackoverflow.com/tags" term="embedded" /> | |
| <category scheme="https://stackoverflow.com/tags" term="ada" /> | |
| <author> | |
| <name>user3758232</name> | |
| <uri>https://stackoverflow.com/users/3758232</uri> | |
| </author> | |
| <link rel="alternate" href="https://stackoverflow.com/questions/79613762/language-suggestions-for-tools-based-on-c-library" /> | |
| <published>2025-05-09T08:34:56Z</published> | |
| <updated>2025-05-09T08:34:56Z</updated> | |
| <summary type="html"> | |
| <p>I have a library written in C, that performs some highly optimized basic tasks.</p>
<p>Now I am looking to build tools around those functions, to build web apps, CLI tools, etc. that I can develop more easily and quickly, without requiring particularly strong optimization, since they would run high-level tasks and use C for the small loops.</p>
<p>I have many years of experience with Python, but its interpreter is quite heavy-weight and slow, and its C API is a nightmare (I am writing Python bindings the old way, without cffi, etc.), so I am looking for something that:</p>
<ul>
<li>runs in low-resource environments (possibly embedded systems)</li>
<li>is best for high-level applications</li>
<li>has a good C API</li>
<li>is reasonably fast</li>
<li>possibly is strongly typed (ideally, but not necessarily, statically typed)</li>
<li>is relatively easy to learn</li>
<li>is not necessarily super popular but also not super niche</li>
</ul>
<p>I have looked at Lua, Ada, and Rust so far. I have discarded the latter two as too complex and strict, and maybe too close to C in their purpose. Lua is appealing for its simplicity, but some paradigms just rub me the wrong way (the melting-pot of tables, 1-based arrays...). I might be able to overcome these if nothing better comes up.</p>
<p>Any other suggestion someone may want to add?</p>
<p>Thanks.</p>
 | |
| </summary> | |
| </entry> | |
| <entry> | |
| <id>https://stackoverflow.com/q/79613333</id> | |
| <re:rank scheme="https://stackoverflow.com">0</re:rank> | |
| <title type="text">Seeding Surrealdb Schemafull tables using the Rust sdk</title> | |
| <category scheme="https://stackoverflow.com/tags" term="database" /> | |
| <category scheme="https://stackoverflow.com/tags" term="rust" /> | |
| <category scheme="https://stackoverflow.com/tags" term="embedded-resource" /> | |
| <category scheme="https://stackoverflow.com/tags" term="surrealdb" /> | |
| <author> | |
| <name>Andrew</name> | |
| <uri>https://stackoverflow.com/users/19090746</uri> | |
| </author> | |
| <link rel="alternate" href="https://stackoverflow.com/questions/79613333/seeding-surrealdb-schemafull-tables-using-the-rust-sdk" /> | |
| <published>2025-05-09T00:17:02Z</published> | |
| <updated>2025-05-09T06:35:16Z</updated> | |
| <summary type="html"> | |
| <p>I'm working on an application that embeds a surrealdb database. I'm new to Rust, but this isn't as much of a Rust specific question. How should I go about seeding the database with the schema?</p>
<p>Right now, I check to see if the database directory exists and then if it doesn't I run the schema as a query, but no tables are being created. It doesn't return or throw any errors, but it just fails to generate any tables or indices... basically it just does nothing.</p>
<pre class="lang-rust prettyprint-override"><code>pub async fn setup_file_system_for_data() -&gt; Vec&lt;FlusterError&gt; {
 let data_dir = dirs::data_dir().or(dirs::data_local_dir());
 let status = get_database_status().await;
 let mut errors: Vec&lt;FlusterError&gt; = Vec::new();
 if let Some(dir_name) = data_dir {
 if let Some(res) =
 make_dir_or_fail_to_create(dir_name.join(&quot;Fluster&quot;).join(&quot;data&quot;).join(&quot;database&quot;))
 {
 errors.push(res);
 }
 if let Some(res) = make_dir_or_fail_to_create(dir_name.join(&quot;Fluster&quot;).join(&quot;logs&quot;)) {
 errors.push(res);
 }
 if let Some(res) = make_dir_or_fail_to_create(dir_name.join(&quot;Fluster&quot;).join(&quot;tmp&quot;)) {
 errors.push(res);
 }
 if status == FlusterDatabaseStatus::NotInitialized {
 fluster_db::api::embedded_schema::seed_schema().await;
 }
 } else {
 errors.push(FlusterError::DataDirNotFound())
 }
 errors
}
</code></pre>
<pre class="lang-rust prettyprint-override"><code>#[derive(rust_embed::Embed)]
#[folder = &quot;src/api/schema&quot;]
pub struct EmbeddedSchema;

pub async fn seed_schema() {
 let db = get_database().await.expect(&quot;Failed to get database.&quot;);
 let schema_data = EmbeddedSchema::get(&quot;schema.surql&quot;)
 .expect(&quot;Failed to load database schema&quot;)
 .data;

 let q = schema_data.to_vec();
 if let Ok(schema) = std::str::from_utf8(&amp;q) {
 let res = db.query(schema).await;
 if res.is_err() {
 error!(&quot;Failed to seed database schema.&quot;);
 }
 } else {
 println!(&quot;Failed to convert schema to a string.&quot;);
 }
}
</code></pre>
<p>The embedded file is returning the proper string, but I've been stuck on the initial database phase of this project for way, <em>wayyyy</em> too long.</p>
 | |
| </summary> | |
| </entry> | |
| <entry> | |
| <id>https://stackoverflow.com/q/79607804</id> | |
| <re:rank scheme="https://stackoverflow.com">0</re:rank> | |
| <title type="text">Improving performance of a threadpool</title> | |
| <category scheme="https://stackoverflow.com/tags" term="multithreading" /> | |
| <category scheme="https://stackoverflow.com/tags" term="rust" /> | |
| <category scheme="https://stackoverflow.com/tags" term="parallel-processing" /> | |
| <category scheme="https://stackoverflow.com/tags" term="simulation" /> | |
| <author> | |
| <name>Makogan</name> | |
| <uri>https://stackoverflow.com/users/6202327</uri> | |
| </author> | |
| <link rel="alternate" href="https://stackoverflow.com/questions/79607804/improving-performance-of-a-threadpool" /> | |
| <published>2025-05-06T00:43:02Z</published> | |
| <updated>2025-05-09T01:34:45Z</updated> | |
| <summary type="html"> | |
| <p>I am tying to write my own threadpool, I am noticing that currently, trying to use this custom made threadpool is slower than doing the exact same work in a single threaded fashion and I don't understand why.</p>
<p>This is the threadpool:</p>
<pre class="lang-rs prettyprint-override"><code>use std::sync::atomic::{AtomicBool, AtomicU32};
use std::sync::{
 Arc,
 atomic::{AtomicUsize, Ordering},
};
use std::thread;

use concurrent_queue::ConcurrentQueue;

pub struct TaskInfo
{
 should_stop: bool,
}

pub struct TaskBatchInfo
{
 pub task_index: usize,
 pub current_task_count: Arc&lt;AtomicUsize&gt;,
}

pub struct Task
{
 func: Box&lt;dyn FnMut() -&gt; Option&lt;TaskInfo&gt; + Send + Sync + 'static&gt;,
}

impl Task
{
 fn new(func: impl FnMut() -&gt; Option&lt;TaskInfo&gt; + Send + Sync + Clone + 'static)
 -&gt; Self
 {
 Self {
 func: Box::new(func),
 }
 }

 fn run(mut self) -&gt; Option&lt;TaskInfo&gt; { (self.func)() }
}

pub struct ThreadPool
{
 queue: Arc&lt;ConcurrentQueue&lt;Task&gt;&gt;,
 pub should_stop: Arc&lt;AtomicBool&gt;,
 concurrency: usize,
}

impl ThreadPool
{
 pub fn new(size: usize) -&gt; Self
 {
 Self {
 queue: Arc::new(ConcurrentQueue::unbounded()),
 should_stop: Arc::new(AtomicBool::new(false)),
 concurrency: size,
 }
 }

 pub fn start(&amp;self)
 {
 let queue = self.queue.clone();
 let concurrency = self.concurrency;
 let should_stop = self.should_stop.clone();

 // Spawn the entire thread pool loop on a new thread
 thread::spawn(move || {
 let mut handles = Vec::new();

 for _task_id in 0..concurrency
 {
 let _queue = queue.clone();
 let _should_stop = should_stop.clone();
 let handle = thread::spawn(move || {
 loop
 {
 if _should_stop.load(Ordering::Relaxed)
 {
 break;
 }

 let task = _queue.pop();
 if let Ok(task) = task
 {
 let info = task.run();

 if let Some(info) = info
 {
 if info.should_stop
 {
 _should_stop.store(true, Ordering::Relaxed);
 break;
 }
 }
 } else {
 thread::sleep(std::time::Duration::from_micros(500));
 }
 }
 });

 handles.push(handle);
 }

 for handle in handles
 {
 handle.join().unwrap();
 }
 });
 }

 pub fn add_task&lt;F&gt;(&amp;self, task: F)
 where
 F: FnMut() -&gt; Option&lt;TaskInfo&gt; + Send + Sync + Clone + 'static,
 {
 let _ = self.queue.push(Task::new(task));
 }

 pub fn task_batch&lt;F, T&gt;(pool: Arc&lt;Self&gt;, task_count: usize, task: F, termination: T)
 where
 F: FnMut(TaskBatchInfo) -&gt; Option&lt;TaskInfo&gt; + Send + Sync + Clone + 'static,
 T: FnMut() + Send + Sync + Clone + 'static,
 {
 let task_counter = Arc::new(AtomicUsize::new(task_count));
 Self::inner_task_batch(pool, task, task_count, termination, task_counter)
 }

 pub fn task_batch_with_barrier&lt;F, T, C&gt;(
 pool: Arc&lt;Self&gt;,
 task_count: usize,
 mut task: F,
 mut termination: T,
 context: C,
 ) where
 F: FnMut(TaskBatchInfo, C) + Send + Sync + Clone + 'static,
 T: FnMut() + Send + Sync + Clone + 'static,
 C: Clone + Send + Sync + 'static,
 {
 let wait_flag = Arc::new(AtomicU32::new(0));
 let _wait_flag = wait_flag.clone();

 let context = Arc::new(context);
 ThreadPool::task_batch(
 pool.clone(),
 task_count,
 move |info| {
 task(info, context.clone().as_ref().clone());

 None
 },
 move || {
 termination();
 _wait_flag.store(1, Ordering::Relaxed);
 atomic_wait::wake_all(_wait_flag.as_ref());
 },
 );
 atomic_wait::wait(&amp;wait_flag, 0);
 }

 pub fn task_batch_with_barrier_contextless&lt;F&gt;(
 pool: Arc&lt;Self&gt;,
 task_count: usize,
 mut task: F,
 ) where
 F: FnMut(TaskBatchInfo) + Send + Sync + Clone + 'static,
 {
 let wait_flag = Arc::new(AtomicU32::new(0));
 let _wait_flag = wait_flag.clone();

 ThreadPool::task_batch(
 pool.clone(),
 task_count,
 move |info| {
 task(info);

 None
 },
 move || {
 _wait_flag.store(1, Ordering::Relaxed);
 atomic_wait::wake_all(_wait_flag.as_ref());
 },
 );
 atomic_wait::wait(&amp;wait_flag, 0);
 }

 fn inner_task_batch&lt;F, T&gt;(
 pool: Arc&lt;Self&gt;,
 task: F,
 mut task_count: usize,
 termination: T,
 current_task_counter: Arc&lt;AtomicUsize&gt;,
 ) where
 F: FnMut(TaskBatchInfo) -&gt; Option&lt;TaskInfo&gt; + Send + Sync + Clone + 'static,
 T: FnMut() + Send + Sync + Clone + 'static,
 {
 let task_chunk_size = (task_count / pool.as_ref().concurrency).max(1);
 let quotient = task_count / task_chunk_size;
 let remainder = task_count % task_chunk_size;
 for i in 0..quotient + (remainder &gt; 0usize) as usize
 {
 let mut _task = task.clone();
 let mut _termination = termination.clone();
 let mut _current_task_counter = current_task_counter.clone();
 let _pool = pool.clone();

 pool.add_task(Box::new(move || {
 for j in i * task_chunk_size..((i+1) * task_chunk_size).min(task_count)
 {
 _task(TaskBatchInfo {
 task_index: j,
 current_task_count: _current_task_counter.clone(),
 });
 let val = _current_task_counter.fetch_sub(1, Ordering::Relaxed);
 if val == 1
 {
 _termination()
 }
 }

 None
 }));
 }
 }
}
</code></pre>
<p>This is a criterion benchmark file I made:</p>
<pre class="lang-rs prettyprint-override"><code>use std::hint::black_box;
use std::sync::{Arc, atomic::Ordering};

use atomic_float::AtomicF64;
use criterion::{Criterion, criterion_group, criterion_main};
use thread_pool::*;


fn st_addition(input: &amp;mut Vec&lt;f64&gt;)
{
 for v in input
 {
 *v += 1.0;
 }
}

fn mt_addition(thread_pool: Arc&lt;ThreadPool&gt;, input: Arc&lt;Vec&lt;AtomicF64&gt;&gt;)
{
 ThreadPool::task_batch_with_barrier_contextless(
 thread_pool.clone(),
 input.len(),
 move |info: TaskBatchInfo| {
 let input = input.clone();
 let i = info.task_index;
 input[i].fetch_add(1., Ordering::Relaxed);
 },
 );
}

fn threadpool_benchmark(c: &amp;mut Criterion)
{
 let mut test_bed = vec![0.; 50_000_000];
 c.bench_function(&quot;single thread&quot;, |b| {
 b.iter(|| st_addition(black_box(&amp;mut test_bed)))
 });

 let thread_num: usize = std::thread::available_parallelism().unwrap().into();
 let threadpool = Arc::new(ThreadPool::new(thread_num));

 threadpool.start();

 let mut test_bed = vec![];
 for _ in 0..50_000_000
 {
 test_bed.push(AtomicF64::new(0.0));
 }
 let test_bed = Arc::new(test_bed);

 let pool = threadpool.clone();
 let data = test_bed.clone();
 c.bench_function(&quot;multi thread&quot;, |b| {
 b.iter({
 let value = data.clone();
 let pool = pool.clone();

 move || mt_addition(pool.clone(), value.clone())
 })
 });
}

fn custom_criterion() -&gt; Criterion
{
 Criterion::default()
 .measurement_time(std::time::Duration::from_secs(300))
 .warm_up_time(std::time::Duration::from_secs(2))
}

criterion_group! {
 name = benches;
 config = custom_criterion();
 targets = threadpool_benchmark
}
criterion_main!(benches);
</code></pre>
<p>Which currently reports:</p>
<pre><code>single thread time: [33.355 ms 33.528 ms 33.728 ms]
 change: [+0.6652% +1.7882% +2.8456%] (p = 0.00 &lt; 0.05)
 Change within noise threshold.
Found 13 outliers among 100 measurements (13.00%)
 6 (6.00%) high mild
 7 (7.00%) high severe

multi thread time: [2.7053 s 2.7124 s 2.7198 s]
 change: [+9.0915% +10.740% +12.440%] (p = 0.00 &lt; 0.05)
 Performance has regressed.
</code></pre>
<p>So, somehow, the MT version is slower than the ST version for the same amount of work.</p>
 | |
| </summary> | |
| </entry> | |
| <entry> | |
| <id>https://stackoverflow.com/q/79612554</id> | |
| <re:rank scheme="https://stackoverflow.com">1</re:rank> | |
| <title type="text">Cargo says "Operation not permitted" when compiling on Arch Linux</title> | |
| <category scheme="https://stackoverflow.com/tags" term="linux" /> | |
| <category scheme="https://stackoverflow.com/tags" term="rust" /> | |
| <category scheme="https://stackoverflow.com/tags" term="archlinux" /> | |
| <category scheme="https://stackoverflow.com/tags" term="cargo" /> | |
| <category scheme="https://stackoverflow.com/tags" term="exfat" /> | |
| <author> | |
| <name>axolotlKing0722</name> | |
| <uri>https://stackoverflow.com/users/20839852</uri> | |
| </author> | |
| <link rel="alternate" href="https://stackoverflow.com/questions/79612554/cargo-says-operation-not-permitted-when-compiling-on-arch-linux" /> | |
| <published>2025-05-08T13:57:53Z</published> | |
| <updated>2025-05-08T20:02:05Z</updated> | |
| <summary type="html"> | |
| <p>I have dual-OS setup on my PC with an NTFS partition for Windows, an ext4 partition for Arch Linux and an exFAT partition for shared data.</p>
<p>The data partition is mounted on my Arch system like this (written in <code>/etc/fstab</code>):</p>
<pre><code>LABEL=Data /run/mount/Data exfat rw,relatime,fmask=0000,dmask=0000
</code></pre>
<p>So it's mounted at <code>/run/mount/Data</code>, and every file has read, write and execute permissions for <strong>everyone</strong> (every file and directory is <code>rwxrwxrwx</code>).</p>
<p>I've never had any problems with that setup, but now I tried using cargo on it, and whenever I try to compile a cargo project using <code>cargo run</code> or <code>cargo build</code>, I get an output like this:</p>
<pre><code> Compiling test-crate v0.1.0 (/run/mount/Data/test-crate)
warning: error copying object file `/run/mount/Data/test-crate/target/debug/deps/test_crate-171d3f4b5eb94014.1844j56bgs10zwdjmbmp4ewcl.rcgu.o` to incremental directory as `/run/mount/Data/test-crate/target/debug/incremental/test_crate-1cwjhrbi82tge/s-h75ofrd5kj-040rlag-working/1844j56bgs10zwdjmbmp4ewcl.o`: Operation not permitted (os error 1)

warning: error copying object file `/run/mount/Data/test-crate/target/debug/deps/test_crate-171d3f4b5eb94014.1xv4e2iaijt2221ugfejfkj9p.rcgu.o` to incremental directory as `/run/mount/Data/test-crate/target/debug/incremental/test_crate-1cwjhrbi82tge/s-h75ofrd5kj-040rlag-working/1xv4e2iaijt2221ugfejfkj9p.o`: Operation not permitted (os error 1)

warning: error copying object file `/run/mount/Data/test-crate/target/debug/deps/test_crate-171d3f4b5eb94014.6p6gfwaw87bt5ts5a6awdvy49.rcgu.o` to incremental directory as `/run/mount/Data/test-crate/target/debug/incremental/test_crate-1cwjhrbi82tge/s-h75ofrd5kj-040rlag-working/6p6gfwaw87bt5ts5a6awdvy49.o`: Operation not permitted (os error 1)

warning: error copying object file `/run/mount/Data/test-crate/target/debug/deps/test_crate-171d3f4b5eb94014.6q31c3ffz1ao19rvlsb4tomhl.rcgu.o` to incremental directory as `/run/mount/Data/test-crate/target/debug/incremental/test_crate-1cwjhrbi82tge/s-h75ofrd5kj-040rlag-working/6q31c3ffz1ao19rvlsb4tomhl.o`: Operation not permitted (os error 1)

warning: error copying object file `/run/mount/Data/test-crate/target/debug/deps/test_crate-171d3f4b5eb94014.8wg0ifnylxkm8sglnzmusehrx.rcgu.o` to incremental directory as `/run/mount/Data/test-crate/target/debug/incremental/test_crate-1cwjhrbi82tge/s-h75ofrd5kj-040rlag-working/8wg0ifnylxkm8sglnzmusehrx.o`: Operation not permitted (os error 1)

warning: error copying object file `/run/mount/Data/test-crate/target/debug/deps/test_crate-171d3f4b5eb94014.9edjogq1wwbwf6yxpzh8o80lw.rcgu.o` to incremental directory as `/run/mount/Data/test-crate/target/debug/incremental/test_crate-1cwjhrbi82tge/s-h75ofrd5kj-040rlag-working/9edjogq1wwbwf6yxpzh8o80lw.o`: Operation not permitted (os error 1)

warning: `test-crate` (bin &quot;test-crate&quot;) generated 6 warnings
error: failed to link or copy `/run/mount/Data/test-crate/target/debug/deps/test_crate-171d3f4b5eb94014` to `/run/mount/Data/test-crate/target/debug/test-crate`

Caused by:
 Operation not permitted (os error 1)
</code></pre>
<p>&quot;test-crate&quot; was just the default &quot;Hello, World&quot; project that I created with <code>cargo new test-crate</code>. The crate directory looks like this:</p>
<pre><code>-rwxrwxrwx 1 root root 154 May 8 15:46 Cargo.lock
-rwxrwxrwx 1 root root 81 May 8 15:46 Cargo.toml
drwxrwxrwx 2 root root 131072 May 8 15:46 src
drwxrwxrwx 3 root root 131072 May 8 15:48 target
</code></pre>
<p>So every file here has <code>rwxrwxrwx</code> permissions like they should have, so I don't understand how an operation on these files can't be permitted because literally <em>everything</em> is permitted.</p>
<p>Compiling a project on the linux partition, or compiling a project in the data partition using my windows installation works fine.</p>
<p>When I use <code>sudo cargo run</code>, the default &quot;Hello, world&quot; project compiles, but if you add files like a <code>lib.rs</code>, the compiler panics like this:</p>
<pre><code> Compiling test-crate v0.1.0 (/run/mount/Data/test-crate)
warning: hard linking files in the incremental compilation cache failed. copying files instead. consider moving the cache directory to a file system which supports hard linking in session dir `/run/mount/Data/test-crate/target/debug/incremental/test_crate-3aiikf0zz4qco/s-h75olu36wq-0bx3gll-working`

error: cached cgu 3jc4qbatsnqtmfg9qzi0sbrfc should have an object file, but doesn't


thread 'coordinator' panicked at /usr/src/debug/rust/rustc-1.86.0-src/compiler/rustc_codegen_ssa/src/back/write.rs:1680:29:
/usr/src/debug/rust/rustc-1.86.0-src/compiler/rustc_codegen_ssa/src/back/write.rs:1680:29: worker thread panicked
stack backtrace:
 0: 0x7cd9e10dd6b0 - &lt;std::sys::backtrace::BacktraceLock::print::DisplayBacktrace as core::fmt::Display&gt;::fmt::h1a61e653684797d4
 1: 0x7cd9e112c6e3 - core::fmt::write::hef3878caa31fc074
 2: 0x7cd9e10d1db3 - &lt;unknown&gt;
 3: 0x7cd9e10dd502 - &lt;unknown&gt;
 4: 0x7cd9e10dfabf - &lt;unknown&gt;
 5: 0x7cd9e10df92a - std::panicking::default_hook::hf5b5ddbe229b04b3
 6: 0x7cd9dddd059d - &lt;unknown&gt;
 7: 0x7cd9e10e05f3 - std::panicking::rust_panic_with_hook::h85e74030df1c120f
 8: 0x7cd9e0b29ce5 - &lt;unknown&gt;
 9: 0x7cd9e0b231d9 - std[425a963a3e5d7a57]::sys::backtrace::__rust_end_short_backtrace::&lt;std[425a963a3e5d7a57]::panicking::begin_panic&lt;alloc[4540294945132585]::string::String&gt;::{closure#0}, !&gt;
 10: 0x7cd9e0a25cbd - std[425a963a3e5d7a57]::panicking::begin_panic::&lt;alloc[4540294945132585]::string::String&gt;
 11: 0x7cd9e0baf799 - &lt;unknown&gt;
 12: 0x7cd9e0ba866f - &lt;unknown&gt;
 13: 0x7cd9e0ba862e - &lt;unknown&gt;
 14: 0x7cd9e0baf6b3 - rustc_middle[a294d822c310247b]::util::bug::bug_fmt
 15: 0x7cd9de16fd5e - std[425a963a3e5d7a57]::sys::backtrace::__rust_begin_short_backtrace::&lt;&lt;rustc_codegen_llvm[ac121063ebf01a90]::LlvmCodegenBackend as rustc_codegen_ssa[2746cc10987e5ed]::traits::backend::ExtraBackendMethods&gt;::spawn_named_thread&lt;rustc_codegen_ssa[2746cc10987e5ed]::back::write::start_executing_work&lt;rustc_codegen_llvm[ac121063ebf01a90]::LlvmCodegenBackend&gt;::{closure#5}, core[f10772f7cf65ba1b]::result::Result&lt;rustc_codegen_ssa[2746cc10987e5ed]::back::write::CompiledModules, ()&gt;&gt;::{closure#0}, core[f10772f7cf65ba1b]::result::Result&lt;rustc_codegen_ssa[2746cc10987e5ed]::back::write::CompiledModules, ()&gt;&gt;
 16: 0x7cd9de08857c - &lt;unknown&gt;
 17: 0x7cd9e10e9cab - &lt;unknown&gt;
 18: 0x7cd9dc6a370a - &lt;unknown&gt;
 19: 0x7cd9dc727aac - &lt;unknown&gt;
 20: 0x0 - &lt;unknown&gt;

error: the compiler unexpectedly panicked. this is a bug.

note: we would appreciate a bug report: https://github.com/rust-lang/rust/issues/new?labels=C-bug%2C+I-ICE%2C+T-compiler&amp;template=ice.md

note: rustc 1.86.0 (05f9846f8 2025-03-31) (Arch Linux rust 1:1.86.0-1) running on x86_64-unknown-linux-gnu

note: compiler flags: --crate-type lib -C embed-bitcode=no -C debuginfo=2 -C incremental=[REDACTED]

note: some of the compiler flags provided by cargo are hidden

query stack during panic:
end of query stack
warning: `test-crate` (lib) generated 1 warning
error: could not compile `test-crate` (lib) due to 1 previous error; 1 warning emitted
</code></pre>
<p>Any idea why it works on windows but not on Linux? I guess it's probably due to the exFAT system or how I'm mounting it, but what exactly is wrong there?</p>
<p>I found those two lines with <code>strace</code> that mention os error 1:</p>
<pre><code>write(2, &quot;: error copying object file `/ru&quot;..., 337: error copying object file `/run/mount/Data/test-crate/target/debug/deps/test_crate-5586b82572a0a3b2.3jc4qbatsnqtmfg9qzi0sbrfc.rcgu.o` to incremental directory as `/run/mount/Data/test-crate/target/debug/incremental/test_crate-3aiikf0zz4qco/s-h75v4lhime-1asa3vw-working/3jc4qbatsnqtmfg9qzi0sbrfc.o`: Operation not permitted (os error 1)) = 337
write(2, &quot; Operation not permitted (os er&quot;..., 39 Operation not permitted (os error 1)
</code></pre>
<p>but I just realized this is just cargo writing to stderr so it's useless I guess.</p>
<h1>EDIT: Current workaround</h1>
<p>Because the exFAT filesystem seems to be causing the trouble here, I moved the target dir to my linux partition. For that, I created a <code>~/.cargo/config.toml</code> file that looks like this:</p>
<pre class="lang-ini prettyprint-override"><code>[build]
target-dir = &quot;.cargo/linux-target&quot;
</code></pre>
<p>so the compiled files will now be in <code>~/.cargo/linux-target</code> which is on my linux partition, instead of in the <code>target</code> folder in the project. This could lead to some conflicts if you work on multiple projects but I guess just calling <code>cargo clean</code> should fix most of this.</p>
 | |
| </summary> | |
| </entry> | |
| <entry> | |
| <id>https://stackoverflow.com/q/78972847</id> | |
| <re:rank scheme="https://stackoverflow.com">0</re:rank> | |
| <title type="text">Dioxus Router Error: use navigation doesnt work</title> | |
| <category scheme="https://stackoverflow.com/tags" term="rust" /> | |
| <category scheme="https://stackoverflow.com/tags" term="dioxus" /> | |
| <author> | |
| <name>IvonaK</name> | |
| <uri>https://stackoverflow.com/users/20130220</uri> | |
| </author> | |
| <link rel="alternate" href="https://stackoverflow.com/questions/78972847/dioxus-router-error-use-navigation-doesnt-work" /> | |
| <published>2024-09-11T08:49:52Z</published> | |
| <updated>2025-05-08T19:13:31Z</updated> | |
| <summary type="html"> | |
| <p>I'm working on a project using Dioxus with routing. My problem occurs when trying to navigate to a different route in my component (src/pages/home.rs). I'm getting the following router-related</p>
<pre><code>use crate::api::alpha_vantage::{AlphaVantageClient, StockData};
use dioxus::prelude::*;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
struct SearchResult {
 #[serde(rename = &quot;1. symbol&quot;)]
 symbol: String,
 #[serde(rename = &quot;2. name&quot;)]
 name: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct SearchResponse {
 #[serde(rename = &quot;bestMatches&quot;)]
 best_matches: Vec&lt;SearchResult&gt;,
}

#[component]
pub fn HomePage() -&gt; Element {
 rsx! {
 SearchComponent {}
 }
}

#[component]
fn SearchComponent() -&gt; Element {
 let mut search_query = use_signal(|| String::new());
 let mut search_results = use_signal(|| Vec::&lt;SearchResult&gt;::new());
 let navigator = use_navigator();

 // TODO: add debouncer
 let _ = use_resource(move || async move {
 let query = search_query();
 if !query.is_empty() {
 match search_stocks(query.clone()).await {
 Ok(results) =&gt; search_results.set(results),
 Err(_) =&gt; search_results.set(Vec::new()),
 }
 }
 });
 let on_select_symbol = |symbol: &amp;str| {
 // Navigate to ticker page with the selected symbol
 navigator.push(Route::TickerPage {
 symbol: symbol.to_string(),
 });
 };

 rsx! {
 div { class: &quot;min-h-screen flex items-center justify-center bg-gray-100&quot;,
 div { class: &quot;bg-white shadow-lg rounded-lg p-8 max-w-lg w-full&quot;,
 h1 { class: &quot;text-4xl font-bold text-center text-gray-800&quot;, &quot;Welcome to Stock Sage&quot; }
 p { class: &quot;text-lg text-gray-600 text-center mt-4&quot;, &quot;Search for a stock symbol to get started&quot; }

 div { class: &quot;mt-6&quot;,
 input {
 class: &quot;w-full p-3 border rounded-lg text-gray-700 focus:outline-none focus:ring-2 focus:ring-indigo-500&quot;,
 placeholder: &quot;Search for a stock symbol&quot;,
 oninput: move |evt| search_query.set(evt.value()),
 value: &quot;{search_query}&quot;
 }
 }
 if !search_results().is_empty() {
 div {
 class: &quot;mt-4 bg-white rounded-lg shadow-md overflow-hidden&quot;,
 for result in search_results().iter() {
 div {
 class: &quot;p-3 border-b hover:bg-gray-100 cursor-pointer&quot;,
 onclick: move |_| on_select_symbol(&amp;result.symbol),
 h2 { class: &quot;font-bold&quot;, &quot;{result.symbol}&quot; }
 p { class: &quot;text-gray-600&quot;, &quot;{result.name}&quot; }
 }
 }
 }
 }

 }
 }
 }
}

async fn search_stocks(query: String) -&gt; Result&lt;Vec&lt;SearchResult&gt;, reqwest::Error&gt; {
 let client = AlphaVantageClient::new();
 let url = format!(
 &quot;{}?function=SYMBOL_SEARCH&amp;keywords={}&amp;apikey={}&quot;,
 crate::api::alpha_vantage::BASE_URL,
 query,
 client.api_key
 );

 let response: SearchResponse = client.client.get(&amp;url).send().await?.json().await?;
 Ok(response.best_matches)
}
</code></pre>
<p>my main.rs looks like this</p>
<pre><code>#![allow(non_snake_case)]

use dioxus::prelude::*;
use dioxus_logger::tracing::{info, Level};

use stock_sage::pages::{home::HomePage, ticker::TickerPage};

#[derive(Routable, Clone, Debug, PartialEq)]
#[rustfmt::skip]
pub enum Route {
 #[layout(NavBar)]
 #[route(&quot;/&quot;)]
 HomePage {},
 #[route(&quot;/ticker/:symbol&quot;)]
 TickerPage { symbol: String },
 #[end_layout]
 #[route(&quot;/:..route&quot;)]
 PageNotFound {
 route: Vec&lt;String&gt;,
 },
}

fn main() {
 dotenv::dotenv().ok();
 // Init logger
 dioxus_logger::init(Level::INFO).expect(&quot;failed to init logger&quot;);
 info!(&quot;starting app&quot;);

 let cfg = dioxus::desktop::Config::new()
 .with_custom_head(r#&quot;&lt;link rel=&quot;stylesheet&quot; href=&quot;tailwind.css&quot;&gt;&quot;#.to_string());
 LaunchBuilder::desktop().with_cfg(cfg).launch(App);
}

#[component]
fn App() -&gt; Element {
 rsx! {
 Router::&lt;Route&gt; {}
 }
}

#[component]
fn NavBar() -&gt; Element {
 rsx! {
 nav {
 class: &quot;bg-blue-500 p-4&quot;,
 ul {
 li {
 Link { to: Route::HomePage {}, class: &quot;text-white mr-4&quot;, &quot;Home&quot; }
 Link { to: Route::TickerPage { symbol: &quot;AAPL&quot;.to_string() }, &quot;Apple Stock&quot; }
 }
 }
 }
 Outlet::&lt;Route&gt; {}
 }
}

#[component]
fn PageNotFound(route: Vec&lt;String&gt;) -&gt; Element {
 rsx! {
 h1 { &quot;Page not found&quot; }
 p { &quot;We are terribly sorry, but the page you requested doesn't exist.&quot; }
 pre { color: &quot;red&quot;, &quot;log:\nattempted to navigate to: {route:?}&quot; }
 }
}




#![allow(non_snake_case)]

use dioxus::prelude::*;
use dioxus_logger::tracing::{info, Level};

use stock_sage::pages::{home::HomePage, ticker::TickerPage};

#[derive(Routable, Clone, Debug, PartialEq)]
#[rustfmt::skip]
pub enum Route {
 #[layout(NavBar)]
 #[route(&quot;/&quot;)]
 HomePage {},
 #[route(&quot;/ticker/:symbol&quot;)]
 TickerPage { symbol: String },
 #[end_layout]
 #[route(&quot;/:..route&quot;)]
 PageNotFound {
 route: Vec&lt;String&gt;,
 },
}

fn main() {
 dotenv::dotenv().ok();
 // Init logger
 dioxus_logger::init(Level::INFO).expect(&quot;failed to init logger&quot;);
 info!(&quot;starting app&quot;);

 let cfg = dioxus::desktop::Config::new()
 .with_custom_head(r#&quot;&lt;link rel=&quot;stylesheet&quot; href=&quot;tailwind.css&quot;&gt;&quot;#.to_string());
 LaunchBuilder::desktop().with_cfg(cfg).launch(App);
}

#[component]
fn App() -&gt; Element {
 rsx! {
 Router::&lt;Route&gt; {}
 }
}

#[component]
fn NavBar() -&gt; Element {
 rsx! {
 nav {
 class: &quot;bg-blue-500 p-4&quot;,
 ul {
 li {
 Link { to: Route::HomePage {}, class: &quot;text-white mr-4&quot;, &quot;Home&quot; }
 Link { to: Route::TickerPage { symbol: &quot;AAPL&quot;.to_string() }, &quot;Apple Stock&quot; }
 }
 }
 }
 Outlet::&lt;Route&gt; {}
 }
}

#[component]
fn PageNotFound(route: Vec&lt;String&gt;) -&gt; Element {
 rsx! {
 h1 { &quot;Page not found&quot; }
 p { &quot;We are terribly sorry, but the page you requested doesn't exist.&quot; }
 pre { color: &quot;red&quot;, &quot;log:\nattempted to navigate to: {route:?}&quot; }
 }
} 
</code></pre>
<p>cargo.toml</p>
<pre><code>
dioxus = { version = &quot;0.5&quot;, features = [&quot;desktop&quot;, &quot;router&quot;] }

# Debug
dioxus-logger = &quot;0.5.1&quot;
</code></pre>
<p>Code works fine but problems is mainly with the router i have no idea why it is not working should i export router enum or what ?</p>
<p>Info from cargo check:</p>
<pre class="lang-none prettyprint-override"><code>failed to resolve: use of undeclared type `Route`
 --&gt; src/pages/home.rs:45:24
 |
45 | navigator.push(Route::TickerPage {
 | ^^^^^ use of undeclared type `Route`
 |
help: there is an enum variant `crate::pages::home::IntoRoutable::Route` and 1 other; try using the variant's enum
 |
45 | navigator.push(crate::pages::home::IntoRoutable {
 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
45 | navigator.push(dioxus::prelude::IntoRoutable {
 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

For more information about this error, try `rustc --explain E0433`.
warning: `stock-sage` (lib) generated 4 warnings
</code></pre>
 | |
| </summary> | |
| </entry> | |
| <entry> | |
| <id>https://stackoverflow.com/q/79612960</id> | |
| <re:rank scheme="https://stackoverflow.com">1</re:rank> | |
| <title type="text">How can I write a generic hex deserializer for all unsigned integers using Serde and Num traits?</title> | |
| <category scheme="https://stackoverflow.com/tags" term="rust" /> | |
| <category scheme="https://stackoverflow.com/tags" term="deserialization" /> | |
| <author> | |
| <name>narumi</name> | |
| <uri>https://stackoverflow.com/users/23005998</uri> | |
| </author> | |
| <link rel="alternate" href="https://stackoverflow.com/questions/79612960/how-can-i-write-a-generic-hex-deserializer-for-all-unsigned-integers-using-serde" /> | |
| <published>2025-05-08T18:23:55Z</published> | |
| <updated>2025-05-08T18:23:55Z</updated> | |
| <summary type="html"> | |
| <p>I'm trying to write a generic deserializer function using serde for hex strings like &quot;0xff&quot; to convert into various unsigned integer types (u64, u128, etc). I want to make the function reusable for all types that implement num_traits::Num.</p>
<p>Here’s my current attempt:</p>
<pre class="lang-rust prettyprint-override"><code>use serde::{Deserialize, Deserializer};
use std::str::FromStr;
use num_traits::Num;

fn deserialize_hex&lt;'de, T, D&gt;(deserializer: D) -&gt; Result&lt;T, D::Error&gt;
where
 T: Num + FromStr,
 &lt;T as FromStr&gt;::Err: std::fmt::Display,
 D: Deserializer&lt;'de&gt;,
{
 let s: String = Deserialize::deserialize(deserializer)?;
 let trimmed = s.trim_start_matches(&quot;0x&quot;);
 T::from_str_radix(trimmed, 16).map_err(serde::de::Error::custom)
}
</code></pre>
<p>This fails to compile with the following error:</p>
<pre><code>&lt;T as num_traits::Num&gt;::FromStrRadixErr doesn't implement std::fmt::Display
</code></pre>
<p>I understand the issue comes from the fact that from_str_radix on T: Num returns an associated error type that may not implement Display. But I'm unsure how to abstract this in a generic way.</p>
 | |
| </summary> | |
| </entry> | |
| <entry> | |
| <id>https://stackoverflow.com/q/79612756</id> | |
| <re:rank scheme="https://stackoverflow.com">0</re:rank> | |
| <title type="text">How to use postgis geography type with sqlx</title> | |
| <category scheme="https://stackoverflow.com/tags" term="rust" /> | |
| <category scheme="https://stackoverflow.com/tags" term="postgis" /> | |
| <category scheme="https://stackoverflow.com/tags" term="geo" /> | |
| <category scheme="https://stackoverflow.com/tags" term="sqlx" /> | |
| <author> | |
| <name>JaB</name> | |
| <uri>https://stackoverflow.com/users/5276170</uri> | |
| </author> | |
| <link rel="alternate" href="https://stackoverflow.com/questions/79612756/how-to-use-postgis-geography-type-with-sqlx" /> | |
| <published>2025-05-08T15:43:36Z</published> | |
| <updated>2025-05-08T15:43:36Z</updated> | |
| <summary type="html"> | |
| <p>I work with geospatial data and want to put it into a (postgres) database with the postgis plugin installed.
I know I need the geozero, geo and sqlx crate and also found an example here under <a href="https://crates.io/crates/geozero" rel="nofollow noreferrer">PostGis example</a></p>
<p>But I cannot find any documentation on how to work with geography type insead of geometry.
How can I insert new rows in a table via sqlx which contains a (postgis) geography column?</p>
<p>This is my table:</p>
<pre class="lang-sql prettyprint-override"><code>create table if not exists location
(
 id uuid not null,
 coordinate geography(POINT,4326) not null,
 primary key (id)
);
</code></pre>
<p>I wrote this code</p>
<pre class="lang-rust prettyprint-override"><code>
#[derive(Serialize)]
pub struct Location {
 pub id: Uuid,
 pub coordinate: Coord&lt;f64&gt;,
}


impl FromRow&lt;'_, PgRow&gt; for Location {
 fn from_row(row: &amp;PgRow) -&gt; Result&lt;Self, Error&gt; {
 let geom_bytes: wkb::Decode&lt;Geometry&lt;f64&gt;&gt; = row.try_get(&quot;coordinate&quot;)?;
 let point = Point::try_from(geom_bytes.geometry.unwrap()).unwrap();
 let coord : Coord&lt;f64&gt; = Coord::from(point);

 Ok(Self {
 id: row.try_get(0)?,
 coordinate: coord,
 })
 }
}

pub async fn create_location(
 db_pool: &amp;Pool&lt;Postgres&gt;,
 coordinate: geo::Point&lt;f64&gt;,
) -&gt; Result&lt;Location, sqlx::Error&gt; {
 let uuid = Uuid::new_v4();
 
 let point: geo_types::Geometry&lt;f64&gt; = coordinate.into();
 let point: geozero::wkb::Encode&lt;Geometry&lt;f64&gt;&gt; = wkb::Encode(coordinate.into());
 

 let location = sqlx::query_as::&lt;_, Location&gt;(
 &quot;
 INSERT INTO location (id, coordinate)
 VALUES ($1, ST_SetSRID($2::geometry, 4326)::geography)
 RETURNING *
 &quot;
 )
 .bind(&amp;uuid)
 .bind(point)
 .bind(&amp;collection_uuid)
 .fetch_one(db_pool)
 .await?;

 Ok(location)
}
</code></pre>
<p>From the docs of the geozero crate I know that I have to have a type which implements <a href="https://docs.rs/geozero/0.14.0/geozero/trait.GeozeroGeometry.html" rel="nofollow noreferrer">GeozeroGeometry</a> but that just seems to be true for Geometry.
If I try any geo_type::Coord or some other struct that maps to geography it wont let me encode it via wkb.</p>
<p>This compiles but if I run it I get this error message:</p>
<pre><code>sqlx::Error: ColumnDecode { index: &quot;\&quot;coordinate\&quot;&quot;, source: &quot;mismatched types; Rust type `geozero::wkb::wkb_common::Decode&lt;geo_types::geometry::Geometry&gt;` (as SQL type `geometry`) is not compatible with SQL type `geography`&quot; }
</code></pre>
 | |
| </summary> | |
| </entry> | |
| <entry> | |
| <id>https://stackoverflow.com/q/79608773</id> | |
| <re:rank scheme="https://stackoverflow.com">3</re:rank> | |
| <title type="text">Reset OnceLock in case of Err variant</title> | |
| <category scheme="https://stackoverflow.com/tags" term="rust" /> | |
| <author> | |
| <name>Harry</name> | |
| <uri>https://stackoverflow.com/users/3938402</uri> | |
| </author> | |
| <link rel="alternate" href="https://stackoverflow.com/questions/79608773/reset-oncelock-in-case-of-err-variant" /> | |
| <published>2025-05-06T13:06:06Z</published> | |
| <updated>2025-05-08T13:18:40Z</updated> | |
| <summary type="html"> | |
| <p>Is it possible to reset <code>OnceLock&lt;Result&lt;T, E&gt;&gt;</code> in-case it gets initialized with an <code>Err</code> variant. Below is a sample code which I have written.</p>
<pre><code>use std::sync::OnceLock;

fn foo() {
 static INIT: OnceLock&lt;Result&lt;(), String&gt;&gt; = OnceLock::new();

 // if res is already initialized with Err variant, 
 // reset INIT so that initialization is attempted again
 let res = INIT.get_or_init(|| {
 match ... {
 Ok(something) =&gt; Ok(()),
 Err(err) =&gt; return Err(String::from(&quot;failed&quot;))
 }
 }
 
 if let Ok(()) = res {
 // do something
 }
}

fn main() {
 foo();
}
</code></pre>
 | |
| </summary> | |
| </entry> | |
| <entry> | |
| <id>https://stackoverflow.com/q/79612353</id> | |
| <re:rank scheme="https://stackoverflow.com">0</re:rank> | |
| <title type="text">Why doesn't dtrace produce symbols?</title> | |
| <category scheme="https://stackoverflow.com/tags" term="macos" /> | |
| <category scheme="https://stackoverflow.com/tags" term="rust" /> | |
| <category scheme="https://stackoverflow.com/tags" term="profiling" /> | |
| <category scheme="https://stackoverflow.com/tags" term="debug-symbols" /> | |
| <category scheme="https://stackoverflow.com/tags" term="dtrace" /> | |
| <author> | |
| <name>ora</name> | |
| <uri>https://stackoverflow.com/users/26964941</uri> | |
| </author> | |
| <link rel="alternate" href="https://stackoverflow.com/questions/79612353/why-doesnt-dtrace-produce-symbols" /> | |
| <published>2025-05-08T12:16:06Z</published> | |
| <updated>2025-05-08T12:38:03Z</updated> | |
| <summary type="html"> | |
| <p>I have been trying to do some profiling on MacOS with dtrace, which will be used for a flamegraph. There's a guide I found helpful at <a href="https://carol-nichols.com/2017/04/20/rust-profiling-with-dtrace-on-osx/" rel="nofollow noreferrer">here</a>.</p>
<p>Despite following the guide, and reading <a href="https://stackoverflow.com/questions/43469047/using-dtrace-to-get-stack-traces-profiling-data-on-rust/43491361#43491361">another stackoverflow thread</a>, I am unable to get dtrace to produce symbols, all I get is a bunch of addresses.</p>
<p>Dtrace is outputting some errors: <code>dtrace: error on enabled probe ID 1 (ID 18829: profile:::profile-99): invalid user access in action #2</code>. Perhaps this is a clue? Though, looking online, most people are just redirecting it to <code>/dev/null</code>, so perhaps it is insignificant.</p>
<p>I have my cargo.toml like:</p>
<pre><code>[profile.trace]
inherits = &quot;release&quot;
debug = true
strip = &quot;none&quot;
</code></pre>
<p>and I'm using this script to run my dtrace</p>
<pre class="lang-bash prettyprint-override"><code>sudo dtrace -n 'profile-99 { @[ustack()] = count(); }' \
 -c &quot;$bin $args&quot; \
 -o trace.folded 2&gt; /dev/null
</code></pre>
<p>I am pretty sure dtrace isn't the problem here, and cargo is not emitting debug symbols. When I check with <code>dsymutil</code> there are no symbols present except for <code>malloc</code> and some other standard functions. How can I get it to emit debug symbols? How come <code>debug = true</code> doesn't do the trick?</p>
<p>Edit: I also tried what stackoverflow thread aforementioned used, using <code>-p</code> on the dtrace. However the problem still persists. It is also inconvenient, since now I have to put a sleep at the beginning of my program to give it enough time to latch onto.</p>
<p>Edit 2: cargo does seem to be putting in debug symbols, as confirmed by</p>
<pre><code>Finished `trace` profile [optimized + debuginfo] target(s) in 0.34s
</code></pre>
<p>so perhaps it's an issue with dtrace?</p>
 | |
| </summary> | |
| </entry> | |
| <entry> | |
| <id>https://stackoverflow.com/q/79610578</id> | |
| <re:rank scheme="https://stackoverflow.com">1</re:rank> | |
| <title type="text">Reducing boilerplate error mapping when constrained by the orphan rule</title> | |
| <category scheme="https://stackoverflow.com/tags" term="rust" /> | |
| <category scheme="https://stackoverflow.com/tags" term="error-handling" /> | |
| <category scheme="https://stackoverflow.com/tags" term="rust-tokio" /> | |
| <category scheme="https://stackoverflow.com/tags" term="orphan-rule" /> | |
| <author> | |
| <name>jwimberley</name> | |
| <uri>https://stackoverflow.com/users/5526072</uri> | |
| </author> | |
| <link rel="alternate" href="https://stackoverflow.com/questions/79610578/reducing-boilerplate-error-mapping-when-constrained-by-the-orphan-rule" /> | |
| <published>2025-05-07T12:51:51Z</published> | |
| <updated>2025-05-08T09:38:57Z</updated> | |
| <summary type="html"> | |
| <p>I am working on a project in which I'm using methods from a number of crates Foo1, Foo2, etc., returning objects like <code>Result&lt;T,Foo1Error&gt;</code>, <code>Result&lt;T,Foo2Error&gt;</code>, respectively, within an implementation of a trait from another crate Bar, whose methods must return <code>Result&lt;U,BarError&gt;</code>. Because Foo1, Foo2, and Bar are all external, I cannot implement <code>impl From&lt;Foo1Error&gt; for BarError</code> or ditto for for <code>Foo2Error</code> due to the orphan rule. The popular third-party crates for error handling (error_chain, thiserror, etc.) don't look to me like they help, since they are generally for creating new error types and I'm stuck with having to return <code>BarError</code>. So, I've defined functions like <code>foo1err_to_barerr</code> and <code>foo2err_to_barerr</code> and my code is littered with dozens of chains involving <code>.map_err(foo1err_to_barerr)?</code>.</p>
<p>While it works perfectly well, this visually clutters up the logical parts of the code quite a bit. Are there any alternative techniques that move some of the error mapping boilerplate out of the logical parts of code? If I only had <code>Foo1Error</code> to worry about, for each trait method I'm implementing I'd just make separate method that returned <code>Result&lt;U,Foo1Error&gt;</code> and then all the trait method would do would map the error (collapsing multiple map_err calls into one). But, I have multiple external error types to deal with, and so that new helper method would have to return a boxed error, or a custom error enum, and between the duplication of methods and new compound error types I think I wouldn't (personally) prefer that style any more.</p>
<p>If I permit myself to dream up some blue sky syntax (of course not something Rust supports) would be the ability to define error mapping that happens when the function scope exits: in the meat of the method I could just use <code>?</code> to my heart's content, and then state once how each error type coming from a <code>?</code> has to map to the returned Result's error type.</p>
<p>I kept everything above generic, but in case there is a <em>particular</em> solution rather than a general one, the &quot;Bar&quot; crate is actually tonic and <code>BarError</code> is actually <code>tonic::Status</code>.</p>
 | |
| </summary> | |
| </entry> | |
| <entry> | |
| <id>https://stackoverflow.com/q/79611233</id> | |
| <re:rank scheme="https://stackoverflow.com">0</re:rank> | |
| <title type="text">How should I structure this websocket-based WASM app?</title> | |
| <category scheme="https://stackoverflow.com/tags" term="rust" /> | |
| <category scheme="https://stackoverflow.com/tags" term="websocket" /> | |
| <category scheme="https://stackoverflow.com/tags" term="wasm-bindgen" /> | |
| <category scheme="https://stackoverflow.com/tags" term="web-sys" /> | |
| <author> | |
| <name>Dacromir</name> | |
| <uri>https://stackoverflow.com/users/6901697</uri> | |
| </author> | |
| <link rel="alternate" href="https://stackoverflow.com/questions/79611233/how-should-i-structure-this-websocket-based-wasm-app" /> | |
| <published>2025-05-07T18:40:48Z</published> | |
| <updated>2025-05-07T22:57:14Z</updated> | |
| <summary type="html"> | |
| <p>I'm trying to build a frontend application using rust wasm and a websocket to connect to the server. Here's the desired core logic:</p>
<ol>
<li>Server (axum) needs to send a command to the app</li>
<li>Server creates an instance of an Enum called <code>ServerMessage</code> that contains a variant for each valid command that the server can send</li>
<li>Server serializes that instance using <code>serde_cbor</code>, and sends it as a binary message over the websocket</li>
<li>App receives the binary data and deserializes it back into a <code>ServerMessage</code></li>
<li>App does whatever it was commanded to do by the server</li>
</ol>
<p>I have a similar flow working in the other direction: if there's data that needs to be sent back to the server (e.g. user input), the app creates a <code>ClientMessage</code>, serializes it, and sends it over the websocket.</p>
<p>On the server side, each active websocket connection runs in its own tokio task. When a message comes in, it is deserialized into a <code>ClientMessage</code>, which is then passed to the main thread over an <a href="https://doc.rust-lang.org/std/sync/mpsc/index.html" rel="nofollow noreferrer">mpsc</a> channel. The main thread processes messages one at a time as they come in. This setup works well for what I'm looking to do.</p>
<p>However, I'm lost on how to structure the WASM app to handle the desired logic above, largely because (as far as I'm aware) there's no way to use an async runtime or channels.</p>
<p>Below is a minimal example of what I'm trying to do. In this case, there are only two commands the server can send: <code>ConsoleLog</code> which instructs the app to log some text to console, or <code>Increment</code> which instructs the app to increment its <code>value</code> and update the display.</p>
<pre class="lang-rust prettyprint-override"><code>use serde::{Deserialize, Serialize};
use serde_cbor::from_slice;
use wasm_bindgen::prelude::*;
use web_sys::{
 console, js_sys, window, MessageEvent, WebSocket
};

#[wasm_bindgen]
pub struct App {
 websocket: WebSocket,
 value: i32
}

#[wasm_bindgen]
impl App {
 pub fn new() -&gt; App {
 let ws = WebSocket::new(&quot;http://127.0.0.1:8080/ws&quot;).unwrap();
 ws.set_binary_type(web_sys::BinaryType::Arraybuffer);

 return App {
 websocket: ws,
 value: 0
 }
 }

 pub fn start(&amp;mut self) {
 // OnMessage callback
 let onmessage_callback = Closure::&lt;dyn FnMut(_)&gt;::new(move |e: MessageEvent| {
 if let Ok(abuf) = e.data().dyn_into::&lt;js_sys::ArrayBuffer&gt;() {
 // Deserialize data
 let bin_vec = js_sys::Uint8Array::new(&amp;abuf).to_vec();
 let server_message: ServerMessage = from_slice(&amp;bin_vec).unwrap();

 // Handle message
 self.handle_message(server_message);
 }
 });

 self.websocket.set_onmessage(Some(onmessage_callback.as_ref().unchecked_ref()));
 onmessage_callback.forget();
 }
}

/// A message sent from the server (axum)
#[derive(Debug, Deserialize, Serialize)]
pub enum ServerMessage {
 ConsoleLog(String),
 Increment(i32)
}

impl App {
 fn handle_message(&amp;mut self, message: ServerMessage) {
 match message {
 ServerMessage::ConsoleLog(text) =&gt; {
 console::log_1(&amp;text.into());
 }
 ServerMessage::Increment(n) =&gt; {
 // Increment value
 self.value += n;
 
 // Get counter element
 let document = window().unwrap().document().unwrap();
 let element = document.get_element_by_id(&quot;counter&quot;).unwrap();
 
 // Update display
 element.set_text_content(Some(&amp;self.value.to_string()));
 }
 }
 }
}
</code></pre>
<p>This code won't compile because borrowed data (the reference to <code>self</code>) escapes the method body. I've tried a few other variations of the code that run into similar errors with lifetimes and ownership. I have a clear vision of how I want the code to work, but I'm stuck on how to write it within the constraints of a WASM app.</p>
<p>How can I adjust this code to successfully use the core logic above?</p>
 | |
| </summary> | |
| </entry> | |
| <entry> | |
| <id>https://stackoverflow.com/q/79611008</id> | |
| <re:rank scheme="https://stackoverflow.com">1</re:rank> | |
| <title type="text">dropdown paramspec use</title> | |
| <category scheme="https://stackoverflow.com/tags" term="rust" /> | |
| <category scheme="https://stackoverflow.com/tags" term="gtk4" /> | |
| <author> | |
| <name>tresgros pipo</name> | |
| <uri>https://stackoverflow.com/users/30474342</uri> | |
| </author> | |
| <link rel="alternate" href="https://stackoverflow.com/questions/79611008/dropdown-paramspec-use" /> | |
| <published>2025-05-07T16:18:55Z</published> | |
| <updated>2025-05-07T22:06:16Z</updated> | |
| <summary type="html"> | |
| <p>I want to implement a choice with a DropDown, clicking on the DropDown to execute a connect_closure, reading doc I guess the choice is in the paramspec, but I am unable to retrieve the choice in the ParamSpec ?</p>
<p>I have a Dropdown declared:</p>
<pre><code>let choix = [&quot;Choice 1&quot;,&quot;Choice 2&quot;]
let drop_down2 = gtk::DropDown::from_strings(&amp;choix);
</code></pre>
<p>and a connect_closure to deal with</p>
<pre><code>drop_down2.connect_closure(
 &quot;notify::selected&quot;,
 false,
 glib::closure_local!(move |_gg: glib::Object, pspec: glib::ParamSpec|
 println!(&quot;{:?}&quot;, pspec.downcast::&lt;glib::ParamSpecUInt&gt;().unwrap())
 );
</code></pre>
<p>I get on the console 'ParamSpecUInt { inner: Shared { inner: 0x1db1eff0700 } }', so the object exist</p>
<p>I would like to get 0 or 1 from that, but I go through the GLIB doc, impossible to find the right command</p>
<p>As a work around, I get it with a 'drop_down2.selected()', but it is annoying if I could get with paramspec.</p>
<p>Any idea ???</p>
<p>Thanks</p>
 | |
| </summary> | |
| </entry> | |
| <entry> | |
| <id>https://stackoverflow.com/q/79609586</id> | |
| <re:rank scheme="https://stackoverflow.com">-6</re:rank> | |
| <title type="text">Compiler source code pointing to Box::new([;]) calling heap allocator (if at all) [closed]</title> | |
| <category scheme="https://stackoverflow.com/tags" term="rust" /> | |
| <author> | |
| <name>ZeZNiQ</name> | |
| <uri>https://stackoverflow.com/users/4726668</uri> | |
| </author> | |
| <link rel="alternate" href="https://stackoverflow.com/questions/79609586/compiler-source-code-pointing-to-boxnew-calling-heap-allocator-if-at-all" /> | |
| <published>2025-05-06T22:39:03Z</published> | |
| <updated>2025-05-07T15:08:36Z</updated> | |
| <summary type="html"> | |
| <p>A similar question has been asked before:
<a href="https://users.rust-lang.org/t/help-heap-allocation-stack-overflow-error/23783" rel="nofollow noreferrer">https://users.rust-lang.org/t/help-heap-allocation-stack-overflow-error/23783</a></p>
<p>But it doesn't look like anybody is able to justify why this is the case despite rust book specifying that this is a way to allocate on heap:
<a href="https://doc.rust-lang.org/book/ch15-01-box.html#using-a-boxt-to-store-data-on-the-heap" rel="nofollow noreferrer">https://doc.rust-lang.org/book/ch15-01-box.html#using-a-boxt-to-store-data-on-the-heap</a></p>
<p>If this is indeed compiler &quot;magic&quot; as some other forums seem to suggest, can someone please point out in source code where that &quot;magic&quot; is happening?</p>
<hr />
<p>More precisely - where is the call to request the heap allocator actually being made? Is the rust compiler calling glibc's malloc(), or does the rust compiler have its own hooks into glibc such that it could call the heap allocator, or does the rust compiler directly call the heap allocator (bypassing libc), or does the rust compiler make syscalls like sbrk() or mmap() to allocate on heap, etc.</p>
<p>Saying it's &quot;magic&quot; is not an acceptable answer. Whole point of this question is to de-mystify this &quot;magic&quot; so its no longer &quot;magic&quot;.</p>
 | |
| </summary> | |
| </entry> | |
| <entry> | |
| <id>https://stackoverflow.com/q/79610453</id> | |
| <re:rank scheme="https://stackoverflow.com">1</re:rank> | |
| <title type="text">How to override the optimization levels of some dependencies, transitively?</title> | |
| <category scheme="https://stackoverflow.com/tags" term="rust" /> | |
| <category scheme="https://stackoverflow.com/tags" term="rust-cargo" /> | |
| <author> | |
| <name>Matthieu M.</name> | |
| <uri>https://stackoverflow.com/users/147192</uri> | |
| </author> | |
| <link rel="alternate" href="https://stackoverflow.com/questions/79610453/how-to-override-the-optimization-levels-of-some-dependencies-transitively" /> | |
| <published>2025-05-07T11:53:47Z</published> | |
| <updated>2025-05-07T14:29:29Z</updated> | |
| <summary type="html"> | |
| <p>In the following not-so-simple situation:</p>
<ol>
<li>A root workspace, with a few crates including <code>root-crypto</code>.
<ul>
<li>Where the <code>root-crypto</code> crate depends on various crypto crates: <code>k256</code>, <code>sha2</code>, <code>sha3</code>, ...</li>
</ul>
</li>
<li>An application workspace, with a few binaries including <code>app-foo</code>.
<ul>
<li>Where the <code>app-foo</code> crate depends on <code>root-crypto</code> amongst other <code>root-*</code> crates.</li>
</ul>
</li>
</ol>
<p>For debugging purposes, it is desirable to compile <code>app-foo</code> and its other <code>app-*</code> and <code>root-*</code> dependencies in debug mode (<code>opt-level</code> at 0 or 1).</p>
<p>However, compiling the cryptographic crates -- especially <code>k256</code> -- in debug mode is truly terrible for performance: calculating one signature takes 20x longer in debug, compared to release!</p>
<p>The key answer appears to be to override the <code>opt-level</code> of <code>k256</code> (<a href="https://doc.rust-lang.org/cargo/reference/profiles.html#overrides" rel="nofollow noreferrer">see Profiles</a>), but <strong>how?</strong></p>
<p>If in the <code>root</code> workspace, one uses:</p>
<pre class="lang-ini prettyprint-override"><code>[profile.dev.package.&quot;*&quot;]
opt-level = 3
</code></pre>
<p>This will likely work when compiling within the <code>root</code> workspace, but not within the <code>app</code> workspace.</p>
<p>If in the <code>app</code> workspace, one uses:</p>
<pre class="lang-ini prettyprint-override"><code>[profile.dev.package.&quot;*&quot;]
opt-level = 3
</code></pre>
<p>Then the <code>root-*</code> dependencies will also get optimized, which is undesirable.</p>
<p>Is specifying the overrides in the <code>root-crypto</code>'s Cargo.toml sufficient, so it applies to all its users?</p>
<p>Is specifying the top-level crates (<code>k256</code>, <code>sha2</code>, and <code>sha3</code>) sufficient, or does one need to specify all their transitive dependencies too? There's 28 in total for now, already, and as versions are upgraded this list may change...</p>
<pre class="lang-none prettyprint-override"><code>base16ct
base64ct
cfg-if
const-oid
cpufeatures
crypto-bigint
der
digest
ecdsa
elliptic-curve
ff
generic-array
group
hmac
k256
keccak
once_cell
pem-rfc7468
pkcs8
rand_core
rfc6979
sec1
sha2
sha3
signature
spki
subtle
zeroize
</code></pre>
 | |
| </summary> | |
| </entry> | |
| <entry> | |
| <id>https://stackoverflow.com/q/79609619</id> | |
| <re:rank scheme="https://stackoverflow.com">3</re:rank> | |
| <title type="text">Unexpected default drop behavior in doubly-linked list</title> | |
| <category scheme="https://stackoverflow.com/tags" term="rust" /> | |
| <author> | |
| <name>Igor Urisman</name> | |
| <uri>https://stackoverflow.com/users/6357920</uri> | |
| </author> | |
| <link rel="alternate" href="https://stackoverflow.com/questions/79609619/unexpected-default-drop-behavior-in-doubly-linked-list" /> | |
| <published>2025-05-06T23:20:17Z</published> | |
| <updated>2025-05-06T23:51:51Z</updated> | |
| <summary type="html"> | |
| <p>I'm working on some course material, where I'll demo the <code>Box</code>, <code>Rc</code>, and <code>RefCell</code> types by gradually developing a singly-linked stack and a doubly linked deque. The default <code>Drop</code> implementation for the <code>Stack</code> (understandably) is recursive and hence blows the stack on large enough lists. (I then develop a custom <code>Drop</code> impl that is not recursive.) However, the default <code>Drop</code> implementation for the doubly linked deque works just fine (if, perhaps inefficiently?) and I would like to understand why.</p>
<p>The structs are as follows.</p>
<p>Singly-linked stack:</p>
<pre class="lang-rust prettyprint-override"><code>struct Stack&lt;E&gt; {
 head: Option&lt;Box&lt;StackNode&lt;E&gt;&gt;&gt;,
 size: usize,
}

struct StackNode&lt;E&gt; {
 elem: E,
 next: Option&lt;Box&lt;StackNode&lt;E&gt;&gt;&gt;,
}

</code></pre>
<p>Doubly-linked deque:</p>
<pre class="lang-rust prettyprint-override"><code>struct Deque&lt;E&gt; {
 head: Option&lt;Rc&lt;RefCell&lt;DequeNode&lt;E&gt;&gt;&gt;&gt;,
 tail: Option&lt;Rc&lt;RefCell&lt;DequeNode&lt;E&gt;&gt;&gt;&gt;,
 size: usize,
}

struct DequeNode&lt;E&gt; {
 next: Option&lt;Rc&lt;RefCell&lt;DequeNode&lt;E&gt;&gt;&gt;&gt;,
 prev: Option&lt;Rc&lt;RefCell&lt;DequeNode&lt;E&gt;&gt;&gt;&gt;,
 elem: E,
}
</code></pre>
<p>(I'm &quot;eliding&quot; the implementations, assuming they're not relevant.)</p>
 | |
| </summary> | |
| </entry> | |
| <entry> | |
| <id>https://stackoverflow.com/q/79486773</id> | |
| <re:rank scheme="https://stackoverflow.com">8</re:rank> | |
| <title type="text">How to reuse full-featured Deno in my Rust project?</title> | |
| <category scheme="https://stackoverflow.com/tags" term="javascript" /> | |
| <category scheme="https://stackoverflow.com/tags" term="rust" /> | |
| <category scheme="https://stackoverflow.com/tags" term="deno" /> | |
| <author> | |
| <name>typed-sigterm</name> | |
| <uri>https://stackoverflow.com/users/19171888</uri> | |
| </author> | |
| <link rel="alternate" href="https://stackoverflow.com/questions/79486773/how-to-reuse-full-featured-deno-in-my-rust-project" /> | |
| <published>2025-03-05T14:20:19Z</published> | |
| <updated>2025-05-06T23:12:40Z</updated> | |
| <summary type="html"> | |
| <p>I'm trying to implement a JS plugin system for my project that uses Deno underground (for its comprehensive permission model). I expect it to have:</p>
<ul>
<li>ECMAScript built-ins (e.g. <code>Math</code> <code>TypeError</code>)</li>
<li><a href="https://docs.deno.com/api/web/all_symbols" rel="noreferrer">Web APIs that Deno has implemented</a> (e.g. <code>setTimeout</code> <code>performance</code>)</li>
<li>Deno/Node.js APIs (e.g. <code>Deno.inspect</code> <code>process</code>) (a subset of them is okay)</li>
<li>Deno built-in permission model</li>
<li>Rust ←→ JS communication</li>
</ul>
<p>I tried <a href="https://crates.io/crates/deno_core" rel="noreferrer"><code>deno_core</code></a>, but it only has ECMAScript built-ins. (<a href="https://codesandbox.io/p/devbox/heuristic-bas-m9t4vf" rel="noreferrer">reproduction</a>) And <a href="https://crates.io/crates/deno" rel="noreferrer"><code>deno</code></a> is executable.</p>
 | |
| </summary> | |
| </entry> | |
| <entry> | |
| <id>https://stackoverflow.com/q/79609445</id> | |
| <re:rank scheme="https://stackoverflow.com">-1</re:rank> | |
| <title type="text">Rust Overflow evaluating the requirement &_: IntoIterator when using imap's fetch method in Rust</title> | |
| <category scheme="https://stackoverflow.com/tags" term="recursion" /> | |
| <category scheme="https://stackoverflow.com/tags" term="rust" /> | |
| <category scheme="https://stackoverflow.com/tags" term="overflow" /> | |
| <category scheme="https://stackoverflow.com/tags" term="imap" /> | |
| <category scheme="https://stackoverflow.com/tags" term="traits" /> | |
| <author> | |
| <name>thacaout</name> | |
| <uri>https://stackoverflow.com/users/15508621</uri> | |
| </author> | |
| <link rel="alternate" href="https://stackoverflow.com/questions/79609445/rust-overflow-evaluating-the-requirement-intoiterator-when-using-imaps-fetc" /> | |
| <published>2025-05-06T20:33:08Z</published> | |
| <updated>2025-05-06T21:30:58Z</updated> | |
| <summary type="html"> | |
| <p>I'm working on a Tauri app that uses the imap crate to fetch emails and extract the sender information to return a <code>Vec&lt;Sender&gt;</code> where <code>Sender</code> is just a struct with a <code>name</code> and <code>email</code> attribute.</p>
<hr />
<p>When I try to iterate over the result of a fetch call, I get the following compiler error:</p>
<pre><code>error[E0275]: overflow evaluating the requirement `&amp;_: IntoIterator`
 = help: consider increasing the recursion limit by adding a `#![recursion_limit = &quot;256&quot;]` attribute to your crate (`mailmanage_lib`)
 = note: required for `&amp;ZeroCopy&lt;_&gt;` to implement `IntoIterator`
 = note: 126 redundant requirements hidden
 = note: required for `&amp;ZeroCopy&lt;ZeroCopy&lt;ZeroCopy&lt;ZeroCopy&lt;ZeroCopy&lt;...&gt;&gt;&gt;&gt;&gt;` to implement `IntoIterator`

</code></pre>
<p>The issue seems to stem from this block of code where I iterate over the result of the <code>fetch</code> method:</p>
<pre class="lang-rust prettyprint-override"><code>for msg in msgs.iter() {
 if let Some(envelop) = msg.envelope() {
 if let Some(_senders) = &amp;envelop.sender {
 for sender in _senders {
 if let (Some(mailbox), Some(host)) = (sender.mailbox, sender.host) {
 senders.push(Sender {
 name: sender.name.map(|name| String::from_utf8(name.to_owned()).expect(&quot;Name decode failed&quot;)),
 email: format!(
 &quot;{}@{}&quot;,
 String::from_utf8(mailbox.to_vec()).expect(&quot;Mailbox decode failed&quot;),
 String::from_utf8(host.to_vec()).expect(&quot;Host decode failed&quot;)
 ),
 });
 }
 }
 }
 }
}
</code></pre>
<p>The <code>fetch</code> result is returned by:</p>
<pre><code>let result = self.imap_session.fetch(seq.to_string(), &quot;ALL&quot;);
</code></pre>
<p>The type of <code>msgs</code> is <code>ZeroCopyResult&lt;VecFetch&gt;</code>. I think my problem come from how i iterate through <code>msgs</code>.</p>
<p>I've tried many possibilities like:
<code>for msg in msgs</code>,
<code>for msg in *msgs</code>,
<code>for msg in msgs.deref().iter()</code>,
<code>for msg in (*msgs).iter()</code>,
<code>for msg in (**msgs).iter()</code>,
<code>for msg in msgs.as_slice()</code></p>
<p>Full code:</p>
<pre><code>pub trait EmailProvider {
 async fn get_inbox_senders_email_list(&amp;mut self) -&gt; Vec&lt;Sender&gt;;
}

#[derive(Serialize)]
pub struct Sender {
 name: Option&lt;String&gt;,
 email: String,
}

pub struct EmailAccessProvider {
 mail_server: MailServer,
 imap_session: Session&lt;TlsStream&lt;TcpStream&gt;&gt;,
}

impl EmailProvider for EmailAccessProvider {
 async fn get_inbox_senders_email_list(&amp;mut self) -&gt; Vec&lt;Sender&gt; {
 let mut senders: Vec&lt;Sender&gt; = Vec::new();

 let search_result = match self.imap_session.search(&quot;BODY unsubscribe&quot;) {
 Ok(ids) =&gt; ids,
 Err(_) =&gt; return senders,
 };

 for seq in search_result {
 let result = self.imap_session.fetch(seq.to_string(), &quot;ALL&quot;);
 match result {
 Ok(msgs) =&gt; {
 for msg in msgs.iter() {
 if let Some(envelop) = msg.envelope() {
 if let Some(_senders) = &amp;envelop.sender {
 for sender in _senders {
 if let (Some(mailbox), Some(host)) = (sender.mailbox, sender.host) {
 senders.push(Sender {
 name: sender.name.map(|name| String::from_utf8(name.to_owned()).unwrap()),
 email: format!(
 &quot;{}@{}&quot;,
 String::from_utf8(mailbox.to_vec()).unwrap(),
 String::from_utf8(host.to_vec()).unwrap()
 ),
 });
 }
 }
 }
 }
 }
 }
 Err(_) =&gt; println!(&quot;Fetch error&quot;),
 }
 }

 senders
 }
}
</code></pre>
 | |
| </summary> | |
| </entry> | |
| <entry> | |
| <id>https://stackoverflow.com/q/71634411</id> | |
| <re:rank scheme="https://stackoverflow.com">3</re:rank> | |
| <title type="text">how to do a count query when using rust diesel</title> | |
| <category scheme="https://stackoverflow.com/tags" term="rust" /> | |
| <category scheme="https://stackoverflow.com/tags" term="rust-diesel" /> | |
| <author> | |
| <name>Dolphin</name> | |
| <uri>https://stackoverflow.com/users/2628868</uri> | |
| </author> | |
| <link rel="alternate" href="https://stackoverflow.com/questions/71634411/how-to-do-a-count-query-when-using-rust-diesel" /> | |
| <published>2022-03-27T07:25:12Z</published> | |
| <updated>2025-05-06T18:19:36Z</updated> | |
| <summary type="html"> | |
| <p>I am doing a count query using rust <code>1.59.0</code> diesel <code>diesel = { version = &quot;1.4.8&quot;, features = [&quot;postgres&quot;,&quot;64-column-tables&quot;,&quot;chrono&quot;] }</code> following this <a href="https://docs.diesel.rs/diesel/dsl/fn.count.html" rel="nofollow noreferrer">document</a>, this is my code looks like right now:</p>
<pre><code>use diesel::{ExpressionMethods, QueryDsl, QueryResult, RunQueryDsl};
use diesel::dsl::count;
use rocket::serde::json::Json;
use rust_wheel::config::db::config;

pub fn channel_fav_count(req_channel_id: &amp;i64) -&gt; i32 {
 use crate::model::diesel::dolphin::dolphin_schema::article_favorites::dsl::*;
 let connection = config::establish_connection();
 let query = article_favorites
 .filter(channel_id.eq(req_channel_id));
 let query_result = query.select(count(id)).first(&amp;connection);
 return query_result.unwrap_or(0);
}
</code></pre>
<p>when I compile the code, shows error like this:</p>
<pre><code>error[E0277]: the trait bound `i32: FromSql&lt;BigInt, Pg&gt;` is not satisfied
 --&gt; src/service/app/cruise/article/article_fav_service.rs:11:48
 |
11 | let query_result = query.select(count(id)).first(&amp;connection);
 | ^^^^^ the trait `FromSql&lt;BigInt, Pg&gt;` is not implemented for `i32`
</code></pre>
<p>why did this happen? what should I do to fix this problem?</p>
 | |
| </summary> | |
| </entry> | |
| <entry> | |
| <id>https://stackoverflow.com/q/79608879</id> | |
| <re:rank scheme="https://stackoverflow.com">1</re:rank> | |
| <title type="text">In Rust is it possible to have an allocator such that a Vec<Arc<[usize]>> stores the Arcs in contiguous memory</title> | |
| <category scheme="https://stackoverflow.com/tags" term="rust" /> | |
| <category scheme="https://stackoverflow.com/tags" term="memory" /> | |
| <category scheme="https://stackoverflow.com/tags" term="memory-management" /> | |
| <category scheme="https://stackoverflow.com/tags" term="allocation" /> | |
| <author> | |
| <name>James Trewern</name> | |
| <uri>https://stackoverflow.com/users/23135503</uri> | |
| </author> | |
| <link rel="alternate" href="https://stackoverflow.com/questions/79608879/in-rust-is-it-possible-to-have-an-allocator-such-that-a-vecarcusize-stores" /> | |
| <published>2025-05-06T14:00:49Z</published> | |
| <updated>2025-05-06T14:00:49Z</updated> | |
| <summary type="html"> | |
| <h1>Old Approach</h1>
<p>Previously my clause table was much more complicated storing the literals field of the clauses in a Vec which would then be indexed by a Range in a ClauseMetaData structure. But this made the code pretty cumbersome, and I'd really like to have an Arc storing the literals for multithreaded reading.</p>
<pre><code>enum ClauseMetaData {
 Clause((usize, usize)), // Literals range
 Meta((usize, usize), u128), // Literals range, Existential variables bitflags
}
pub struct ClauseTable {
 clauses: Vec&lt;ClauseMetaData&gt;,
 literal_addrs: Vec&lt;usize&gt;, //Heap addresses of clause literals
}
</code></pre>
<h1>New Approach</h1>
<p>I currently have these two data structures</p>
<pre><code>struct Clause{
 literals: Arc&lt;[usize]&gt;,
 meta_vars: Option&lt;u128&gt;
}

pub struct ClauseTable (Vec&lt;Clause&gt;);
</code></pre>
<p>I'm trying to focus on efficiency, and I know this memory will be accessed regularly so I want to reduce cache misses. So ideally I can write an allocator or use and existing library which makes this specific grouping of data fall in one continuous block</p>
<p>I understand this is a broad question, however resources on this seem to be sparse, the best I found so far is <a href="https://www.brochweb.com/blog/post/how-to-create-a-custom-memory-allocator-in-rust/" rel="nofollow noreferrer">How to create custom memory allocator in Rust</a>.</p>
<p>I suppose this comes down to two questions, Is what I'm attempting possible/ what resources could I use to understand better, or are there existing libraries which achieve the same thing.</p>
<h1>Additional Information</h1>
<p>The memory once allocated will only rarely be deleted so leaving gaps is fine, It feels like this should be a simple allocator to implement if I understood more</p>
<p>The majority of the [usize] arrays are going to be between 1 and 10 elements long so ideally each allocation would use the exact size of the data.</p>
 | |
| </summary> | |
| </entry> | |
| <entry> | |
| <id>https://stackoverflow.com/q/79608547</id> | |
| <re:rank scheme="https://stackoverflow.com">-1</re:rank> | |
| <title type="text">Rust fn_mut primitive type [closed]</title> | |
| <category scheme="https://stackoverflow.com/tags" term="rust" /> | |
| <author> | |
| <name>Harry</name> | |
| <uri>https://stackoverflow.com/users/3938402</uri> | |
| </author> | |
| <link rel="alternate" href="https://stackoverflow.com/questions/79608547/rust-fn-mut-primitive-type" /> | |
| <published>2025-05-06T10:56:08Z</published> | |
| <updated>2025-05-06T10:56:08Z</updated> | |
| <summary type="html"> | |
| <p>In Rust there is a primitive type called <a href="https://doc.rust-lang.org/std/primitive.fn.html" rel="nofollow noreferrer">fn</a>. Is there any primitive equivalent for <code>FnMut</code> like <code>fn_mut</code>. I'm trying to compile the below code but getting an error</p>
<pre><code>fn foo(mut a_opt: Option&lt;impl FnMut(u64)&gt;) {
 if let Some(a) = &amp;mut a_opt {
 (a)(67);
 }
}

fn main() {
 let a = |abc: u64| {
 println!(&quot;{}&quot;, abc);
 };
 
 foo(Some(a));
 foo(None::&lt;fn(0u64)&gt;);
}
</code></pre>
<p>Error</p>
<pre><code>error: expected one of `...`, `..=`, `..`, or `:`, found `)`
 --&gt; src/main.rs:13:23
 |
13 | foo(None::&lt;fn(0u64)&gt;);
 | ^ expected one of `...`, `..=`, `..`, or `:`
</code></pre>
 | |
| </summary> | |
| </entry> | |
| <entry> | |
| <id>https://stackoverflow.com/q/79607682</id> | |
| <re:rank scheme="https://stackoverflow.com">0</re:rank> | |
| <title type="text">Force "shallow equality" of a type by comparing pointers in a type's `PartialEq` instance</title> | |
| <category scheme="https://stackoverflow.com/tags" term="rust" /> | |
| <author> | |
| <name>Nicola Gigante</name> | |
| <uri>https://stackoverflow.com/users/3206471</uri> | |
| </author> | |
| <link rel="alternate" href="https://stackoverflow.com/questions/79607682/force-shallow-equality-of-a-type-by-comparing-pointers-in-a-types-partialeq" /> | |
| <published>2025-05-05T21:39:48Z</published> | |
| <updated>2025-05-06T07:49:51Z</updated> | |
| <summary type="html"> | |
| <p>Pointer types in Rust, such as <code>Box&lt;T&gt;</code>, <code>Rc&lt;T&gt;</code> and <code>Arc&lt;T&gt;</code>, implement their <code>Eq</code> and <code>Hash</code> instance in a <em>deep</em> way, i.e. they call to the respective instances of <code>T</code>. This is different from what a C/C++ programmer would expect from pointer types, which compare always shallowly in those languages.</p>
<p>In some cases one may want to still compare shallowly two pointer types. Since implementing <code>Eq</code> and <code>Hash</code> for <code>Rc&lt;MyType&gt;</code> is not possible because it would be an orphan instance, then I figured out I may do it by implement the shallow comparison and hashing in the type's instance, as follows:</p>
<pre><code>pub struct MyType {
 pub x: (),
}

impl PartialEq for MyType {
 fn eq(&amp;self, other: &amp;Self) -&gt; bool {
 std::ptr::eq(self, other)
 }
}

impl Eq for MyType {}

impl Hash for MyType {
 fn hash&lt;H: Hasher&gt;(&amp;self, state: &amp;mut H) {
 (self as *const MyType).hash(state);
 }
}
</code></pre>
<p>In this way, <code>Box&lt;MyType&gt;</code>, <code>Rc&lt;MyType&gt;</code>, and <code>Arc&lt;MyType&gt;</code> would compare shallowly (and <code>MyType</code> directly as well).</p>
<p>However, I'm quite new to Rust so I'm not sure this approach is sensible.</p>
<ol>
<li>does comparing pointers in that way do what I expect, i.e., returning <code>true</code> when and only when I compare exactly the same object?</li>
<li>is there any advice against such a practice? Does this patently violates some code quality guideline? Is this <em>&quot;wrong&quot;</em> in any concrete way?</li>
</ol>
 | |
| </summary> | |
| </entry> | |
| <entry> | |
| <id>https://stackoverflow.com/q/79607500</id> | |
| <re:rank scheme="https://stackoverflow.com">0</re:rank> | |
| <title type="text">Rust error: borrowed data escapes outside of method</title> | |
| <category scheme="https://stackoverflow.com/tags" term="rust" /> | |
| <category scheme="https://stackoverflow.com/tags" term="lifetime" /> | |
| <author> | |
| <name>Albéric</name> | |
| <uri>https://stackoverflow.com/users/30454753</uri> | |
| </author> | |
| <link rel="alternate" href="https://stackoverflow.com/questions/79607500/rust-error-borrowed-data-escapes-outside-of-method" /> | |
| <published>2025-05-05T19:10:23Z</published> | |
| <updated>2025-05-06T06:46:23Z</updated> | |
| <summary type="html"> | |
| <p>I am writing a code <a href="https://github.com/abriotde/openhems-rust" rel="nofollow noreferrer">https://github.com/abriotde/openhems-rust</a> which is an implementation in Rust of <a href="https://github.com/abriotde/openhems-sample" rel="nofollow noreferrer">https://github.com/abriotde/openhems-sample</a> (which is in Python).</p>
<pre class="lang-rust prettyprint-override"><code>struct NodesHeapIterator&lt;'b, Updater:HomeStateUpdater+Clone+'b&gt; {
 nodetype: node::NodeType,
 index:usize,
 filter: String,
 heap: &amp;'b NodesHeap&lt;'b, Updater&gt;
}

impl&lt;'a, Updater:HomeStateUpdater+Clone&gt; fmt::Debug for NodesHeap&lt;'a, Updater&gt; {
 fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result {
 let iter: NodesHeapIterator&lt;'_, Updater&gt; = self.get_all();
 for node in iter {
 let _ = write!(f, &quot;, {}&quot;, node);
 }
 Ok(())
 }
}

impl&lt;'a, Updater:HomeStateUpdater+Clone&gt; NodesHeap&lt;'a, Updater&gt; {
 pub fn get_all&lt;'b&gt;(&amp;'static self) -&gt; NodesHeapIterator&lt;'b, Updater&gt; {
 NodesHeapIterator {
 nodetype: node::NodeType::PublicPowerGrid,
 index: 0,
 filter: &quot;all&quot;.to_string(),
 heap: &amp;self,
 }
 }
}
</code></pre>
<p>give me an error:</p>
<pre class="lang-none prettyprint-override"><code>error[E0521]: borrowed data escapes outside of method
 --&gt; src/network.rs:25:46
 |
22 | impl&lt;'a, Updater:HomeStateUpdater+Clone&gt; fmt::Debug for NodesHeap&lt;'a, Updater&gt; {
 | -- lifetime `'a` defined here
23 | fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result
 | ----- `self` is a reference that is only valid in the method body
24 | {
25 | let iter: NodesHeapIterator&lt;'_, Updater&gt; = self.get_all();
 | ^^^^^^^^^^^^^^
 | |
 | `self` escapes the method body here
 | argument requires that `'a` must outlive `'static`
</code></pre>
<p>I just want to print data.</p>
 | |
| </summary> | |
| </entry> | |
| <entry> | |
| <id>https://stackoverflow.com/q/79607902</id> | |
| <re:rank scheme="https://stackoverflow.com">1</re:rank> | |
| <title type="text">Transmuting between enums containing transmutable types</title> | |
| <category scheme="https://stackoverflow.com/tags" term="rust" /> | |
| <author> | |
| <name>Nicola Gigante</name> | |
| <uri>https://stackoverflow.com/users/3206471</uri> | |
| </author> | |
| <link rel="alternate" href="https://stackoverflow.com/questions/79607902/transmuting-between-enums-containing-transmutable-types" /> | |
| <published>2025-05-06T02:53:10Z</published> | |
| <updated>2025-05-06T03:15:30Z</updated> | |
| <summary type="html"> | |
| <p>Consider these two types:</p>
<pre><code>pub struct InnerA {
 pub x: i32,
}

#[repr(transparent)]
pub struct InnerB {
 pub a: InnerA,
}
</code></pre>
<p>As far as I understood, <code>repr(transparent)</code> ensures it is safe to do <code>std::men::transmute</code> from <code>InnerA</code> to <code>InnerB</code> and <em>vice versa</em>.</p>
<p>But now consider other two types:</p>
<pre><code>pub struct OuterA {
 pub a: InnerA,
}

pub struct OuterB {
 pub b: InnerB,
}
</code></pre>
<p>Don't fix on the fact that these types have a single field. They may be more complex structs or enums, but they are equal in everything except the use of <code>InnerA</code> and <code>InnerB</code>. Is it safe to transmute between <code>OuterA</code> and <code>OuterB</code>?</p>
 | |
| </summary> | |
| </entry> | |
| <entry> | |
| <id>https://stackoverflow.com/q/69147490</id> | |
| <re:rank scheme="https://stackoverflow.com">1</re:rank> | |
| <title type="text">Making NmApi (Network Monitor API) example in rust. Compilation successful and the process executes without error but no capture file appears</title> | |
| <category scheme="https://stackoverflow.com/tags" term="c++" /> | |
| <category scheme="https://stackoverflow.com/tags" term="windows" /> | |
| <category scheme="https://stackoverflow.com/tags" term="rust" /> | |
| <author> | |
| <name>Nikolai Savulkin</name> | |
| <uri>https://stackoverflow.com/users/12255379</uri> | |
| </author> | |
| <link rel="alternate" href="https://stackoverflow.com/questions/69147490/making-nmapi-network-monitor-api-example-in-rust-compilation-successful-and-t" /> | |
| <published>2021-09-11T23:51:56Z</published> | |
| <updated>2025-05-05T20:52:28Z</updated> | |
| <summary type="html"> | |
| <p>I'm trying to use the functionality of Network Monitor 3.4 in my rust executable: In order to do so I've added the following files in following places:</p>
<p><code>NmApi.lib</code> in <code>target\\debug\\deps</code></p>
<p><code>NMAPI.dll</code> in <code>target\\debug</code></p>
<p>Then I've created some binding based on the in-app documentation like this:</p>
<pre class="lang-rust prettyprint-override"><code>// NMAPI module
use crate::shared::types::*;

#[link(name=&quot;NmApi&quot;)]
extern &quot;system&quot; {

 pub fn NmCreateCaptureFile(pFileName: LPCWSTR, ulSize: ULONG, ulFlags: ULONG, phCaptureFile: PHANDLE, pulReturnSize: PULONG) -&gt; ULONG;
 pub fn NmOpenCaptureEngine(pCaptureEngine: PHANDLE) -&gt; ULONG;
 pub fn NmConfigAdapter(hCaptureEngine: HANDLE, ulIndex: ULONG, CallbackFunction: NM_FRAME_CALLBACK,
 pCallerContext: LPVOID, CaptureCallbackExitMode: NmCaptureCallbackExitMode) -&gt; ULONG;

 pub fn NmStopCapture(pCaptureEngine: HANDLE, adapterInedx: ULONG);

 pub fn NmCloseHandle(objectHandle: HANDLE);
 pub fn NmAddFrame(hCaptureFile: HANDLE, hFrame: HANDLE) -&gt; ULONG;
 pub fn NmStartCapture(hCaptureEngine: HANDLE, ulAdapterIndex: ULONG, CaptureMode: NmAdapterCaptureMode) -&gt; ULONG;
}
</code></pre>
<pre class="lang-rust prettyprint-override"><code>// types module
pub type DWORD = u32;
pub type CHAR = u8;
pub type LONG = i32;
pub type ULONG = u32;
pub type PULONG = *mut ULONG;
pub type VOID = c_void;
pub type LPVOID = *mut VOID;
pub type LPCWSTR = *mut u16;
pub type HANDLE = *mut c_void;
pub type PHANDLE = *mut HANDLE;

#[derive(PartialEq)]
#[repr(u32)]
pub enum BOOL {
 TRUE = 1,
 FALSE = 0,
}

impl BOOL {
 const TRUE_LITERAL: &amp;'static str = &quot;true&quot;;
 const FALSE_LITERAL: &amp;'static str = &quot;false&quot;;

}

impl Debug for BOOL {
 fn fmt(&amp;self, f: &amp;mut Formatter&lt;'_&gt;) -&gt; std::fmt::Result {
 f.debug_struct(&amp;format!(&quot;BOOL {}&quot;,if *self == Self::TRUE {Self::TRUE_LITERAL} else {Self::FALSE_LITERAL}))
 .finish()
 }
}

pub type NM_FRAME_CALLBACK = Option&lt;unsafe extern &quot;system&quot; fn ( _: HANDLE, _: ULONG, _: LPVOID, _: HANDLE)&gt;;

#[repr(u32)]
pub enum NmCaptureCallbackExitMode {
 DiscardRemainFrames = 1,
 ReturnRemainFrames = 2,
}

#[repr(u32)]
pub enum NmAdapterCaptureMode {
 NmLocalOnly = 0,
 NmPromiscuous = 1,
}
</code></pre>
<p>Afterwards I attempted to replicate the example below (from in in-app documentation)</p>
<pre class="lang-cpp prettyprint-override"><code>#include &quot;Stdafx.h&quot;
#include &quot;windows.h&quot;
#include &quot;stdio.h&quot;
#include &quot;stdlib.h&quot;
#include &quot;objbase.h&quot;
#include &quot;ntddndis.h&quot;
#include &quot;NMApi.h&quot;

void __stdcall 
MyFrameIndication(HANDLE hCapEng, ULONG ulAdaptIdx, PVOID pContext, HANDLE hRawFrame)
{
 HANDLE capFile = (HANDLE)pContext;
 NmAddFrame(capFile, hRawFrame);
}

int __cdecl wmain(int argc, WCHAR* argv[])
{
 ULONG ret;
 ULONG adapterIndex = 0;

 if(2 == argc)
 adapterIndex = _wtol(argv[1]);

 // Open a capture file for saving frames.
 HANDLE myCapFile;
 ULONG CapSize;
 ret = NmCreateCaptureFile(L&quot;20sec.cap&quot;, 20000000, NmCaptureFileWrapAround, &amp;myCapFile, &amp;CapSize);
 if(ret != ERROR_SUCCESS)
 {
 wprintf(L&quot;Error opening capture file, 0x%X\n&quot;, ret);
 return ret;
 }

 // Open the capture engine.
 HANDLE myCaptureEngine;
 ret = NmOpenCaptureEngine(&amp;myCaptureEngine);
 if(ret != ERROR_SUCCESS)
 {
 wprintf(L&quot;Error opening capture engine, 0x%X\n&quot;, ret);
 NmCloseHandle(myCapFile);
 return ret;
 }

 //Configure the adapter.
 ret = NmConfigAdapter(myCaptureEngine, adapterIndex, MyFrameIndication, myCapFile);
 if(ret != ERROR_SUCCESS)
 {
 wprintf(L&quot;Error configuration adapter, 0x%X\n&quot;, ret);
 NmCloseHandle(myCaptureEngine);
 NmCloseHandle(myCapFile);
 return ret;
 }

 //Start capturing frames.
 wprintf(L&quot;Capturing for 20 seconds\n&quot;);
 NmStartCapture(myCaptureEngine, adapterIndex, NmLocalOnly);

 Sleep(20000);

 wprintf(L&quot;Stopping capture\n&quot;);
 NmStopCapture(myCaptureEngine, adapterIndex);

 NmCloseHandle(myCaptureEngine);
 NmCloseHandle(myCapFile);

 return 0;
}
</code></pre>
<p>With this implementation:</p>
<pre class="lang-rust prettyprint-override"><code>pub unsafe extern &quot;system&quot; fn _MyFrameIndication(hCaptureEngine: HANDLE, adapterIndex: ULONG, pContext: LPVOID, hRawFrame: HANDLE) {
 let hCapFile: HANDLE = pContext as HANDLE;
 let ret = unsafe { NmAddFrame(hCapFile, hRawFrame) };
 println!(&quot;capturing frame: got code {}&quot;,ret);
}

pub const MyFrameIndication: NM_FRAME_CALLBACK = Some(_MyFrameIndication);


fn main () {

 let mut myCapFile: HANDLE = unsafe { zeroed() };
 let mut CapSize: ULONG = unsafe { zeroed() };
 let mut pname: Vec&lt;u16&gt; = OsStr::new(&quot;20sec.cap&quot;).encode_wide().chain(once(0)).collect();
 unsafe {
 println!(&quot;opening capture file: code is {}&quot;,NmCreateCaptureFile(pname.as_mut_ptr(),
 2000, 0,
 &amp;mut myCapFile as PHANDLE,
 &amp;mut CapSize));
 };

 let mut myCaptureEngine: HANDLE = unsafe { zeroed() };
 let ret = unsafe { NmOpenCaptureEngine(&amp;mut myCaptureEngine) };
 println!(&quot;acquiring capture engine: code is {}&quot;, ret);

 let ret = unsafe { NmConfigAdapter(myCaptureEngine,
 0, MyFrameIndication,
 myCapFile,
 NmCaptureCallbackExitMode::DiscardRemainFrames) };

 println!(&quot;configuring adapter: code is {}&quot;, ret);

 let ret = unsafe {NmStartCapture(myCaptureEngine, 0, NmAdapterCaptureMode::NmLocalOnly)};
 println!(&quot;starting capture: code is {}&quot;,ret);

 let before = SystemTime::now();

 while (SystemTime::now().duration_since(before).unwrap().as_secs() &lt; 25) {
 }

 println!(&quot;stopping capture&quot;);
 unsafe {
 NmStopCapture(myCaptureEngine, 0)
 };

 println!(&quot;releasing handles&quot;);
 unsafe {
 NmCloseHandle(myCaptureEngine);
 NmCloseHandle(myCapFile);
 }
}
</code></pre>
<p>Afterwards I built the binary without any error, and launched it:
the console window appeared and the output of all codes was 0 which is the value of <code>ERROR_SUCCESS</code> implying that the functions were called correctly.</p>
<p>However no file appeared anywhere in the working directory.
Furthermore - nothing was printed from within the callback function.</p>
<p>Can anyone help me with this? was on it for some time and not even sure how to debug it.</p>
<p>PS: I tried placing the <code>.lib</code> and <code>.dll</code> files in the cwd of resulting <code>.exe</code> as well - but that didn't change anything.</p>
<p><strong>Update</strong></p>
<p>I've tried creating new project and included the following config file in the <code>.cargo</code> subdirectory:</p>
<pre class="lang-ini prettyprint-override"><code>
[target.x86_64-pc-windows-msvc]
rustflags = [&quot;-C&quot;, &quot;target-feature=+crt-static&quot;]
rustc-link-lib = {name=&quot;NmApi&quot;}
rustc-link-search = {path=&quot;C:\\Users\\grass\\Desktop\\codes\\Rust\\cpp_xport\\res&quot;}
</code></pre>
<p>where the target if my default. Didn't change anything sadly</p>
 | |
| </summary> | |
| </entry> | |
| <entry> | |
| <id>https://stackoverflow.com/q/79440250</id> | |
| <re:rank scheme="https://stackoverflow.com">0</re:rank> | |
| <title type="text">Why does my Rust build takes so much time?</title> | |
| <category scheme="https://stackoverflow.com/tags" term="rust" /> | |
| <category scheme="https://stackoverflow.com/tags" term="compilation" /> | |
| <category scheme="https://stackoverflow.com/tags" term="compiler-optimization" /> | |
| <category scheme="https://stackoverflow.com/tags" term="rust-cargo" /> | |
| <author> | |
| <name>Gigin Parseh</name> | |
| <uri>https://stackoverflow.com/users/26776210</uri> | |
| </author> | |
| <link rel="alternate" href="https://stackoverflow.com/questions/79440250/why-does-my-rust-build-takes-so-much-time" /> | |
| <published>2025-02-14T18:22:12Z</published> | |
| <updated>2025-05-05T19:28:20Z</updated> | |
| <summary type="html"> | |
| <p>I LITERALLY tried everything, when I do <code>cargo clean</code> and then <code>cargo build</code> , it takes almost 10 minutes to build because of <code>rocksdb</code> , below is my <code>Cargo.toml</code> file, I have only 2 or 3 files of code which are only around 50 line each. I have MacBook Pro 2017, corei17, 16gb ram and have 150gb free storage.</p>
<p>I installed rocksdb as <code>brew install rocksdb</code> and installed <code>ccache</code> but still takes THIS much to build.</p>
<pre><code>[package]
name = &quot;hgdb_core&quot;
version = &quot;0.1.0&quot;
edition = &quot;2021&quot;

[[test]]
name = &quot;db_config_test&quot;
path = &quot;tests/db_config_test.rs&quot;

[[test]]
name = &quot;simple_h_edge_test&quot;
path = &quot;tests/simple_h_edge_test.rs&quot;

[profile.dev]
incremental = true

[profile.release]
incremental = true
debug = false
opt-level = 3

[dependencies]
bincode = &quot;1.3.3&quot;
quote = &quot;1.0.38&quot;
serde = { version = &quot;1.0&quot;, features = [&quot;derive&quot;] }
serde_json = &quot;1.0&quot;
rocksdb = &quot;0.23.0&quot;
</code></pre>
<p><a href="https://i.sstatic.net/f5VE8Hq6.jpg" rel="nofollow noreferrer">Activity Monitor</a></p>
<p>VSCODE terminal:</p>
<pre><code>✗ cargo build --release
 Compiling librocksdb-sys v0.17.1+9.9.3
 Compiling rocksdb v0.23.0
 Compiling hgdb_core v0.1.0 (/Users/gigin/Documents/GitHub/HG-db/hgdb_core)
 Finished `release` profile [optimized] target(s) in 9m 41s

HG-db/hgdb_core on  main is 📦 v0.1.0 via 🦀 vv1.84.1 took 9m42s 
</code></pre>
<p>When I run cargo <code>build --timings</code> it hangs on <code>librocksdb-sys(build)</code>.</p>
 | |
| </summary> | |
| </entry> | |
| <entry> | |
| <id>https://stackoverflow.com/q/79607457</id> | |
| <re:rank scheme="https://stackoverflow.com">0</re:rank> | |
| <title type="text">In Rust, is there a consensus of the style of `TBuilder::new()` vs `T::builder()`? [closed]</title> | |
| <category scheme="https://stackoverflow.com/tags" term="rust" /> | |
| <category scheme="https://stackoverflow.com/tags" term="conventions" /> | |
| <author> | |
| <name>Thomas</name> | |
| <uri>https://stackoverflow.com/users/115355</uri> | |
| </author> | |
| <link rel="alternate" href="https://stackoverflow.com/questions/79607457/in-rust-is-there-a-consensus-of-the-style-of-tbuildernew-vs-tbuilder" /> | |
| <published>2025-05-05T18:37:22Z</published> | |
| <updated>2025-05-05T18:37:22Z</updated> | |
| <summary type="html"> | |
| <p>In my opinion <code>T::builder() -&gt; TBuilder</code> seems better than <code>TBuilder::new()</code>, since users will only need to <code>use</code> a single symbol instead of (potentially) both <code>T</code> and <code>TBuilder</code>.</p>
<p>But my opinion is not all that matters. I want to write &quot;unsurprising&quot; maintainable code. Idiomatic, if you will.</p>
<p>More full examples:</p>
<h2>Option 1: <code>T::builder()</code></h2>
<pre><code>struct T {
 …
}
impl T {
 pub fn builder() -&gt; TBuilder {
 TBuilder {}
 }
}
struct TBuilder {
 …
}
impl TBuilder {
 pub fn build(self) -&gt; T {
 T {}
 }
}
</code></pre>
<h2>Option 2: <code>TBuilder::new()</code></h2>
<pre><code>struct T {
 …
}
struct TBuilder {
 …
}
impl TBuilder {
 pub fn new() -&gt; TBuilder {
 TBuilder {}
 }
 pub fn build(self) -&gt; T {
 T {}
 }
}
</code></pre>
 | |
| </summary> | |
| </entry> | |
| </feed> | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment