use crate::{
Bounds, Error, Library, Point, Result,
decode::{Decode, ReadWindow, add},
source::Source,
};
use std::{borrow::Cow, fmt};
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum FeatureType {
Node,
Way,
Relation,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FeatureId {
pub kind: FeatureType,
pub id: u64,
}
impl fmt::Display for FeatureId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}{id}",
match self.kind {
FeatureType::Node => 'N',
FeatureType::Way => 'W',
FeatureType::Relation => 'R',
},
id = self.id
)
}
}
#[derive(Clone, Copy, Default)]
pub(crate) struct TileExtent {
page: u32,
length: u32,
}
impl TileExtent {
#[inline]
pub(crate) fn new(start: u64, end: u64) -> Result<Self> {
let page = u32::try_from(start >> 12)
.ok()
.filter(|_| start & 4095 == 0)
.ok_or_else(|| Error::invalid(start, "invalid tile page"))?;
let length = end
.checked_sub(start)
.and_then(|length| u32::try_from(length).ok())
.ok_or_else(|| Error::invalid(start, "invalid tile extent"))?;
Ok(Self { page, length })
}
#[inline]
pub(crate) fn start(self) -> u64 {
u64::from(self.page) << 12
}
#[inline]
pub(crate) fn end(self) -> u64 {
self.start() + u64::from(self.length)
}
}
pub struct Feature<'a, S> {
pub(crate) library: &'a Library<S>,
header: u64,
pub(crate) tile: TileExtent,
anchor_offset: u32,
tag_pointer: i32,
}
impl<S> Copy for Feature<'_, S> {}
impl<S> Clone for Feature<'_, S> {
fn clone(&self) -> Self {
*self
}
}
impl<S> fmt::Debug for Feature<'_, S> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Feature").field("id", &self.id()).finish()
}
}
impl<S> Feature<'_, S> {
#[inline]
pub(crate) fn tile_start(self) -> u64 {
self.tile.start()
}
#[inline]
pub(crate) fn tile_end(self) -> u64 {
self.tile.end()
}
#[inline]
pub(crate) fn anchor(self) -> u64 {
self.tile_start() + u64::from(self.anchor_offset)
}
pub fn id(self) -> FeatureId {
FeatureId {
kind: self.kind(),
id: self.header >> 12,
}
}
pub fn kind(self) -> FeatureType {
match (self.header >> 3) & 3 {
0 => FeatureType::Node,
1 => FeatureType::Way,
2 => FeatureType::Relation,
_ => unreachable!("validated feature header"),
}
}
pub fn is_area(self) -> bool {
self.header & 2 != 0
}
pub(crate) fn flags(self) -> u16 {
self.header as u16 & 0xfff
}
}
impl<'a, S: Source> Feature<'a, S> {
#[inline]
pub(crate) fn at(
library: &'a Library<S>,
anchor: u64,
tile_start: u64,
tile_end: u64,
) -> Result<Self> {
Self::at_source(
library,
&library.source,
anchor,
TileExtent::new(tile_start, tile_end)?,
)
}
pub(crate) fn at_source(
library: &'a Library<S>,
source: &impl Source,
anchor: u64,
tile: TileExtent,
) -> Result<Self> {
let record = source.array::<12>(anchor)?;
Self::at_record(library, &record, anchor, tile)
}
#[inline]
pub(crate) fn at_window<const EXACT: bool>(
library: &'a Library<S>,
window: &ReadWindow<'_, S>,
anchor: u64,
tile: TileExtent,
) -> Result<Self> {
if let Some(record) = window.record::<12, EXACT>(anchor, tile.end()) {
Self::at_record(library, record, anchor, tile)
} else {
Self::at_source(library, window, anchor, tile)
}
}
#[inline]
pub(crate) fn at_record(
library: &'a Library<S>,
record: &[u8; 12],
anchor: u64,
tile: TileExtent,
) -> Result<Self> {
let kind = match record[0] & 24 {
0 => FeatureType::Node,
8 => FeatureType::Way,
16 => FeatureType::Relation,
_ => return Err(Error::invalid(anchor, "invalid feature type")),
};
let before = if kind == FeatureType::Node { 8 } else { 16 };
let after = if kind == FeatureType::Node { 12 } else { 16 };
let start = tile.start();
if anchor < start + before || anchor > tile.end().saturating_sub(after) {
return Err(Error::invalid(anchor, "feature outside tile"));
}
Ok(Self::from_leaf_header(
library,
record,
tile,
(anchor - start) as u32,
))
}
#[inline]
pub(crate) fn from_leaf_header(
library: &'a Library<S>,
record: &[u8; 12],
tile: TileExtent,
anchor_offset: u32,
) -> Self {
Self {
library,
tile,
anchor_offset,
header: u64::from_le_bytes(record[..8].try_into().expect("eight header bytes")),
tag_pointer: i32::from_le_bytes(
record[8..].try_into().expect("four tag-pointer bytes"),
),
}
}
pub fn bounds(self) -> Result<Bounds> {
self.bounds_source(&self.library.source)
}
pub(crate) fn bounds_source(self, source: &impl Source) -> Result<Bounds> {
if self.kind() == FeatureType::Node {
let bytes = source.array::<8>(self.anchor() - 8)?;
let p = Point {
x: i32::from_le_bytes(bytes[..4].try_into().expect("four x bytes")),
y: i32::from_le_bytes(bytes[4..].try_into().expect("four y bytes")),
};
Ok(Bounds { min: p, max: p })
} else {
Bounds::read(source, self.anchor() - 16)
}
}
#[inline(always)]
pub(crate) fn bounds_window<const EXACT: bool>(
self,
window: &ReadWindow<'_, S>,
) -> Result<Bounds> {
if self.kind() == FeatureType::Node {
if let Some(b) = window.record::<8, EXACT>(self.anchor() - 8, self.tile_end()) {
let p = Point {
x: i32::from_le_bytes(b[..4].try_into().expect("four x bytes")),
y: i32::from_le_bytes(b[4..].try_into().expect("four y bytes")),
};
return Ok(Bounds { min: p, max: p });
}
} else if let Some(b) = window.record::<16, EXACT>(self.anchor() - 16, self.tile_end()) {
return Bounds::from_record(b);
}
self.bounds_source(window)
}
pub fn point(self) -> Result<Option<Point>> {
if self.kind() != FeatureType::Node {
return Ok(None);
}
let record = self.library.source.array::<8>(self.anchor() - 8)?;
Ok(Some(Point {
x: i32::from_le_bytes(record[..4].try_into().expect("four x bytes")),
y: i32::from_le_bytes(record[4..].try_into().expect("four y bytes")),
}))
}
pub(crate) fn body(self) -> Result<u64> {
if self.kind() == FeatureType::Node {
return Err(Error::WrongFeatureType);
}
let p = self.library.source.relative(self.anchor() + 12, !0)?;
self.check(p, 1)?;
Ok(p)
}
pub(crate) fn check(self, p: u64, n: u64) -> Result<()> {
if p < self.tile_start() || p.checked_add(n).is_none_or(|e| e > self.tile_end()) {
return Err(Error::invalid(p, "feature data outside tile"));
}
Ok(())
}
#[inline]
pub(crate) fn checked_tag_table(self) -> Result<u64> {
let p = add(self.anchor() + 8, i64::from(self.tag_pointer & !1))?;
self.check(p, 4)?;
Ok(p)
}
pub fn tags(self) -> Result<Tags<'a, S>> {
Tags::new(self)
}
pub fn tag(self, key: &str) -> Result<Option<TagValue<'a>>> {
for tag in self.tags()? {
let tag = tag?;
if tag.key == key {
return Ok(Some(tag.value));
}
}
Ok(None)
}
#[inline(always)]
pub(crate) fn encoded_tag(
self,
key: &str,
code: Option<u16>,
window: &mut ReadWindow<'_, S>,
strings: &mut ReadWindow<'_, S>,
) -> Result<Option<EncodedValue>> {
let pointer = self.tag_pointer;
let table = self.checked_tag_table()?;
if code.is_none() && pointer & 1 == 0 {
return Ok(None);
}
window.seek(table)?;
let s = &*window;
let mut steps = 0;
if let Some(code) = code {
let mut p = table;
let mut cursor = window.tail(table, self.tile_end());
loop {
steps += 1;
if steps > self.library.limits.max_tags {
return Err(Error::Limit("tag lookup"));
}
let entry = if let Some((entry, _)) =
cursor.and_then(|bytes| bytes.split_first_chunk::<4>())
{
u32::from_le_bytes(*entry)
} else {
self.check(p, 4)?;
s.u32(p)?
};
if entry == 0x8001 {
return Ok(None);
}
let word = entry as u16;
let found = (word >> 2) & 8191;
if found == code {
if word & 3 == 0 {
return Ok(Some(EncodedValue::Number {
mantissa: (entry >> 16) as i32 - 256,
scale: 0,
}));
}
if word & 3 == 1 {
let value = (entry >> 16) as u16;
if usize::from(value) >= self.library.string_count {
return Err(Error::invalid(p + 2, "undefined global string code"));
}
return Ok(Some(EncodedValue::Global(value)));
}
return self.encoded_value(s, i32::from(word & 3), p + 2).map(Some);
}
if found > code || word & 0x8000 != 0 {
return Ok(None);
}
let width = 4 + usize::from(word & 2);
cursor = cursor.and_then(|bytes| bytes.get(width..));
p += width as u64;
}
}
let mut p = add(table, -6)?;
loop {
steps += 1;
if steps > self.library.limits.max_tags {
return Err(Error::Limit("tag lookup"));
}
self.check(p, 6)?;
let word = s.i32(p + 2)?;
let flags = word & 7;
let value_ptr = if flags & 2 != 0 { add(p, -2)? } else { p };
self.check(value_ptr, if flags & 2 != 0 { 8 } else { 6 })?;
let key_ptr = add(table & !3, i64::from((word & !7) >> 1))?;
self.check(key_ptr, 1)?;
strings.seek(key_ptr)?;
if self.local_string_equals(strings, key_ptr, key)? {
return self.encoded_value(s, flags, value_ptr).map(Some);
}
if flags & 4 != 0 {
return Ok(None);
}
p = add(p, -i64::from(6 + (flags & 2)))?;
}
}
#[inline(always)]
pub(crate) fn encoded_local_tag(
self,
key: &str,
window: &mut ReadWindow<'_, S>,
strings: &mut ReadWindow<'_, S>,
) -> Result<Option<EncodedValue>> {
self.encoded_tag(key, None, window, strings)
}
#[inline]
fn encoded_value(self, s: &impl Source, flags: i32, p: u64) -> Result<EncodedValue> {
self.check(p, if flags & 2 != 0 { 4 } else { 2 })?;
Ok(match flags & 3 {
0 => EncodedValue::Number {
mantissa: i32::from(s.u16(p)?) - 256,
scale: 0,
},
1 => {
let code = s.u16(p)?;
if usize::from(code) >= self.library.string_count {
return Err(Error::invalid(p, "undefined global string code"));
}
EncodedValue::Global(code)
}
2 => {
let n = s.u32(p)?;
EncodedValue::Number {
mantissa: (n >> 2) as i32 - 256,
scale: (n & 3) as u8,
}
}
_ => EncodedValue::Local {
field: p,
delta: s.i32(p)?,
},
})
}
#[inline]
pub(crate) fn local_value_target(self, field: u64, delta: i32) -> Result<u64> {
let target = add(field, i64::from(delta))?;
self.check(target, 1)?;
Ok(target)
}
fn tag_value(self, flags: i32, p: u64) -> Result<TagValue<'a>> {
let s = &self.library.source;
self.check(p, if flags & 2 != 0 { 4 } else { 2 })?;
Ok(match flags & 3 {
0 => TagValue::Number {
mantissa: i32::from(s.u16(p)?) - 256,
scale: 0,
},
1 => TagValue::Text(self.library.global_string(s.u16(p)?)?),
2 => {
let n = s.u32(p)?;
TagValue::Number {
mantissa: (n >> 2) as i32 - 256,
scale: (n & 3) as u8,
}
}
_ => {
let target = s.relative(p, !0)?;
self.check(target, 1)?;
TagValue::Text(self.local_string(target)?)
}
})
}
fn local_string(self, start: u64) -> Result<Cow<'a, str>> {
self.local_string_source(&self.library.source, start)
}
fn local_string_source<'s>(self, source: &'s impl Source, start: u64) -> Result<Cow<'s, str>> {
self.check(start, 1)?;
let mut cursor = start;
let length = source.varint(&mut cursor)?;
if length > 32767 {
return Err(Error::invalid(start, "string exceeds format limit"));
}
self.check(start, cursor - start + length)?;
source.text(cursor, length as usize)
}
fn local_bytes_source<'s>(self, source: &'s impl Source, start: u64) -> Result<Cow<'s, [u8]>> {
self.check(start, 1)?;
let mut cursor = start;
let length = source.varint(&mut cursor)?;
if length > 32767 {
return Err(Error::invalid(start, "string exceeds format limit"));
}
self.check(start, cursor - start + length)?;
if let Some(bytes) = source.view(cursor, length as usize)? {
return Ok(Cow::Borrowed(bytes));
}
let mut out = vec![0; length as usize];
source.read_exact_at(cursor, &mut out)?;
Ok(Cow::Owned(out))
}
#[inline]
fn short_local_bytes<'s>(
self,
source: &'s ReadWindow<'_, S>,
start: u64,
) -> Result<Option<&'s [u8]>> {
self.check(start, 1)?;
Ok(source.tail(start, self.tile_end()).and_then(|bytes| {
let (&length, tail) = bytes.split_first()?;
if length < 128 {
tail.get(..usize::from(length))
} else {
None
}
}))
}
#[inline]
pub(crate) fn local_bytes_window<'s>(
self,
source: &'s ReadWindow<'_, S>,
start: u64,
) -> Result<Cow<'s, [u8]>> {
if let Some(bytes) = self.short_local_bytes(source, start)? {
return Ok(Cow::Borrowed(bytes));
}
self.local_bytes_source(source, start)
}
#[inline]
pub(crate) fn local_string_window<'s>(
self,
source: &'s ReadWindow<'_, S>,
start: u64,
) -> Result<Cow<'s, str>> {
if let Some(bytes) = self.short_local_bytes(source, start)? {
return std::str::from_utf8(bytes)
.map(Cow::Borrowed)
.map_err(|_| Error::invalid(start + 1, "invalid UTF-8"));
}
self.local_string_source(source, start)
}
#[inline]
pub(crate) fn local_string_equals(
self,
source: &ReadWindow<'_, S>,
start: u64,
expected: &str,
) -> Result<bool> {
if let Some(bytes) = self.short_local_bytes(source, start)? {
return Ok(bytes == expected.as_bytes());
}
Ok(self.local_bytes_source(source, start)?.as_ref() == expected.as_bytes())
}
pub fn coordinates(self) -> Result<Coordinates<'a, S>> {
Coordinates::new(self)
}
pub fn members(self) -> Result<Members<'a, S>> {
Members::new(self)
}
}
#[derive(Clone, Copy)]
pub(crate) enum EncodedValue {
Number { mantissa: i32, scale: u8 },
Global(u16),
Local { field: u64, delta: i32 },
}
#[derive(Clone, Debug, PartialEq)]
pub enum TagValue<'a> {
Text(Cow<'a, str>),
Number {
mantissa: i32,
scale: u8,
},
}
impl TagValue<'_> {
pub fn as_number(&self) -> Option<f64> {
match self {
Self::Text(s) => s.parse().ok(),
Self::Number { mantissa, scale } => {
Some(f64::from(*mantissa) / 10f64.powi(i32::from(*scale)))
}
}
}
}
impl fmt::Display for TagValue<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Text(s) => f.write_str(s),
Self::Number { mantissa, scale: 0 } => write!(f, "{mantissa}"),
Self::Number { mantissa, scale } => {
let absolute = i64::from(*mantissa).abs();
if *mantissa < 0 {
f.write_str("-")?;
}
if *scale > 9 {
return write!(f, "0.{:0width$}", absolute, width = usize::from(*scale));
}
let divisor = 10i64.pow(u32::from(*scale));
write!(
f,
"{}.{:0width$}",
absolute / divisor,
absolute % divisor,
width = usize::from(*scale)
)
}
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Tag<'a> {
pub key: Cow<'a, str>,
pub value: TagValue<'a>,
}
pub struct Tags<'a, S> {
feature: Feature<'a, S>,
table: u64,
local: bool,
next: Option<u64>,
steps: u64,
}
impl<'a, S: Source> Tags<'a, S> {
fn new(feature: Feature<'a, S>) -> Result<Self> {
let s = &feature.library.source;
let local = feature.tag_pointer & 1 != 0;
let table = feature.checked_tag_table()?;
let next = if s.u32(table)? == 0x8001 {
if local { Some(add(table, -6)?) } else { None }
} else {
Some(table)
};
Ok(Self {
feature,
table,
local,
next,
steps: 0,
})
}
#[inline]
fn retained_bytes(&self, start: u64) -> Option<&'a [u8]> {
let source = &self.feature.library.source;
let bytes = if let Some(bytes) = source.as_bytes() {
bytes.get(usize::try_from(start).ok()?..)?
} else {
source.retained_tail(start)?
};
let tile = usize::try_from(self.feature.tile_end().checked_sub(start)?).ok()?;
bytes.get(..bytes.len().min(tile))
}
#[inline]
fn short_text(&self, start: u64) -> Option<Cow<'a, str>> {
if start < self.feature.tile_start() {
return None;
}
let (&length, tail) = self.retained_bytes(start)?.split_first()?;
if length >= 128 {
return None;
}
let text = std::str::from_utf8(tail.get(..usize::from(length))?).ok()?;
Some(Cow::Borrowed(text))
}
#[inline]
fn read_global(&mut self, p: u64) -> Option<Tag<'a>> {
let lib = self.feature.library;
let bytes = self.retained_bytes(p)?;
let word = u32::from_le_bytes(*bytes.first_chunk()?);
let dictionary = lib.strings.get()?;
let key = Cow::Borrowed(dictionary.get(((word >> 2) & 8191) as u16)?);
let narrow = (word >> 16) as u16;
let value = match word & 3 {
0 => TagValue::Number {
mantissa: i32::from(narrow) - 256,
scale: 0,
},
1 => TagValue::Text(Cow::Borrowed(dictionary.get(narrow)?)),
kind => {
let wide = u32::from_le_bytes(bytes.get(2..6)?.try_into().ok()?);
if kind == 2 {
TagValue::Number {
mantissa: (wide >> 2) as i32 - 256,
scale: (wide & 3) as u8,
}
} else {
let target = (p + 2).checked_add_signed(i64::from(wide as i32))?;
TagValue::Text(self.short_text(target)?)
}
}
};
self.next = if word & 0x8000 != 0 {
if self.local {
Some(self.table.checked_sub(6)?)
} else {
None
}
} else {
Some(p + 4 + u64::from(word & 2))
};
Some(Tag { key, value })
}
#[inline(never)]
fn read_fallback(&mut self, p: u64) -> Result<Tag<'a>> {
let f = self.feature;
let lib = f.library;
let s = &lib.source;
let (key, flags, value_ptr) = if p < self.table {
f.check(p, 6)?;
let word = s.i32(p + 2)?;
let flags = word & 7;
let key_ptr = add(self.table & !3, ((word & !7) >> 1) as i64)?;
f.check(key_ptr, 1)?;
let key = f.local_string(key_ptr)?;
self.next = if flags & 4 != 0 {
None
} else {
Some(add(p, -(6 + (flags & 2)) as i64)?)
};
(key, flags, if flags & 2 != 0 { add(p, -2)? } else { p })
} else {
f.check(p, 4)?;
let word = s.u16(p)?;
let key = lib.global_string((word >> 2) & 8191)?;
self.next = if word & 0x8000 != 0 {
if self.local {
Some(add(self.table, -6)?)
} else {
None
}
} else {
Some(p + 4 + u64::from(word & 2))
};
(key, i32::from(word & 3), p + 2)
};
let value = f.tag_value(flags, value_ptr)?;
Ok(Tag { key, value })
}
}
impl<'a, S: Source> Iterator for Tags<'a, S> {
type Item = Result<Tag<'a>>;
fn next(&mut self) -> Option<Self::Item> {
let p = self.next?;
self.steps += 1;
if self.steps > self.feature.library.limits.max_tags {
self.next = None;
return Some(Err(Error::Limit("tags")));
}
if p >= self.table {
if let Some(tag) = self.read_global(p) {
return Some(Ok(tag));
}
}
let result = self.read_fallback(p);
if result.is_err() {
self.next = None;
}
Some(result)
}
}
impl<S: Source> std::iter::FusedIterator for Tags<'_, S> {}
pub struct Coordinates<'a, S> {
feature: Feature<'a, S>,
window: ReadWindow<'a, S>,
p: u64,
remaining: u64,
current: Point,
first: Option<Point>,
close: bool,
done: bool,
}
impl<'a, S: Source> Coordinates<'a, S> {
#[cfg(feature = "way-checkpoints")]
pub(crate) fn stored_count(&self) -> u64 {
self.remaining
}
#[cfg(feature = "way-checkpoints")]
pub(crate) fn position(&self) -> u64 {
self.p
}
#[cfg(feature = "way-checkpoints")]
pub(crate) fn restarted(
feature: Feature<'a, S>,
p: u64,
current: Point,
remaining: u64,
) -> Self {
Self {
feature,
window: ReadWindow::new(&feature.library.source),
p,
remaining,
current,
first: None,
close: false,
done: false,
}
}
fn new(feature: Feature<'a, S>) -> Result<Self> {
if feature.kind() != FeatureType::Way {
return Err(Error::WrongFeatureType);
}
let mut p = feature.body()?;
let remaining = feature.library.source.varint(&mut p)?;
if remaining > feature.library.limits.max_coordinates {
return Err(Error::Limit("way coordinates"));
}
Ok(Self {
feature,
window: ReadWindow::new(&feature.library.source),
p,
remaining,
current: feature.bounds()?.min,
first: None,
close: feature.is_area(),
done: false,
})
}
fn read(&mut self) -> Result<Point> {
if let Some((x, y, used)) = self
.window
.record::<6, false>(self.p, self.feature.tile_end())
.and_then(short_coordinate_pair)
{
self.p += used;
return Ok(self.advance(x, y));
}
self.window.seek(self.p)?;
self.read_fallback()
}
fn read_fallback(&mut self) -> Result<Point> {
let s = &self.window;
let x = s.signed_varint(&mut self.p)?;
let y = s.signed_varint(&mut self.p)?;
self.feature.check(self.p - 1, 1)?;
let limit = i64::from(u32::MAX);
if !(-limit..=limit).contains(&x) || !(-limit..=limit).contains(&y) {
return Err(Error::invalid(
self.p,
"coordinate delta exceeds coordinate domain",
));
}
Ok(self.advance(x as i32, y as i32))
}
#[inline]
fn advance(&mut self, x: i32, y: i32) -> Point {
self.current.x = self.current.x.wrapping_add(x);
self.current.y = self.current.y.wrapping_add(y);
self.first.get_or_insert(self.current);
self.remaining -= 1;
self.current
}
pub(crate) fn collect_owned(mut self, capacity: usize) -> Result<Vec<Point>> {
let mut out = Vec::with_capacity(capacity);
while self.remaining != 0 {
self.window.seek(self.p)?;
let mut tail = self
.window
.tail(self.p, self.feature.tile_end())
.unwrap_or_default();
let original_len = tail.len();
while self.remaining != 0 {
let Some((x, y, used)) = tail.first_chunk::<6>().and_then(short_coordinate_pair)
else {
break;
};
self.current.x = self.current.x.wrapping_add(x);
self.current.y = self.current.y.wrapping_add(y);
self.remaining -= 1;
out.push(self.current);
tail = &tail[used as usize..];
}
let used = original_len - tail.len();
self.p += used as u64;
if self.remaining != 0 {
if used != 0 {
self.window.seek(self.p)?;
}
out.push(self.read_fallback()?);
}
}
if self.close {
if let Some(&first) = out.first() {
out.push(first);
}
}
Ok(out)
}
}
#[inline]
fn short_coordinate_pair(bytes: &[u8; 6]) -> Option<(i32, i32, u64)> {
fn read(bytes: &[u8]) -> Option<(u32, usize)> {
let &[a, b, c] = bytes.first_chunk::<3>()?;
if a < 128 {
return Some((u32::from(a), 1));
}
let low = u32::from(a & 127);
if b < 128 {
return Some((low | u32::from(b) << 7, 2));
}
if c < 128 {
return Some((low | u32::from(b & 127) << 7 | u32::from(c) << 14, 3));
}
None
}
let (x, x_len) = read(bytes)?;
let (y, y_len) = read(&bytes[x_len..])?;
Some((
zigzag_coordinate(x),
zigzag_coordinate(y),
(x_len + y_len) as u64,
))
}
fn zigzag_coordinate(n: u32) -> i32 {
((n >> 1) as i32) ^ -((n & 1) as i32)
}
impl<S: Source> Iterator for Coordinates<'_, S> {
type Item = Result<Point>;
fn size_hint(&self) -> (usize, Option<usize>) {
if self.done {
return (0, Some(0));
}
if self.remaining == 0 {
let closing = usize::from(self.close && self.first.is_some());
return (closing, Some(closing));
}
let upper = usize::try_from(self.remaining)
.ok()
.and_then(|n| n.checked_add(usize::from(self.close)));
(1, upper)
}
fn next(&mut self) -> Option<Self::Item> {
if self.done {
return None;
}
if self.remaining == 0 {
self.done = true;
return if self.close { self.first.map(Ok) } else { None };
}
let result = self.read();
if result.is_err() {
self.done = true;
}
Some(result)
}
}
impl<S: Source> std::iter::FusedIterator for Coordinates<'_, S> {}
#[derive(Debug)]
pub struct Member<'a, S> {
pub feature: Feature<'a, S>,
pub role: Cow<'a, str>,
}
pub struct Members<'a, S> {
owner: Feature<'a, S>,
next: Option<u64>,
role: Cow<'a, str>,
tip: i64,
tex: i64,
cached_foreign: Option<(u32, u64, u64, u64)>,
steps: u64,
}
impl<'a, S: Source> Members<'a, S> {
fn new(owner: Feature<'a, S>) -> Result<Self> {
if owner.kind() != FeatureType::Relation {
return Err(Error::WrongFeatureType);
}
let p = owner.body()?;
owner.check(p, 4)?;
let next = if owner.library.source.u32(p)? == 0 {
None
} else {
Some(p)
};
Ok(Self {
owner,
next,
role: Cow::Borrowed(""),
tip: 0x4000,
tex: 0x400,
cached_foreign: None,
steps: 0,
})
}
fn read(&mut self, start: u64) -> Result<Member<'a, S>> {
let owner = self.owner;
let lib = owner.library;
let s = &lib.source;
self.steps += 1;
if self.steps > lib.limits.max_members {
return Err(Error::Limit("relation members"));
}
owner.check(start, 2)?;
let narrow = s.u16(start)?;
let foreign = narrow & 2 != 0;
let width = if foreign && narrow & 16 == 0 { 2 } else { 4 };
owner.check(start, width)?;
let word = if width == 2 {
i32::from(narrow as i16)
} else {
s.i32(start)?
};
let mut p = start + width;
if foreign {
if word & 8 != 0 {
owner.check(p, 2)?;
let delta = s.u16(p)? as i16;
let delta = if delta & 1 != 0 {
owner.check(p, 4)?;
let d = s.i32(p)?;
p += 4;
d >> 1
} else {
p += 2;
i32::from(delta) >> 1
};
self.tip += i64::from(delta);
}
self.tex += i64::from(word >> 5);
}
if word & 4 != 0 {
owner.check(p, 2)?;
let role = s.u16(p)?;
if role & 1 != 0 {
self.role = lib.global_string(role >> 1)?;
p += 2;
} else {
owner.check(p, 4)?;
let target = add(p, (s.i32(p)? >> 1) as i64)?;
owner.check(target, 1)?;
self.role = owner.local_string(target)?;
p += 4;
}
}
let feature = if foreign {
let tip = u32::try_from(self.tip)
.map_err(|_| Error::invalid(start, "invalid foreign tile"))?;
let (tile, tile_end, exports) = match self.cached_foreign {
Some((cached_tip, tile, tile_end, exports)) if cached_tip == tip => {
(tile, tile_end, exports)
}
_ => {
let tile = lib.tile_page(tip)?;
let tile_end = tile + 4 + u64::from(s.u32(tile)? & 0x3fff_ffff);
let exports = s.relative(tile + 24, !0)?;
self.cached_foreign = Some((tip, tile, tile_end, exports));
(tile, tile_end, exports)
}
};
let tex = u32::try_from(self.tex)
.map_err(|_| Error::invalid(start, "invalid export index"))?;
let entry = exports
.checked_add(u64::from(tex) * 4)
.ok_or_else(|| Error::invalid(start, "export overflow"))?;
if entry < tile || entry + 4 > tile_end {
return Err(Error::invalid(entry, "export outside tile"));
}
Feature::at(lib, s.relative(entry, !0)?, tile, tile_end)?
} else {
Feature::at_source(
lib,
&lib.source,
add(start & !3, i64::from(word >> 3) * 4)?,
owner.tile,
)?
};
self.next = if word & 1 != 0 { None } else { Some(p) };
Ok(Member {
feature,
role: self.role.clone(),
})
}
}
impl<'a, S: Source> Iterator for Members<'a, S> {
type Item = Result<Member<'a, S>>;
fn next(&mut self) -> Option<Self::Item> {
let p = self.next?;
let result = self.read(p);
if result.is_err() {
self.next = None;
}
Some(result)
}
}
impl<S: Source> std::iter::FusedIterator for Members<'_, S> {}
#[cfg(test)]
mod compact_handle_tests;
#[cfg(test)]
mod coordinate_hints;
#[cfg(test)]
mod optimized_query_errors;
#[cfg(test)]
mod tag_iteration_errors;