rust-igraph 0.6.0

Pure-Rust, high-performance graph & network analysis library — 1200+ APIs, zero unsafe, igraph-compatible
Documentation
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
//! UCINET DL format reader and writer (ALGO-IO-009 / IO-013).
//!
//! Reads and writes graphs in the DL format used by UCINET. Three data
//! representations are supported for reading:
//!
//! - **fullmatrix**: adjacency matrix of 0/1 values
//! - **edgelist1**: pairs of 1-based vertex IDs with optional weights
//! - **nodelist1**: source vertex followed by its neighbors (1-based)
//!
//! Writing always uses **edgelist1** format.
//!
//! ```text
//! DL n=5
//! format = edgelist1
//! data:
//! 1 2
//! 1 3
//! 2 3
//! ```
//!
//! Vertex labels can be provided via `labels:` or `labels embedded:`.
//!
//! Counterpart of `igraph_read_graph_dl` / `igraph_write_graph_dl`.

use std::io::{BufRead, BufReader, Read, Write};

use crate::core::attributes::AttributeValue;
use crate::core::{Graph, IgraphError, IgraphResult};

/// Result of reading a DL file.
#[derive(Debug, Clone)]
pub struct DlGraph {
    /// The parsed graph.
    pub graph: Graph,
    /// Vertex labels (if provided).
    pub labels: Option<Vec<String>>,
    /// Edge weights (if provided, only for edgelist1 format).
    pub weights: Option<Vec<f64>>,
}

#[derive(Debug, Clone, Copy, PartialEq)]
enum DlFormat {
    FullMatrix,
    EdgeList1,
    NodeList1,
}

/// Read a graph from UCINET DL format.
///
/// Supports fullmatrix, edgelist1, and nodelist1 data formats.
/// Case-insensitive keywords. Vertex IDs in edgelist1 and nodelist1
/// are 1-based.
///
/// # Examples
///
/// ```
/// use rust_igraph::read_dl;
///
/// let input = b"DL n=3\nformat = edgelist1\ndata:\n1 2\n2 3\n1 3\n";
/// let result = read_dl(&input[..], true).unwrap();
/// assert_eq!(result.graph.vcount(), 3);
/// assert_eq!(result.graph.ecount(), 3);
/// ```
#[allow(clippy::too_many_lines)]
pub fn read_dl<R: Read>(input: R, directed: bool) -> IgraphResult<DlGraph> {
    let reader = BufReader::new(input);
    let mut lines: Vec<String> = Vec::new();

    for line_result in reader.lines() {
        let line = line_result?;
        lines.push(line);
    }

    let mut pos = 0;
    let mut n_vertices: Option<u32> = None;
    let mut format = DlFormat::FullMatrix;
    let mut labels: Vec<String> = Vec::new();
    let mut labels_embedded = false;

    // Parse header: DL n=N
    pos = skip_empty(&lines, pos);
    if pos >= lines.len() {
        return Err(parse_err(0, "empty DL file"));
    }

    let header_line = lines[pos].trim().to_ascii_lowercase();
    if !header_line.starts_with("dl") {
        return Err(parse_err(pos + 1, "DL file must start with 'DL'"));
    }

    // Extract n= from header line or subsequent lines
    let header_rest = &lines[pos].trim()[2..];
    if let Some(n) = extract_n(header_rest) {
        n_vertices = Some(n);
    }
    pos += 1;

    // Parse directives until DATA:
    loop {
        pos = skip_empty(&lines, pos);
        if pos >= lines.len() {
            break;
        }

        let trimmed = lines[pos].trim();
        let lower = trimmed.to_ascii_lowercase();

        if lower.starts_with("data:") || lower == "data" {
            pos += 1;
            break;
        }

        if lower.starts_with("n=") || lower.starts_with("n =") {
            if n_vertices.is_none() {
                let val =
                    extract_n(trimmed).ok_or_else(|| parse_err(pos + 1, "invalid n= value"))?;
                n_vertices = Some(val);
            }
            pos += 1;
            continue;
        }

        if lower.starts_with("format") {
            if lower.contains("fullmatrix") || lower.contains("full matrix") {
                format = DlFormat::FullMatrix;
            } else if lower.contains("edgelist1")
                || lower.contains("edge list1")
                || lower.contains("edgelist 1")
            {
                format = DlFormat::EdgeList1;
            } else if lower.contains("nodelist1")
                || lower.contains("node list1")
                || lower.contains("nodelist 1")
            {
                format = DlFormat::NodeList1;
            }
            pos += 1;
            continue;
        }

        if lower.starts_with("labels embedded") {
            labels_embedded = true;
            pos += 1;
            continue;
        }

        if lower.starts_with("labels:") || lower == "labels" {
            pos += 1;
            // Read label lines until next keyword or data:
            while pos < lines.len() {
                let lbl_line = lines[pos].trim();
                let lbl_lower = lbl_line.to_ascii_lowercase();
                if lbl_lower.starts_with("data")
                    || lbl_lower.starts_with("format")
                    || lbl_lower.starts_with("labels")
                {
                    break;
                }
                if !lbl_line.is_empty() {
                    // Labels can be comma or whitespace separated on one line
                    for token in split_labels(lbl_line) {
                        labels.push(token);
                    }
                }
                pos += 1;
            }
            continue;
        }

        // Try to extract n= from lines like "N = 5"
        if let Some(n) = extract_n(trimmed) {
            if n_vertices.is_none() {
                n_vertices = Some(n);
            }
            pos += 1;
            continue;
        }

        pos += 1;
    }

    let n = n_vertices.ok_or_else(|| parse_err(0, "no vertex count (n=) found in DL file"))?;

    let mut edges: Vec<(u32, u32)> = Vec::new();
    let mut weights: Vec<f64> = Vec::new();
    let mut has_weights = false;

    match format {
        DlFormat::FullMatrix => {
            if labels_embedded {
                // First row is label row, then labeled rows
                pos = skip_empty(&lines, pos);
                if pos < lines.len() {
                    let header_labels = split_labels(lines[pos].trim());
                    if labels.is_empty() {
                        labels = header_labels;
                    }
                    pos += 1;
                }
                let mut row = 0u32;
                while pos < lines.len() && row < n {
                    let trimmed = lines[pos].trim();
                    if trimmed.is_empty() {
                        pos += 1;
                        continue;
                    }
                    let tokens: Vec<&str> = trimmed.split_whitespace().collect();
                    if tokens.is_empty() {
                        pos += 1;
                        continue;
                    }
                    // First token is the row label (skip), rest are 0/1
                    let data_start = 1;
                    for (col, &val) in tokens.iter().skip(data_start).enumerate() {
                        if val == "1" {
                            #[allow(clippy::cast_possible_truncation)]
                            edges.push((row, col as u32));
                        }
                    }
                    row += 1;
                    pos += 1;
                }
            } else {
                let mut row = 0u32;
                while pos < lines.len() && row < n {
                    let trimmed = lines[pos].trim();
                    if trimmed.is_empty() {
                        pos += 1;
                        continue;
                    }
                    for (col, ch) in trimmed.split_whitespace().enumerate() {
                        if ch == "1" {
                            #[allow(clippy::cast_possible_truncation)]
                            edges.push((row, col as u32));
                        }
                    }
                    row += 1;
                    pos += 1;
                }
            }
        }
        DlFormat::EdgeList1 => {
            if labels_embedded {
                while pos < lines.len() {
                    let trimmed = lines[pos].trim();
                    if trimmed.is_empty() {
                        pos += 1;
                        continue;
                    }
                    let tokens: Vec<&str> = trimmed.split_whitespace().collect();
                    if tokens.len() < 2 {
                        pos += 1;
                        continue;
                    }
                    let from_label = tokens[0].to_string();
                    let to_label = tokens[1].to_string();
                    let from_id = get_or_add_label(&mut labels, &from_label);
                    let to_id = get_or_add_label(&mut labels, &to_label);
                    edges.push((from_id, to_id));
                    if tokens.len() >= 3 {
                        if let Ok(w) = tokens[2].parse::<f64>() {
                            has_weights = true;
                            weights.push(w);
                        } else {
                            weights.push(0.0);
                        }
                    } else {
                        weights.push(0.0);
                    }
                    pos += 1;
                }
            } else {
                while pos < lines.len() {
                    let trimmed = lines[pos].trim();
                    if trimmed.is_empty() {
                        pos += 1;
                        continue;
                    }
                    let tokens: Vec<&str> = trimmed.split_whitespace().collect();
                    if tokens.len() < 2 {
                        pos += 1;
                        continue;
                    }
                    let from: u32 = tokens[0]
                        .parse()
                        .map_err(|e| parse_err(pos + 1, &format!("invalid source id: {e}")))?;
                    let to: u32 = tokens[1]
                        .parse()
                        .map_err(|e| parse_err(pos + 1, &format!("invalid target id: {e}")))?;
                    if from == 0 || to == 0 || from > n || to > n {
                        return Err(parse_err(
                            pos + 1,
                            &format!("vertex ID out of range: {from} {to} (n={n})"),
                        ));
                    }
                    edges.push((from - 1, to - 1));
                    if tokens.len() >= 3 {
                        if let Ok(w) = tokens[2].parse::<f64>() {
                            has_weights = true;
                            weights.push(w);
                        } else {
                            weights.push(0.0);
                        }
                    } else {
                        weights.push(0.0);
                    }
                    pos += 1;
                }
            }
        }
        DlFormat::NodeList1 => {
            if labels_embedded {
                while pos < lines.len() {
                    let trimmed = lines[pos].trim();
                    if trimmed.is_empty() {
                        pos += 1;
                        continue;
                    }
                    let tokens: Vec<&str> = trimmed.split_whitespace().collect();
                    if tokens.is_empty() {
                        pos += 1;
                        continue;
                    }
                    let from_label = tokens[0].to_string();
                    let from_id = get_or_add_label(&mut labels, &from_label);
                    for &tok in &tokens[1..] {
                        let to_label = tok.to_string();
                        let to_id = get_or_add_label(&mut labels, &to_label);
                        edges.push((from_id, to_id));
                    }
                    pos += 1;
                }
            } else {
                while pos < lines.len() {
                    let trimmed = lines[pos].trim();
                    if trimmed.is_empty() {
                        pos += 1;
                        continue;
                    }
                    let tokens: Vec<&str> = trimmed.split_whitespace().collect();
                    if tokens.is_empty() {
                        pos += 1;
                        continue;
                    }
                    let from: u32 = tokens[0]
                        .parse()
                        .map_err(|e| parse_err(pos + 1, &format!("invalid source id: {e}")))?;
                    if from == 0 || from > n {
                        return Err(parse_err(
                            pos + 1,
                            &format!("source vertex ID out of range: {from} (n={n})"),
                        ));
                    }
                    for &tok in &tokens[1..] {
                        let to: u32 = tok
                            .parse()
                            .map_err(|e| parse_err(pos + 1, &format!("invalid target id: {e}")))?;
                        if to == 0 || to > n {
                            return Err(parse_err(
                                pos + 1,
                                &format!("target vertex ID out of range: {to} (n={n})"),
                            ));
                        }
                        edges.push((from - 1, to - 1));
                    }
                    pos += 1;
                }
            }
        }
    }

    let mut graph = Graph::new(n, directed)?;
    graph.add_edges(edges)?;

    let final_labels = if labels.is_empty() {
        None
    } else {
        Some(labels)
    };
    let final_weights = if has_weights { Some(weights) } else { None };

    if let Some(ref lbls) = final_labels {
        graph.set_vertex_attribute_all(
            "name",
            lbls.iter()
                .map(|l| AttributeValue::String(l.clone()))
                .collect(),
        )?;
    }
    if let Some(ref wts) = final_weights {
        graph.set_edge_attribute_all(
            "weight",
            wts.iter().map(|&w| AttributeValue::Numeric(w)).collect(),
        )?;
    }

    Ok(DlGraph {
        graph,
        labels: final_labels,
        weights: final_weights,
    })
}

fn parse_err(line: usize, msg: &str) -> IgraphError {
    IgraphError::Parse {
        line,
        message: msg.to_string(),
    }
}

fn skip_empty(lines: &[String], mut pos: usize) -> usize {
    while pos < lines.len() && lines[pos].trim().is_empty() {
        pos += 1;
    }
    pos
}

fn extract_n(s: &str) -> Option<u32> {
    let lower = s.to_ascii_lowercase();
    // Look for n=N or n = N pattern
    for part in lower.split([',', ';']) {
        let trimmed = part.trim();
        if let Some(after_n) = trimmed.strip_prefix('n') {
            let rest = after_n.trim();
            if let Some(stripped) = rest.strip_prefix('=') {
                if let Ok(val) = stripped.trim().parse::<u32>() {
                    return Some(val);
                }
            }
        }
    }
    None
}

fn split_labels(s: &str) -> Vec<String> {
    if s.contains(',') {
        s.split(',')
            .map(|t| t.trim().trim_matches('"').to_string())
            .filter(|t| !t.is_empty())
            .collect()
    } else {
        s.split_whitespace()
            .map(|t| t.trim_matches('"').to_string())
            .collect()
    }
}

fn get_or_add_label(labels: &mut Vec<String>, name: &str) -> u32 {
    for (i, lbl) in labels.iter().enumerate() {
        if lbl == name {
            #[allow(clippy::cast_possible_truncation)]
            return i as u32;
        }
    }
    labels.push(name.to_string());
    #[allow(clippy::cast_possible_truncation)]
    let id = (labels.len() - 1) as u32;
    id
}

/// Write a graph in UCINET DL edgelist1 format.
///
/// Uses the `edgelist1` representation with 1-based vertex IDs. Vertex
/// labels are emitted as a `labels:` section if provided. Edge weights
/// appear as a third field on each edge line.
///
/// # Examples
///
/// ```
/// use rust_igraph::{Graph, write_dl};
///
/// let mut g = Graph::with_vertices(3);
/// g.add_edge(0, 1).unwrap();
/// g.add_edge(1, 2).unwrap();
///
/// let mut buf = Vec::new();
/// write_dl(&g, None, None, &mut buf).unwrap();
/// let s = String::from_utf8(buf).unwrap();
/// assert!(s.contains("DL n=3"));
/// assert!(s.contains("format = edgelist1"));
/// ```
pub fn write_dl<W: Write>(
    graph: &Graph,
    vertex_labels: Option<&[String]>,
    edge_weights: Option<&[f64]>,
    writer: &mut W,
) -> IgraphResult<()> {
    if let Some(l) = vertex_labels {
        if l.len() != graph.vcount() as usize {
            return Err(IgraphError::InvalidArgument(format!(
                "vertex_labels length {} does not match vcount {}",
                l.len(),
                graph.vcount()
            )));
        }
    }
    if let Some(w) = edge_weights {
        if w.len() != graph.ecount() {
            return Err(IgraphError::InvalidArgument(format!(
                "edge_weights length {} does not match ecount {}",
                w.len(),
                graph.ecount()
            )));
        }
    }

    writeln!(writer, "DL n={}", graph.vcount())?;
    writeln!(writer, "format = edgelist1")?;

    let has_attr_labels =
        vertex_labels.is_none() && graph.vertex_attribute_names().contains(&"name");
    if let Some(labels) = vertex_labels {
        writeln!(writer, "labels:")?;
        let joined: Vec<&str> = labels.iter().map(String::as_str).collect();
        writeln!(writer, "{}", joined.join(","))?;
    } else if has_attr_labels {
        writeln!(writer, "labels:")?;
        let attr_labels: Vec<String> = (0..graph.vcount())
            .map(|v| {
                graph
                    .vertex_attribute("name", v)
                    .and_then(AttributeValue::as_str)
                    .unwrap_or("")
                    .to_owned()
            })
            .collect();
        let joined: Vec<&str> = attr_labels.iter().map(String::as_str).collect();
        writeln!(writer, "{}", joined.join(","))?;
    }

    writeln!(writer, "data:")?;

    for eid in 0..graph.ecount() {
        #[allow(clippy::cast_possible_truncation)]
        let (from, to) = graph.edge(eid as u32)?;

        if let Some(w) = edge_weights {
            writeln!(writer, "{} {} {}", from + 1, to + 1, w[eid])?;
        } else {
            #[allow(clippy::cast_possible_truncation)]
            let eid_u32 = eid as u32;
            if let Some(w) = graph
                .edge_attribute("weight", eid_u32)
                .and_then(AttributeValue::as_f64)
            {
                writeln!(writer, "{} {} {w}", from + 1, to + 1)?;
            } else {
                writeln!(writer, "{} {}", from + 1, to + 1)?;
            }
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_edgelist1_basic() {
        let input = b"DL n=3\nformat = edgelist1\ndata:\n1 2\n2 3\n1 3\n";
        let result = read_dl(&input[..], true).unwrap();
        assert_eq!(result.graph.vcount(), 3);
        assert_eq!(result.graph.ecount(), 3);
        assert!(result.graph.is_directed());
    }

    #[test]
    fn test_edgelist1_undirected() {
        let input = b"DL n=3\nformat = edgelist1\ndata:\n1 2\n2 3\n";
        let result = read_dl(&input[..], false).unwrap();
        assert_eq!(result.graph.vcount(), 3);
        assert_eq!(result.graph.ecount(), 2);
        assert!(!result.graph.is_directed());
    }

    #[test]
    fn test_edgelist1_with_weights() {
        let input = b"DL n=3\nformat = edgelist1\ndata:\n1 2 1.5\n2 3 2.5\n";
        let result = read_dl(&input[..], true).unwrap();
        let w = result.weights.unwrap();
        assert!((w[0] - 1.5).abs() < 1e-10);
        assert!((w[1] - 2.5).abs() < 1e-10);
    }

    #[test]
    fn test_edgelist1_with_labels() {
        let input = b"DL n=3\nformat = edgelist1\nlabels:\nA,B,C\ndata:\n1 2\n2 3\n";
        let result = read_dl(&input[..], true).unwrap();
        let labels = result.labels.unwrap();
        assert_eq!(labels, vec!["A", "B", "C"]);
    }

    #[test]
    fn test_edgelist1_labels_embedded() {
        let input = b"DL n=3\nformat = edgelist1\nlabels embedded:\ndata:\nAlice Bob\nBob Carol\n";
        let result = read_dl(&input[..], true).unwrap();
        assert_eq!(result.graph.ecount(), 2);
        let labels = result.labels.unwrap();
        assert_eq!(labels[0], "Alice");
        assert_eq!(labels[1], "Bob");
        assert_eq!(labels[2], "Carol");
    }

    #[test]
    fn test_fullmatrix_basic() {
        let input = b"DL n=3\nformat = fullmatrix\ndata:\n0 1 0\n0 0 1\n1 0 0\n";
        let result = read_dl(&input[..], true).unwrap();
        assert_eq!(result.graph.vcount(), 3);
        assert_eq!(result.graph.ecount(), 3);
    }

    #[test]
    fn test_fullmatrix_default_format() {
        // No format line = default fullmatrix
        let input = b"DL n=3\ndata:\n0 1 1\n1 0 0\n0 1 0\n";
        let result = read_dl(&input[..], true).unwrap();
        assert_eq!(result.graph.vcount(), 3);
        assert_eq!(result.graph.ecount(), 4);
    }

    #[test]
    fn test_fullmatrix_labels_embedded() {
        let input = b"DL n=3\nlabels embedded:\ndata:\nA B C\nA 0 1 0\nB 0 0 1\nC 1 0 0\n";
        let result = read_dl(&input[..], true).unwrap();
        assert_eq!(result.graph.vcount(), 3);
        assert_eq!(result.graph.ecount(), 3);
        let labels = result.labels.unwrap();
        assert_eq!(labels, vec!["A", "B", "C"]);
    }

    #[test]
    fn test_nodelist1_basic() {
        let input = b"DL n=4\nformat = nodelist1\ndata:\n1 2 3\n2 3\n3 4\n";
        let result = read_dl(&input[..], true).unwrap();
        assert_eq!(result.graph.vcount(), 4);
        assert_eq!(result.graph.ecount(), 4);
    }

    #[test]
    fn test_nodelist1_labels_embedded() {
        let input = b"DL n=3\nformat = nodelist1\nlabels embedded:\ndata:\nA B C\nB C\n";
        let result = read_dl(&input[..], true).unwrap();
        assert_eq!(result.graph.ecount(), 3);
        let labels = result.labels.unwrap();
        assert_eq!(labels[0], "A");
    }

    #[test]
    fn test_case_insensitive() {
        let input = b"dl N=2\nFORMAT = EDGELIST1\nDATA:\n1 2\n";
        let result = read_dl(&input[..], true).unwrap();
        assert_eq!(result.graph.vcount(), 2);
        assert_eq!(result.graph.ecount(), 1);
    }

    #[test]
    fn test_empty_graph() {
        let input = b"DL n=5\nformat = edgelist1\ndata:\n";
        let result = read_dl(&input[..], true).unwrap();
        assert_eq!(result.graph.vcount(), 5);
        assert_eq!(result.graph.ecount(), 0);
    }

    #[test]
    fn test_no_dl_header_error() {
        let input = b"n=3\ndata:\n1 2\n";
        let result = read_dl(&input[..], true);
        assert!(result.is_err());
    }

    #[test]
    fn test_no_n_error() {
        let input = b"DL\nformat = edgelist1\ndata:\n1 2\n";
        let result = read_dl(&input[..], true);
        assert!(result.is_err());
    }

    #[test]
    fn test_vertex_id_out_of_range() {
        let input = b"DL n=2\nformat = edgelist1\ndata:\n1 5\n";
        let result = read_dl(&input[..], true);
        assert!(result.is_err());
    }

    #[test]
    fn test_zero_vertex_id_error() {
        let input = b"DL n=2\nformat = edgelist1\ndata:\n0 1\n";
        let result = read_dl(&input[..], true);
        assert!(result.is_err());
    }

    #[test]
    fn test_n_on_same_line() {
        let input = b"DL n=4\nformat=edgelist1\ndata:\n1 2\n3 4\n";
        let result = read_dl(&input[..], true).unwrap();
        assert_eq!(result.graph.vcount(), 4);
        assert_eq!(result.graph.ecount(), 2);
    }

    #[test]
    fn test_labels_whitespace_separated() {
        let input = b"DL n=3\nformat = edgelist1\nlabels:\nAlpha Beta Gamma\ndata:\n1 2\n";
        let result = read_dl(&input[..], true).unwrap();
        let labels = result.labels.unwrap();
        assert_eq!(labels, vec!["Alpha", "Beta", "Gamma"]);
    }

    // --- write_dl tests ---

    #[test]
    fn test_write_basic_directed() {
        let mut g = Graph::new(3, true).unwrap();
        g.add_edge(0, 1).unwrap();
        g.add_edge(1, 2).unwrap();

        let mut buf = Vec::new();
        write_dl(&g, None, None, &mut buf).unwrap();
        let s = String::from_utf8(buf).unwrap();

        assert!(s.contains("DL n=3"));
        assert!(s.contains("format = edgelist1"));
        assert!(s.contains("data:"));
        assert!(s.contains("1 2\n"));
        assert!(s.contains("2 3\n"));
    }

    #[test]
    fn test_write_with_labels() {
        let mut g = Graph::with_vertices(3);
        g.add_edge(0, 1).unwrap();

        let labels = vec!["A".to_string(), "B".to_string(), "C".to_string()];
        let mut buf = Vec::new();
        write_dl(&g, Some(&labels), None, &mut buf).unwrap();
        let s = String::from_utf8(buf).unwrap();

        assert!(s.contains("labels:"));
        assert!(s.contains("A,B,C"));
    }

    #[test]
    fn test_write_with_weights() {
        let mut g = Graph::with_vertices(2);
        g.add_edge(0, 1).unwrap();

        let weights = vec![3.5];
        let mut buf = Vec::new();
        write_dl(&g, None, Some(&weights), &mut buf).unwrap();
        let s = String::from_utf8(buf).unwrap();

        assert!(s.contains("1 2 3.5\n"));
    }

    #[test]
    fn test_write_empty_graph() {
        let g = Graph::with_vertices(0);

        let mut buf = Vec::new();
        write_dl(&g, None, None, &mut buf).unwrap();
        let s = String::from_utf8(buf).unwrap();

        assert!(s.contains("DL n=0"));
        assert!(s.contains("data:"));
    }

    #[test]
    fn test_write_no_edges() {
        let g = Graph::with_vertices(5);

        let mut buf = Vec::new();
        write_dl(&g, None, None, &mut buf).unwrap();
        let s = String::from_utf8(buf).unwrap();

        assert!(s.contains("DL n=5"));
        let after_data = s.split("data:\n").nth(1).unwrap();
        assert!(after_data.trim().is_empty());
    }

    #[test]
    fn test_write_label_mismatch_error() {
        let g = Graph::with_vertices(3);
        let labels = vec!["A".to_string()];
        let mut buf = Vec::new();
        assert!(write_dl(&g, Some(&labels), None, &mut buf).is_err());
    }

    #[test]
    fn test_write_weight_mismatch_error() {
        let mut g = Graph::with_vertices(2);
        g.add_edge(0, 1).unwrap();
        let weights = vec![1.0, 2.0];
        let mut buf = Vec::new();
        assert!(write_dl(&g, None, Some(&weights), &mut buf).is_err());
    }

    #[test]
    fn test_roundtrip_directed() {
        let mut g = Graph::new(4, true).unwrap();
        g.add_edge(0, 1).unwrap();
        g.add_edge(1, 2).unwrap();
        g.add_edge(2, 3).unwrap();

        let mut buf = Vec::new();
        write_dl(&g, None, None, &mut buf).unwrap();
        let result = read_dl(&buf[..], true).unwrap();

        assert_eq!(result.graph.vcount(), g.vcount());
        assert_eq!(result.graph.ecount(), g.ecount());
        assert!(result.graph.is_directed());
    }

    #[test]
    fn test_roundtrip_undirected() {
        let mut g = Graph::with_vertices(3);
        g.add_edge(0, 1).unwrap();
        g.add_edge(1, 2).unwrap();

        let mut buf = Vec::new();
        write_dl(&g, None, None, &mut buf).unwrap();
        let result = read_dl(&buf[..], false).unwrap();

        assert_eq!(result.graph.vcount(), g.vcount());
        assert_eq!(result.graph.ecount(), g.ecount());
        assert!(!result.graph.is_directed());
    }

    #[test]
    fn test_roundtrip_with_labels() {
        let mut g = Graph::with_vertices(3);
        g.add_edge(0, 1).unwrap();
        g.add_edge(1, 2).unwrap();

        let labels = vec!["X".to_string(), "Y".to_string(), "Z".to_string()];
        let mut buf = Vec::new();
        write_dl(&g, Some(&labels), None, &mut buf).unwrap();
        let result = read_dl(&buf[..], false).unwrap();

        assert_eq!(result.labels.unwrap(), labels);
    }

    #[test]
    fn test_roundtrip_with_weights() {
        let mut g = Graph::with_vertices(2);
        g.add_edge(0, 1).unwrap();

        let weights = vec![2.75];
        let mut buf = Vec::new();
        write_dl(&g, None, Some(&weights), &mut buf).unwrap();
        let result = read_dl(&buf[..], false).unwrap();

        let w = result.weights.unwrap();
        assert!((w[0] - 2.75).abs() < 1e-10);
    }

    #[test]
    fn test_roundtrip_with_labels_and_weights() {
        let mut g = Graph::new(3, true).unwrap();
        g.add_edge(0, 1).unwrap();
        g.add_edge(1, 2).unwrap();

        let labels = vec!["A".to_string(), "B".to_string(), "C".to_string()];
        let weights = vec![1.5, 2.5];
        let mut buf = Vec::new();
        write_dl(&g, Some(&labels), Some(&weights), &mut buf).unwrap();
        let result = read_dl(&buf[..], true).unwrap();

        assert_eq!(result.graph.vcount(), 3);
        assert_eq!(result.graph.ecount(), 2);
        assert_eq!(result.labels.unwrap(), labels);
        let w = result.weights.unwrap();
        assert!((w[0] - 1.5).abs() < 1e-10);
        assert!((w[1] - 2.5).abs() < 1e-10);
    }

    #[test]
    fn test_write_self_loop() {
        let mut g = Graph::with_vertices(2);
        g.add_edge(0, 0).unwrap();

        let mut buf = Vec::new();
        write_dl(&g, None, None, &mut buf).unwrap();
        let s = String::from_utf8(buf).unwrap();

        assert!(s.contains("1 1\n"));
    }

    #[test]
    fn test_write_one_based_ids() {
        let mut g = Graph::with_vertices(4);
        g.add_edge(2, 3).unwrap();

        let mut buf = Vec::new();
        write_dl(&g, None, None, &mut buf).unwrap();
        let s = String::from_utf8(buf).unwrap();

        assert!(s.contains("3 4\n"));
    }

    // --- Attribute integration tests ---

    #[test]
    fn test_read_stores_label_attribute() {
        let input = b"DL n=3\nformat = edgelist1\nlabels:\nAlice,Bob,Carol\ndata:\n1 2\n";
        let result = read_dl(&input[..], false).unwrap();
        assert_eq!(
            result
                .graph
                .vertex_attribute("name", 0)
                .and_then(AttributeValue::as_str),
            Some("Alice")
        );
        assert_eq!(
            result
                .graph
                .vertex_attribute("name", 2)
                .and_then(AttributeValue::as_str),
            Some("Carol")
        );
    }

    #[test]
    fn test_read_stores_weight_attribute() {
        let input = b"DL n=2\nformat = edgelist1\ndata:\n1 2 4.5\n";
        let result = read_dl(&input[..], false).unwrap();
        let w = result
            .graph
            .edge_attribute("weight", 0)
            .and_then(AttributeValue::as_f64)
            .unwrap();
        assert!((w - 4.5).abs() < 1e-10);
    }

    #[test]
    fn test_read_no_label_attribute_when_absent() {
        let input = b"DL n=2\nformat = edgelist1\ndata:\n1 2\n";
        let result = read_dl(&input[..], false).unwrap();
        assert!(result.graph.vertex_attribute("name", 0).is_none());
    }

    #[test]
    fn test_write_fallback_to_label_attribute() {
        let mut g = Graph::with_vertices(2);
        g.add_edge(0, 1).unwrap();
        g.set_vertex_attribute("name", 0, AttributeValue::String("X".into()))
            .unwrap();
        g.set_vertex_attribute("name", 1, AttributeValue::String("Y".into()))
            .unwrap();

        let mut buf = Vec::new();
        write_dl(&g, None, None, &mut buf).unwrap();
        let s = String::from_utf8(buf).unwrap();
        assert!(s.contains("labels:"));
        assert!(s.contains("X,Y"));
    }

    #[test]
    fn test_write_fallback_to_weight_attribute() {
        let mut g = Graph::with_vertices(2);
        g.add_edge(0, 1).unwrap();
        g.set_edge_attribute("weight", 0, AttributeValue::Numeric(7.5))
            .unwrap();

        let mut buf = Vec::new();
        write_dl(&g, None, None, &mut buf).unwrap();
        let s = String::from_utf8(buf).unwrap();
        assert!(s.contains("1 2 7.5"));
    }

    #[test]
    fn test_roundtrip_via_attributes() {
        let input =
            b"DL n=3\nformat = edgelist1\nlabels:\nAlice,Bob,Carol\ndata:\n1 2 1.5\n2 3 2.5\n";
        let result = read_dl(&input[..], false).unwrap();

        let mut buf = Vec::new();
        write_dl(&result.graph, None, None, &mut buf).unwrap();

        let result2 = read_dl(&buf[..], false).unwrap();
        assert_eq!(result2.graph.vcount(), 3);
        assert_eq!(result2.graph.ecount(), 2);
        assert!(result2.labels.is_some());
        assert!(result2.weights.is_some());
    }

    #[test]
    fn test_explicit_params_override_attributes() {
        let mut g = Graph::with_vertices(2);
        g.add_edge(0, 1).unwrap();
        g.set_vertex_attribute("name", 0, AttributeValue::String("attr_A".into()))
            .unwrap();
        g.set_vertex_attribute("name", 1, AttributeValue::String("attr_B".into()))
            .unwrap();
        g.set_edge_attribute("weight", 0, AttributeValue::Numeric(9.0))
            .unwrap();

        let labels = vec!["explicit_A".to_string(), "explicit_B".to_string()];
        let weights = vec![1.0];
        let mut buf = Vec::new();
        write_dl(&g, Some(&labels), Some(&weights), &mut buf).unwrap();
        let s = String::from_utf8(buf).unwrap();
        assert!(s.contains("explicit_A,explicit_B"));
        assert!(!s.contains("attr_A"));
        assert!(s.contains("1 2 1"));
    }
}