Skip to content

Writing custom types with write_record and AsRef<[u8]> implementation not possible? #318

Description

@stevenliebregt

What version of the csv crate are you using?

1.2.1

Briefly describe the question, bug or feature request.

I'm trying to use write_record with an array of enum instances that have an inner value. I'm running into the problem that those enums can not implement AsRef<[u8]> because they can have integers as well.

Include a complete program demonstrating a problem.

For example:

pub enum TagValue {
    String(String),
    Boolean(bool),
    Integer(i128),
    Empty
}

impl AsRef<[u8]> for TagValue {
    fn as_ref(&self) -> &[u8] {
        match self {
            // String works
            TagValue::String(value) => value.as_ref(),
            // But I have no idea how to do the other types,
            // int for example `to_be_bytes()` doesn't work because I can't return references
            // to the result of that since it's owned by this function
            _ => todo!()
        }
    }
}

// The calling code

let output_file = File::create(&self.output_path).unwrap(); 
let writer = BufWriter::new(output_file);
let gzip_encoder = GzEncoder::new(writer, Compression::default());

let mut tsv_writer = csv::WriterBuilder::new()
    .delimiter(TSV_DELIMITER)
    .from_writer(gzip_encoder);

let tags = vec![TagValue::String("test".into()), TagValue::Integer(1234), TagValue::Boolean(true), TagValue::Empty];

tsv_writer.write_record(tags).unwrap();

What is the observed behavior of the code above?

Returns a value referencing data owned by this function in the AsRef<[u8]> implementation.

What is the expected or desired behavior of the code above?

I hoped I could return a reference to the byte representations of those values.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions