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
use std::collections::HashMap;
use crate::{Parser,element,Element,Error};
use unbounded_interval_tree::IntervalTree;
use std::ops::{Bound::Included,Bound};
use std::io::{Read,Seek};

pub struct Scan<F: Read+Seek> {
  pub parser: Parser<F>,
  pub table: ScanTable,
}

#[derive(Debug,Clone)]
pub struct ScanTable {
  pub nodes: IntervalTree<i64>,
  pub ways: IntervalTree<i64>,
  pub relations: IntervalTree<i64>,
  pub node_interval_offsets: HashMap<(Bound<i64>,Bound<i64>),(u64,usize,usize)>,
  pub way_interval_offsets: HashMap<(Bound<i64>,Bound<i64>),(u64,usize,usize)>,
  pub relation_interval_offsets: HashMap<(Bound<i64>,Bound<i64>),(u64,usize,usize)>,
}
impl Default for ScanTable {
  fn default() -> Self {
    Self {
      nodes: IntervalTree::default(),
      ways: IntervalTree::default(),
      relations: IntervalTree::default(),
      node_interval_offsets: HashMap::new(),
      way_interval_offsets: HashMap::new(),
      relation_interval_offsets: HashMap::new(),
    }
  }
}

impl ScanTable {
  pub fn get_node_blob_offsets(&self) -> impl Iterator<Item=(u64,usize,usize)>+'_ {
    self.node_interval_offsets.values().cloned()
  }
  pub fn get_node_blob_offsets_for_id(&self, id: i64) -> Vec<(u64,usize,usize)> {
    let q = (Included(id),Included(id));
    self.nodes.get_interval_overlaps(&q).iter()
      .map(|iv| self.node_interval_offsets.get(iv))
      .filter(|o_pair| o_pair.is_some())
      .map(|o_pair| o_pair.unwrap())
      .cloned()
      .collect()
  }
  pub fn get_way_blob_offsets(&self) -> impl Iterator<Item=(u64,usize,usize)>+'_ {
    self.way_interval_offsets.values().cloned()
  }
  pub fn get_way_blob_offsets_for_id(&self, id: i64) -> Vec<(u64,usize,usize)> {
    let q = (Included(id),Included(id));
    self.ways.get_interval_overlaps(&q).iter()
      .map(|iv| self.way_interval_offsets.get(iv))
      .filter(|o_pair| o_pair.is_some())
      .map(|o_pair| o_pair.unwrap())
      .cloned()
      .collect()
  }
  pub fn get_relation_blob_offsets(&self) -> impl Iterator<Item=(u64,usize,usize)>+'_ {
    self.relation_interval_offsets.values().cloned()
  }
  pub fn get_relation_blob_offsets_for_id(&self, id: i64) -> Vec<(u64,usize,usize)> {
    let q = (Included(id),Included(id));
    self.relations.get_interval_overlaps(&q).iter()
      .map(|iv| self.relation_interval_offsets.get(iv))
      .filter(|o_pair| o_pair.is_some())
      .map(|o_pair| o_pair.unwrap())
      .cloned()
      .collect()
  }
}

impl<F> Scan<F> where F: Read+Seek {
  pub fn new(parser: Parser<F>) -> Self {
    Self {
      parser,
      table: ScanTable::default(),
    }
  }
  pub fn from_table(parser: Parser<F>, table: ScanTable) -> Self {
    Self { parser, table }
  }
  pub fn scan(&mut self, start: u64, end: u64) -> Result<(),Error> {
    let mut offset = start;
    while offset < end {
      let (blob_header_len,blob_header) = self.parser.read_blob_header(offset)?;
      let blob_offset = offset + blob_header_len;
      let blob_len = blob_header.datasize as usize;
      let blob = self.parser.read_blob(blob_offset, blob_len)?;
      let len = blob_header_len + blob_len as u64;
      if offset == 0 { // skip header
        offset += len;
        continue;
      }
      let items = blob.decode_primitive()?.decode();

      let mut etype = element::MemberType::Node;
      let mut min_id = i64::MAX;
      let mut max_id = i64::MIN;
      for item in items.iter() {
        match item {
          Element::Node(node) => {
            min_id = node.id.min(min_id);
            max_id = node.id.max(max_id);
          },
          Element::Way(way) => {
            etype = element::MemberType::Way;
            min_id = way.id.min(min_id);
            max_id = way.id.max(max_id);
          },
          Element::Relation(relation) => {
            etype = element::MemberType::Relation;
            min_id = relation.id.min(min_id);
            max_id = relation.id.max(max_id);
          },
        }
      }
      if !items.is_empty() {
        let iv = (Included(min_id),Included(max_id));
        match etype {
          element::MemberType::Node => {
            self.table.node_interval_offsets.insert(
              iv.clone(),
              (blob_offset,blob_len,items.len())
            );
            self.table.nodes.insert(iv);
          },
          element::MemberType::Way => {
            self.table.way_interval_offsets.insert(
              iv.clone(),
              (blob_offset,blob_len,items.len())
            );
            self.table.ways.insert(iv);
          },
          element::MemberType::Relation => {
            self.table.relation_interval_offsets.insert(
              iv.clone(),
              (blob_offset,blob_len,items.len())
            );
            self.table.relations.insert(iv);
          },
        }
      }
      offset += len;
    }
    Ok(())
  }
  pub fn get_node_blob_offsets(&self) -> impl Iterator<Item=(u64,usize,usize)>+'_ {
    self.table.get_node_blob_offsets()
  }
  pub fn get_node_blob_offsets_for_id(&mut self, id: i64) -> Vec<(u64,usize,usize)> {
    self.table.get_node_blob_offsets_for_id(id)
  }
  pub fn get_node(&mut self, id: i64) -> Result<Option<element::Node>,Error> {
    for (offset,byte_len,_len) in self.get_node_blob_offsets_for_id(id) {
      let blob = self.parser.read_blob(offset,byte_len)?;
      let items = blob.decode_primitive()?.decode();
      for item in items {
        match item {
          Element::Node(node) => {
            if node.id == id { return Ok(Some(node)) }
          },
          _ => { break }
        }
      }
    }
    Ok(None)
  }
  pub fn get_way_blob_offsets(&mut self) -> impl Iterator<Item=(u64,usize,usize)>+'_ {
    self.table.get_way_blob_offsets()
  }
  pub fn get_way_blob_offsets_for_id(&mut self, id: i64) -> Vec<(u64,usize,usize)> {
    self.table.get_way_blob_offsets_for_id(id)
  }
  pub fn get_way(&mut self, id: i64) -> Result<Option<element::Way>,Error> {
    for (offset,byte_len,_len) in self.get_way_blob_offsets_for_id(id) {
      let blob = self.parser.read_blob(offset,byte_len)?;
      let items = blob.decode_primitive()?.decode();
      for item in items {
        match item {
          Element::Way(way) => {
            if way.id == id { return Ok(Some(way)) }
          },
          _ => { break }
        }
      }
    }
    Ok(None)
  }
  pub fn get_relation_blob_offsets(&mut self) -> impl Iterator<Item=(u64,usize,usize)>+'_ {
    self.table.get_relation_blob_offsets()
  }
  pub fn get_relation_blob_offsets_for_id(&mut self, id: i64) -> Vec<(u64,usize,usize)> {
    self.table.get_relation_blob_offsets_for_id(id)
  }
  pub fn get_relation(&mut self, id: i64) -> Result<Option<element::Relation>,Error> {
    for (offset,byte_len,_len) in self.get_relation_blob_offsets_for_id(id) {
      let blob = self.parser.read_blob(offset,byte_len)?;
      let items = blob.decode_primitive()?.decode();
      for item in items {
        match item {
          Element::Relation(relation) => {
            if relation.id == id { return Ok(Some(relation)) }
          },
          _ => { break }
        }
      }
    }
    Ok(None)
  }
}