These are chat archives for rust-lang/rust

4th
May 2018
Kelly Thomas Kline
@kellytk
May 04 2018 00:45
Is it possible to, using a Cargo file key or otherwise, configure a project to refuse to build if the project or any of its dependencies use unsafe?
Zack Pierce
@ZackPierce
May 04 2018 01:00
That sounds technically do-able with a build script @kellytk
Kelly Thomas Kline
@kellytk
May 04 2018 01:01
Thanks @ZackPierce
Zack Pierce
@ZackPierce
May 04 2018 01:01
There are a number of tools out there to find unsafe code, but I don't know how amenable they are to use as libraries
That said, you may soon find yourself making exceptions -- e.g. for the standard or core library
Kelly Thomas Kline
@kellytk
May 04 2018 01:05
If it's in core/std, I'd trust it, but if it's in a crate I'd at least look for a viable alternative
VJ
@00imvj00
May 04 2018 04:47
pub struct SyncDecoder<T> {
    phantom: PhantomData<T>,
}
 pub fn mqtt_string_from_slice(b: &[u8]) -> Result<String> {
        if b.len() < 2 {
            return Err(Error::PayloadRequired);
        }

        let len: usize = (((0 as u16 | b[1] as u16) << 8) | b[0] as u16) as usize;
        let mut data = Vec::with_capacity(len);
        data.extend_from_slice(&b[2..len]);

        Ok(String::from_utf8(data).unwrap())
    }

while calling

  let protocol_name: String = SyncDecoder::mqtt_string_from_slice(&b).unwrap();

Getting following compile time error

error[E0282]: type annotations needed
  --> src/packet.rs:40:37
   |
40 |         let protocol_name: String = SyncDecoder::mqtt_string_from_slice(&b).unwrap();
   |                                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot infer type for `T`

error: aborting due to previous error
VJ
@00imvj00
May 04 2018 05:10
^^ I think i got the issue. bottom line is, for empty struct, don't make is work with generics, instead us function level generics.
ha ha
VJ
@00imvj00
May 04 2018 05:39
@all rustup is giving following error while updating. could not download file from 'https://static.rust-lang.org/dist/channel-rust-stable.toml.sha256'
Dylan DPC
@Dylan-DPC
May 04 2018 06:47
@00imvj00 why do you need generics in this case? since none of your params or return type or struct properties are generic (phantom is, but you don't need it
please do not use @all @00imvj00
VJ
@00imvj00
May 04 2018 06:53
Sorry for that @Dylan-DPC
Andy Grove
@andygrove
May 04 2018 09:15
Hi. I wonder if someone can help me with generics. This is what I am trying to do:
impl<T> BufferArrayData<T> where T: PrimitiveType + Add {

    pub fn add(&self, other: &BufferArrayData<T>) {
        let mut builder: Builder<T> = Builder::new();
        for i in 0..self.len {
            builder.push(self.data.get(i) + other.data.get(i));
        }
        BufferArrayData::from(builder.finish())
    }
}
However, this doesn't work because Builder<T> is only implemented for T: Primitive not T: Primitive + Add
I think I need a second generic type here but haven't been able to figure out how
Andy Grove
@andygrove
May 04 2018 09:23
I also tried
impl<T> BufferArrayData<T> where T: PrimitiveType + Add {

    pub fn add<U: PrimitiveType>(&self, other: &BufferArrayData<T>) -> BufferArrayData<U> {
        let mut builder: Builder<U> = Builder::new();
        for i in 0..self.len {
            builder.push(self.data.get(i) + other.data.get(i));
        }
        BufferArrayData::from(builder.finish())
    }
}
but this fails with
41 |             builder.push(self.data.get(i) + other.data.get(i));
   |                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected type parameter, found associated type
   |
   = note: expected type `U`
              found type `<T as std::ops::Add>::Output`
Here's a playground version
Sergey Noskov
@Albibek
May 04 2018 10:00
@andygrove You need to specify Add's Output type explicitly in impl: + Add<Output=T>
Andy Grove
@andygrove
May 04 2018 10:04
@Albibek Thanks! I just recently got the same answer on Rust IRC.
tain335
@tain335
May 04 2018 11:02
how install rls@0.127.0? I can't install this version
Do Duy
@juchiast
May 04 2018 12:50
I see that std::net::TcpStream::try_clone return a Result, which means it could fail. So, I read the source to see what makes it fail.
The function call sys::net::Socket::duplicate, which calls sys::fd::FileDesc::duplicate, which calls fcntlF_DUPFD (and something to do with cloexec).
My questions are: Is it necessary to call fcntl to clone a socket? Can't we just copy the value? What could go wrong?
Note: I'm on linux, and only care about recent versions of linux kernel
James McCoy
@jamessan
May 04 2018 13:55
A file descriptor in Linux is just an int. You need to perform a dup, either with fcntl or dup, to ensure that the kernel-side tracking knows there's another copy of it. Doing the equivalent of int newfd = fd; isn't going to work.
Do Duy
@juchiast
May 04 2018 14:08
https://stackoverflow.com/questions/38298279/why-cant-we-copy-file-descriptors-just-by-plainly-assigning-the-value-to-new-va i've just come across this answer in stackoverflow. I'm new to system programming so it is a bit confusing :smile:
sitty
@sitty
May 04 2018 15:20

How can I fix this code

pub fn square_of_sum(n: usize) -> usize {
    (1..n+1).sum().pow(2)
}

I get this error

error[E0619]: the type of this value must be known in this context
 --> src\lib.rs:3:5
  |
3 |     (1..n+1).sum().pow(2)
  |     ^^^^^^^^^^^^^^

error: aborting due to previous error
Guillaume P.
@TeXitoi
May 04 2018 15:22
@sitty
pub fn square_of_sum(n: usize) -> usize {
    (1..n+1).sum::<usize>().pow(2)
}
sitty
@sitty
May 04 2018 15:23
@TeXitoi thanks!!
Paul Reesman
@reesmanp
May 04 2018 17:55
users.rust-lang.org seems to be down (or at least serving no content) in case anyone can doing anything about it
Dylan DPC
@Dylan-DPC
May 04 2018 18:16
works well for me @reesmanp
Maciej Gorywoda
@makingthematrix
May 04 2018 22:34

Hi all,
Let's say I have something like this:

let vec: Vec<Option<i32>> = vec![None, None, Some(2), None, Some(4), Some(5)];
let mut iter = vec.iter().enumerate().filter_map( |(i, &v)| if v.is_some() { Some(i, v.unwrap()) } else { None });

Consecutive iter.next() will return Some((2,2)), Some((4,4)), ann Some((5,5)). All good.
But I want to to create fn iter() which will return this iter. vec is a field of a struct for which I will implement the iter(). What should be its signature? IntelliJ hints some black magic: FilterMap<Enumerate<Iter<_>, fn((usize, _)) -> Option(usize, &T)>>. When I use it as the return type, it doesn't work anyway :)

Basically, I'd like to create create a struct which will encapsulate that vec, an accompanying iterator.
If you had a link to an article about iterators, that would help me too. I think I will have more problems like this in the future ;)
Ravi Shankar
@wafflespeanut
May 04 2018 22:56
Usually, any iterable (vec, slice, Hashmat, etc.) is associated with an iterator implementor which takes a reference to the iterable and lives as long as that reference
Take a look at the iterator for VecDeque - https://doc.rust-lang.org/src/alloc/vec_deque.rs.html#1909-1913
When you call “iter” method on the VecDeque, it creates this struct which holds a reference to the underlying slice
The returned struct implements the iterator
Oh wait, actually I misread this.
Ravi Shankar
@wafflespeanut
May 04 2018 23:02
If you wanna hold this exact iterator, then you can cast it to a Box<Iterator<Item=(usize,usize)>>>
Box::new(iter) as [above]
Maciej Gorywoda
@makingthematrix
May 04 2018 23:48
no, I don't need to hold that exact iterator. In fact, I tried first something similar to what you wrote, but then I ran into some complexities and tried another way.
thanks, I'll try both.