Skip to content

cannot implement Hash except by IterBytes ? #9075

Closed
@pnkfelix

Description

@pnkfelix

A strange problem: Let's say I want to implement the Hash trait myself, making use of the hash functions of my substructure, instead of by defining/deriving IterBytes.

rustc rejects my attempts to do so, saying that it failed to find an implementation of IterBytes for the structure in question.

Just to double-check my work, I cut-and-pasted a renamed version of the Hash trait into my code, and checked that I could indeed implement that (which I can):

Test case:

enum AB<A,B> { Lft(A), Rgt(B) }

pub trait Hash2 {
    fn hash_keyed(&self, k0: u64, k1: u64) -> u64;

    #[inline]
    fn hash(&self) -> u64 { self.hash_keyed(0,0) }
}

#[cfg(not(workaround))]
impl<A:Hash, B:Hash> Hash for AB<A,B> {
    fn hash_keyed(&self, k0: u64, k1: u64) -> u64 {
        match self {
            &Lft(ref a) => a.hash_keyed(k0, k1),
            &Rgt(ref b) => b.hash_keyed(k0, k1),
        }
    }
}

#[cfg(workaround)]
impl<A:Hash2, B:Hash2> Hash2 for AB<A,B> {
    fn hash_keyed(&self, k0: u64, k1: u64) -> u64 {
        match self {
            &Lft(ref a) => a.hash_keyed(k0, k1),
            &Rgt(ref b) => b.hash_keyed(k0, k1),
        }
    }
}

fn main() {

}

Transcript:

% rustc --version
/Users/pnkfelix/opt/rust-dbg/bin/rustc 0.8-pre (dd5c737 2013-09-08 12:05:55 -0700)
host: x86_64-apple-darwin
% rustc --cfg workaround /tmp/foo.rs
warning: no debug symbols in executable (-arch x86_64)
% rustc /tmp/foo.rs
/tmp/foo.rs:11:0: 18:1 error: failed to find an implementation of trait std::to_bytes::IterBytes for AB<A,B>
/tmp/foo.rs:11 impl<A:Hash, B:Hash> Hash for AB<A,B> {
/tmp/foo.rs:12     fn hash_keyed(&self, k0: u64, k1: u64) -> u64 {
/tmp/foo.rs:13         match self {
/tmp/foo.rs:14             &Lft(ref a) => a.hash_keyed(k0, k1),
/tmp/foo.rs:15             &Rgt(ref b) => b.hash_keyed(k0, k1),
/tmp/foo.rs:16         }
               ...
% 

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-trait-systemArea: Trait systemA-type-systemArea: Type systemC-enhancementCategory: An issue proposing an enhancement or a PR with one.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions