1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
use std::io;

use dbn::{
    decode::{DbnRecordDecoder, DecodeDbn, DecodeRecordRef, DynDecoder},
    encode::{
        json, DbnEncodable, DbnRecordEncoder, DynEncoder, DynWriter, EncodeDbn, EncodeRecordRef,
    },
    rtype_dispatch, Compression, Encoding, MetadataBuilder, SType,
};

use crate::{infer_encoding_and_compression, output_from_args, Args};

pub fn encode_from_dbn<R: io::BufRead>(decoder: DynDecoder<R>, args: &Args) -> anyhow::Result<()> {
    let writer = output_from_args(args)?;
    let (encoding, compression) = infer_encoding_and_compression(args)?;
    let encode_res = if args.should_output_metadata {
        assert!(args.json);
        json::Encoder::new(
            writer,
            args.should_pretty_print,
            args.should_pretty_print,
            args.should_pretty_print,
        )
        .encode_metadata(decoder.metadata())
    } else if args.fragment {
        encode_fragment(decoder, writer, compression, args)
    } else if let Some(limit) = args.limit {
        let mut metadata = decoder.metadata().clone();
        // Update metadata
        metadata.limit = args.limit;
        DynEncoder::new(
            writer,
            encoding,
            compression,
            &metadata,
            args.should_pretty_print,
            args.should_pretty_print,
            args.should_pretty_print,
        )?
        .encode_decoded_with_limit(decoder, limit)
    } else {
        DynEncoder::new(
            writer,
            encoding,
            compression,
            decoder.metadata(),
            args.should_pretty_print,
            args.should_pretty_print,
            args.should_pretty_print,
        )?
        .encode_decoded(decoder)
    };
    match encode_res {
        // Handle broken pipe as a non-error.
        Err(dbn::Error::Io { source, .. }) if source.kind() == std::io::ErrorKind::BrokenPipe => {
            Ok(())
        }
        res => Ok(res?),
    }
}

pub fn encode_from_frag<R: io::Read>(
    mut decoder: DbnRecordDecoder<R>,
    args: &Args,
) -> anyhow::Result<()> {
    let writer = output_from_args(args)?;
    let (encoding, compression) = infer_encoding_and_compression(args)?;
    if args.fragment {
        encode_fragment(decoder, writer, compression, args)?;
        return Ok(());
    }
    assert!(!args.should_output_metadata);

    let mut encoder = DynEncoder::new(
        writer,
        encoding,
        compression,
        // dummy metadata won't be encoded
        &MetadataBuilder::new()
            .dataset(String::new())
            .schema(None)
            .start(0)
            .stype_in(None)
            .stype_out(SType::InstrumentId)
            .build(),
        args.should_pretty_print,
        args.should_pretty_print,
        args.should_pretty_print,
    )?;
    let mut n = 0;
    let mut has_written_header = encoding != Encoding::Csv;
    fn write_header<T: DbnEncodable>(
        _record: &T,
        encoder: &mut DynEncoder<Box<dyn io::Write>>,
    ) -> dbn::Result<()> {
        encoder.encode_header::<T>(false)
    }
    while let Some(record) = decoder.decode_record_ref()? {
        if !has_written_header {
            match rtype_dispatch!(record, write_header, &mut encoder)? {
                Err(dbn::Error::Io { source, .. })
                    if source.kind() == io::ErrorKind::BrokenPipe =>
                {
                    return Ok(())
                }
                res => res?,
            }
            has_written_header = true;
        }
        // Assume no ts_out for safety
        match encoder.encode_record_ref(record) {
            // Handle broken pipe as a non-error.
            Err(dbn::Error::Io { source, .. }) if source.kind() == io::ErrorKind::BrokenPipe => {
                return Ok(());
            }
            res => res?,
        };
        n += 1;
        if args.limit.map_or(false, |l| n >= l.get()) {
            break;
        }
    }
    Ok(())
}

fn encode_fragment<D: DecodeRecordRef>(
    mut decoder: D,
    writer: Box<dyn io::Write>,
    compression: Compression,
    args: &Args,
) -> dbn::Result<()> {
    let mut encoder = DbnRecordEncoder::new(DynWriter::new(writer, compression)?);
    let mut n = 0;
    while let Some(record) = decoder.decode_record_ref()? {
        encoder.encode_record_ref(record)?;
        n += 1;
        if args.limit.map_or(false, |l| n >= l.get()) {
            break;
        }
    }
    Ok(())
}