Donner 0.5.1
Embeddable browser-grade SVG2 engine
Loading...
Searching...
No Matches
donner Namespace Reference

Top-level Donner namespace, which is split into different sub-namespaces such as donner::svg and donner::css. More...

Namespaces

namespace  parser
 Parsers for shared data types such as NumberParser and LengthParser.
namespace  css
 Donner CSS library, a standalone composable CSS parser.
namespace  svg
 Donner SVG library, which can load, manipulate and render SVG files.
namespace  xml
 XML parsing and document model support, top-level objects are donner::xml::XMLParser and donner::xml::XMLDocument.

Classes

struct  Box2
 A 2D axis-aligned bounding box. More...
class  ChunkedString
 ChunkedString is a small helper to accumulate multiple RcStringOrRef pieces, either as small appended fragments or single codepoints. More...
struct  CompileTimeMapTables
 Perfect-hash metadata used to resolve keys into storage slots. More...
struct  CompileTimeMapDiagnostics
 Diagnostics describing how a CompileTimeMap was constructed. More...
class  CompileTimeMap
 Compile-time associative container backed by a perfect hash layout. More...
class  DiagnosticRenderer
 Renders diagnostic messages with source context and caret/tilde indicators, similar to clang/rustc output. More...
class  ElementTraversalGenerator
 Selectors may need to traverse the tree in different ways to match, and this is abstracted away using C++20 coroutines. More...
class  Decompress
 A utility class for decompressing data. More...
struct  FileOffset
 Error context for a failed parse, such as the error reason, line, and character offset. More...
struct  SourceRange
 Holds a selection range for a region in the source text, as a half-open interval [start, end). More...
struct  Length
 Parses a CSS <length-percentage> type as defined by https://www.w3.org/TR/css-values-3/#typedef-length-percentage. More...
struct  MathConstants
 Contains a set of math constants for the specified type (float or double). More...
struct  MathConstants< float >
 Math constants for float. More...
struct  MathConstants< double >
 Math constants for double. More...
struct  QuadraticSolution
 Holds the solution of a quadratic equation, as returned by SolveQuadratic. More...
class  OptionalRef
 A class that simulates an optional reference to a constant object of type T. More...
struct  ParseDiagnostic
 A diagnostic message from a parser, with severity, source range, and human-readable reason. More...
class  ParseResult
 A parser result, which may contain a result of type T, or an error, or both. More...
class  ParseWarningSink
 Collects parse warnings during parsing. More...
struct  StrokeStyle
 Parameters for converting a stroked path to a filled outline. More...
class  Path
 Immutable 2D vector path. More...
class  PathBuilder
 Mutable builder for constructing immutable Path objects. More...
class  RcString
 A reference counted string, that is copy-on-write and implements the small-string optimization. More...
class  RcStringOrRef
 An in-transit type that can hold either an RcString or std::string_view, to enable transferring the RcString reference or also accepting a non-owning std::string_view from API surfaces. More...
struct  FontMetrics
 A container for font information relevant for computing font-relative lengths, per https://www.w3.org/TR/css-values/#font-relative-lengths. More...
struct  AbsoluteLengthMetrics
 A container with ratios for converting absolute lengths, such as "cm" or "in", see https://www.w3.org/TR/css-values/#absolute-lengths. More...
class  SmallVector
 A vector with small-size optimization. More...
struct  CaseInsensitiveCharTraits
 Type traits for case-insensitive string comparison, usable with algorithms that accept an STL std::char_traits. More...
class  StringUtils
 A collection of string utils, such as case-insensitive comparison and StartsWith/EndsWith. More...
struct  Transform2
 A 2D matrix representing an affine transformation. More...
class  Utf8
 Utility class for working with UTF-8 encoded strings. More...
struct  Vector2
 A 2D vector, (x, y). More...

Concepts

concept  ElementLike
 Concept for types that can be matched against a selector, such as a donner::svg::SVGElement.
concept  StringLike
 A concept for types that are string-like, i.e.

Typedefs

using Entity = entt::entity
 Entity type for the Registry, a std::uint32_t alias.
using Registry = entt::basic_registry<Entity, std::allocator<Entity>>
 Registry type for the SVG ECS, which is the entry point for storing all data.
using EntityHandle = entt::basic_handle<Registry>
 Convenience handle for a Entity with an attached Registry.
using Lengthd = Length<double>
 Shorthand for Length<double>.
Typedefs
using Box2d = Box2<double>
 Shorthand for Box2<double>.
using Transform2f = Transform2<float>
 Shorthand for Transform2<float>.
using Transform2d = Transform2<double>
 Shorthand for Transform2<double>.
using Vector2f = Vector2<float>
 Shorthand for Vector2<float>.
using Vector2d = Vector2<double>
 Shorthand for Vector2<double>.
using Vector2i = Vector2<int>
 Shorthand for Vector2<int>.

Enumerations

enum class  CompileTimeMapStatus {
  kOk ,
  kUsingFallbackHash ,
  kDuplicateKey ,
  kSeedSearchFailed ,
  kConstexprHashUnsupported
}
 Indicates the result of building a CompileTimeMap. More...
enum class  FillRule : uint8_t {
  NonZero ,
  EvenOdd
}
 The parsed result of the 'fill-rule' property, see: https://www.w3.org/TR/SVG2/painting.html#FillRuleProperty. More...
enum class  LengthUnit : uint8_t {
  None ,
  Percent ,
  Cm ,
  Mm ,
  Q ,
  In ,
  Pc ,
  Pt ,
  Px ,
  Em ,
  Ex ,
  Ch ,
  Rem ,
  Vw ,
  Vh ,
  Vmin ,
  Vmax
}
 The unit identifier for a length, corresponding to CSS unit identifiers. More...
enum class  DiagnosticSeverity : uint8_t {
  Warning ,
  Error
}
 Severity level for a parser diagnostic. More...
enum class  LineCap : uint8_t {
  Butt ,
  Round ,
  Square
}
 Line cap style for stroke endpoints. More...
enum class  LineJoin : uint8_t {
  Miter ,
  Round ,
  Bevel
}
 Line join style for stroke corners. More...
enum class  StringComparison : uint8_t {
  Default ,
  IgnoreCase
}
 String comparison options, e.g. case sensitivity. More...

Functions

Vector2d EvalQuadratic (const Vector2d &p0, const Vector2d &p1, const Vector2d &p2, double t)
 Evaluate a quadratic Bezier curve at parameter t using the standard basis expansion.
Vector2d EvalCubic (const Vector2d &p0, const Vector2d &p1, const Vector2d &p2, const Vector2d &p3, double t)
 Evaluate a cubic Bezier curve at parameter t using the standard basis expansion.
std::pair< std::array< Vector2d, 3 >, std::array< Vector2d, 3 > > SplitQuadratic (const Vector2d &p0, const Vector2d &p1, const Vector2d &p2, double t)
 Split a quadratic Bezier curve at parameter t using De Casteljau subdivision.
std::pair< std::array< Vector2d, 4 >, std::array< Vector2d, 4 > > SplitCubic (const Vector2d &p0, const Vector2d &p1, const Vector2d &p2, const Vector2d &p3, double t)
 Split a cubic Bezier curve at parameter t using De Casteljau subdivision.
void ApproximateCubicWithQuadratics (const Vector2d &p0, const Vector2d &p1, const Vector2d &p2, const Vector2d &p3, double tolerance, std::vector< Vector2d > &out)
 Approximate a cubic Bezier curve as a sequence of quadratic Bezier curves within a given tolerance.
SmallVector< double, 1 > QuadraticYExtrema (const Vector2d &p0, const Vector2d &p1, const Vector2d &p2)
 Find parameter values where the Y-derivative is zero for a quadratic Bezier curve.
SmallVector< double, 2 > CubicYExtrema (const Vector2d &p0, const Vector2d &p1, const Vector2d &p2, const Vector2d &p3)
 Find parameter values where the Y-derivative is zero for a cubic Bezier curve.
Box2d QuadraticBounds (const Vector2d &p0, const Vector2d &p1, const Vector2d &p2)
 Compute the tight axis-aligned bounding box of a quadratic Bezier curve.
Box2d CubicBounds (const Vector2d &p0, const Vector2d &p1, const Vector2d &p2, const Vector2d &p3)
 Compute the tight axis-aligned bounding box of a cubic Bezier curve.
constexpr uint64_t mixHash (uint64_t baseHash, std::uint32_t seed)
 Mix a base hash value with a seed to produce a new hash. Used to construct perfect-hash bucket seeds during CompileTimeMap construction.
template<typename Key>
constexpr bool supportsConstexprHash ()
 Returns true when the provided key type can be hashed in a constexpr context by constexprHashValue.
template<typename Key>
constexpr uint64_t constexprHashValue (const Key &key)
 Compute a constexpr-friendly hash of key for supported key types.
template<typename Key, std::size_t N, typename KeyEqual>
constexpr bool hasDuplicateKeys (const std::array< Key, N > &keys, KeyEqual keyEqual)
 Returns true when the provided keys contain duplicates.
auto operator<=> (Entity lhs, Entity rhs)
 Compare two Entity values.
template<ElementLike T>
ElementTraversalGenerator< T > singleElementGenerator (T element)
 A generator that yields a single element, if it exists.
template<ElementLike T>
ElementTraversalGenerator< T > parentsGenerator (T element)
 A generator that yields all parents of an element, repeatedly following parentElement() until reaching the root.
template<ElementLike T>
ElementTraversalGenerator< T > previousSiblingsGenerator (T element)
 A generator that yields all siblings of an element, in reverse order.
template<ElementLike T>
ElementTraversalGenerator< T > allChildrenRecursiveGenerator (T element)
 A generator that yields all children of an element recursively with pre-order traversal.
ParseResult< std::vector< uint8_t > > DecodeBase64Data (std::string_view base64String)
 Decode a base64-encoded string into a byte array.
std::string EncodeBase64Data (std::span< const uint8_t > data)
 Encode a byte array into a base64-encoded string.
std::vector< uint8_t > UrlDecode (std::string_view urlEncodedString)
 Decode a URL-encoded string into a byte array, translating XX sequences into the corresponding byte value.
void InstallFailureSignalHandler ()
 Install signal handlers for crash signals (SIGSEGV, SIGABRT, SIGFPE, SIGILL, SIGBUS, SIGTRAP).
std::ostream & operator<< (std::ostream &os, FillRule value)
 Ostream output operator for FillRule enum, outputs the CSS value.
std::ostream & operator<< (std::ostream &os, LengthUnit unit)
 OStream output operator, writes the CSS unit identifier to the stream, e.g. % or px.
float NarrowToFloat (double from)
 Semantically represent a narrowing conversion, such as converting a double to a float, to make the conversion more visible.
template<typename T>
const T & Min (const T &a, const T &b)
 Returns minimum of the provided values.
template<typename T, typename... Args>
const T & Min (const T &a, const T &b, Args &&... args)
 Returns minimum of the provided values.
template<typename T>
const T & Max (const T &a, const T &b)
 Returns maximum of the provided values.
template<typename T, typename... Args>
const T & Max (const T &a, const T &b, Args &&... args)
 Returns maximum of the provided values.
float Abs (float a)
 Returns the absolute value of the number.
double Abs (double a)
 Returns the absolute value of the number.
template<typename T, typename = std::enable_if<std::is_integral<T>::value && std::is_signed<T>::value>>
Abs (T a)
 Returns the absolute value of the number.
template<typename T, typename = std::enable_if<std::is_floating_point<T>::value>>
Round (T orig)
 Round a floating point value to an integer.
template<typename T>
Lerp (T a, T b, const float t)
 Returns linear interpolation of a and b with ratio t.
template<typename T>
const T Clamp (T value, T low, T high)
 Clamps a value between low and high.
template<typename T>
bool NearEquals (T a, T b, T tolerance=std::numeric_limits< T >::epsilon())
 Returns if a equals b, taking possible rounding errors into account.
template<typename T>
bool NearZero (T a, T tolerance=std::numeric_limits< T >::epsilon())
 Returns if a equals zero, taking rounding errors into account.
template<typename T, typename = std::enable_if<std::is_integral<T>::value>>
bool InRange (T var, T start, T end)
 Test if a variable is in a specific range, using an optimized technique that requires only one branch.
template<typename T>
QuadraticSolution< T > SolveQuadratic (T a, T b, T c)
 Solve a quadratic equation.
std::ostream & operator<< (std::ostream &os, DiagnosticSeverity severity)
 Ostream output operator for DiagnosticSeverity.
std::ostream & operator<< (std::ostream &os, LineCap cap)
 Ostream output operator for LineCap.
std::ostream & operator<< (std::ostream &os, LineJoin join)
 Ostream output operator for LineJoin.
RcString toSVGTransformString (const Transform2d &transform)
 Serialize a Transform2d to its canonical SVG transform attribute text, decomposing to the simplest form when possible:

Detailed Description

Top-level Donner namespace, which is split into different sub-namespaces such as donner::svg and donner::css.


Class Documentation

◆ donner::CompileTimeMapTables

struct donner::CompileTimeMapTables
template<std::size_t N>
struct donner::CompileTimeMapTables< N >

Perfect-hash metadata used to resolve keys into storage slots.

Collaboration diagram for donner::CompileTimeMapTables< N >:
[legend]
Class Members
uint32_t bucketCount = 0 Number of buckets used by the first-level table; zero enables fallback lookup.
array< uint32_t, N > primary {} First-level table storing direct indices or bucket seeds.
array< uint32_t, N > secondary {} Secondary slot table addressed with the bucket seed and key hash.

◆ donner::CompileTimeMapDiagnostics

struct donner::CompileTimeMapDiagnostics

Diagnostics describing how a CompileTimeMap was constructed.

Class Members
bool constexprHashSupported = true Whether constexpr hashing was available for the provided key type.
uint32_t failedBucket = kEmptySlot Index of the bucket that failed to place, or kEmptySlot when successful.
uint32_t maxBucketSize = 0 Largest bucket size observed while building the table.
uint32_t seedAttempts = 0 Total seed attempts across all buckets.

◆ donner::MathConstants

struct donner::MathConstants
template<typename T>
struct donner::MathConstants< T >

Contains a set of math constants for the specified type (float or double).

Template Parameters
T

◆ donner::QuadraticSolution

struct donner::QuadraticSolution
template<typename T>
struct donner::QuadraticSolution< T >

Holds the solution of a quadratic equation, as returned by SolveQuadratic.

Template Parameters
T
Collaboration diagram for donner::QuadraticSolution< T >:
[legend]
Class Members
bool hasSolution = false True if the equation has solutions.
array< T, 2 > solution Solutions to the equation, valid if hasSolution is true.

Typedef Documentation

◆ Entity

using donner::Entity = entt::entity

Entity type for the Registry, a std::uint32_t alias.

Entity type for the Registry.

This is a core type for the the ECS, and is used to identify entities in the Registry.

See also
Entity Component System (ECS)
Registry

◆ EntityHandle

typedef entt::basic_handle< Registry > donner::EntityHandle = entt::basic_handle<Registry>

Convenience handle for a Entity with an attached Registry.

Forward declaration of EntityHandle.

Allows calling functions typically on Registry without having to pass around two values.

◆ Registry

using donner::Registry = entt::basic_registry<Entity, std::allocator<Entity>>

Registry type for the SVG ECS, which is the entry point for storing all data.

Forward declaration of Registry.

It is used to create new entities:

Registry registry;
const Entity entity = registry.create();
entt::basic_registry< Entity, std::allocator< Entity > > Registry
Registry type for the SVG ECS, which is the entry point for storing all data.
Definition EcsRegistry.h:51
entt::entity Entity
Entity type for the Registry, a std::uint32_t alias.
Definition EcsRegistry.h:21

Attach or remove data classes to entities:

registry.emplace<components::TreeComponent>(entity, "unknown");
Stores the tree structure for an XML element, such as the parent, children, and siblings.
Definition TreeComponent.h:17
void remove(Registry &registry)
Remove this node from its parent, if it has one.

Store global objects (singleton-like):

registry.ctx().emplace<components::RenderingContext>(registry));
const Entity root = registry.ctx().get<components::RenderingContext>().rootEntity;
See also
Entity Component System (ECS)

Enumeration Type Documentation

◆ CompileTimeMapStatus

enum class donner::CompileTimeMapStatus
strong

Indicates the result of building a CompileTimeMap.

Enumerator
kOk 

Perfect-hash tables were constructed successfully.

kUsingFallbackHash 

Map is available but using the linear fallback path instead of perfect hashing.

kDuplicateKey 

Duplicate keys were detected in the input payload.

kSeedSearchFailed 

Perfect-hash seed search failed; map is available via fallback lookup.

kConstexprHashUnsupported 

Compile-time hashing is unsupported for this key type when evaluated constexpr.

◆ DiagnosticSeverity

enum class donner::DiagnosticSeverity : uint8_t
strong

Severity level for a parser diagnostic.

Enumerator
Warning 

Non-fatal issue; parsing continues.

Error 

Fatal issue; parsing may stop or produce partial results.

◆ FillRule

enum class donner::FillRule : uint8_t
strong

The parsed result of the 'fill-rule' property, see: https://www.w3.org/TR/SVG2/painting.html#FillRuleProperty.

Enumerator
NonZero 

[DEFAULT] Determines "insideness" of a point by counting crossings of a ray drawn from that point to infinity and path segments. If crossings is non-zero, the point is inside, else outside.

EvenOdd 

Determines "insideness" of a point by counting the number of path segments from the shape crossed by a ray drawn from that point to infinity. If count is odd, point is inside, else outside.

◆ LengthUnit

enum class donner::LengthUnit : uint8_t
strong

The unit identifier for a length, corresponding to CSS unit identifiers.

See https://www.w3.org/TR/css-values-3/#lengths for definitions.

Enumerator
None 

Unitless.

Percent 

Percentage, using the '%' symbol.

Cm 

Centimeters, 1cm = 96px/2.54.

Mm 

Millimeters, 1mm = 1/10th of 1cm.

Quarter-millimeters, 1Q = 1/40th of 1cm.

In 

Inches, 1in = 2.54cm = 96px.

Pc 

Picas, 1pc = 1/6th of 1in.

Pt 

Points, 1pt = 1/72nd of 1in.

Px 

Pixels, 1px = 1/96th of 1in.

Em 

Font size, 1em = current font size.

Ex 

x-height of the current font, 1ex = x-height of current font.

Ch 

Width of the glyph '0' in the current font, 1ch = width of '0' in current font.

Rem 

Root font size, 1rem = font size of the root element.

Vw 

Viewport width, 1vw = 1% of viewport width.

Vh 

Viewport height, 1vh = 1% of viewport height.

Vmin 

Smaller of viewport width and height, 1vmin = 1% of smaller of viewport width and height.

Vmax 

Larger of viewport width and height, 1vmax = 1% of larger of viewport width and height.

◆ LineCap

enum class donner::LineCap : uint8_t
strong

Line cap style for stroke endpoints.

Enumerator
Butt 

The stroke is squared off at the endpoint of the path.

Round 

The stroke is rounded at the endpoint of the path.

Square 

The stroke extends beyond the endpoint by half the stroke width and is squared off.

◆ LineJoin

enum class donner::LineJoin : uint8_t
strong

Line join style for stroke corners.

Enumerator
Miter 

The outer edges of the strokes are extended until they meet at a sharp point.

Round 

The corners of the stroke are rounded using a circular arc.

Bevel 

A triangular shape fills the area between the two stroked segments.

◆ StringComparison

enum class donner::StringComparison : uint8_t
strong

String comparison options, e.g. case sensitivity.

Enumerator
Default 

The default case-sensitive string comparison.

IgnoreCase 

Case-insensitive string comparison.

Function Documentation

◆ constexprHashValue()

template<typename Key>
uint64_t donner::constexprHashValue ( const Key & key)
constexpr

Compute a constexpr-friendly hash of key for supported key types.

Returns uint64_t to ensure consistent hashing on both 32-bit and 64-bit platforms.

◆ DecodeBase64Data()

ParseResult< std::vector< uint8_t > > donner::DecodeBase64Data ( std::string_view base64String)

Decode a base64-encoded string into a byte array.

If the string is not valid base64, an error is returned.

Parameters
base64StringThe base64-encoded string to decode.
Returns
The decoded byte array, or an error if the input is not valid base64.

◆ EncodeBase64Data()

std::string donner::EncodeBase64Data ( std::span< const uint8_t > data)

Encode a byte array into a base64-encoded string.

Parameters
dataThe byte array to encode.
Returns
The base64-encoded string.

◆ InRange()

template<typename T, typename = std::enable_if<std::is_integral<T>::value>>
bool donner::InRange ( T var,
T start,
T end )
inline

Test if a variable is in a specific range, using an optimized technique that requires only one branch.

Some compilers do this automatically.

Example:

if (InRange(var, 'a', 'z')) // ...
bool InRange(T var, T start, T end)
Test if a variable is in a specific range, using an optimized technique that requires only one branch...
Definition MathUtils.h:219

◆ InstallFailureSignalHandler()

void donner::InstallFailureSignalHandler ( )

Install signal handlers for crash signals (SIGSEGV, SIGABRT, SIGFPE, SIGILL, SIGBUS, SIGTRAP).

When a crash signal is received, the handler prints a stack trace to stderr and then re-raises the signal so the default handler can produce a core dump.

◆ Lerp()

template<typename T>
T donner::Lerp ( T a,
T b,
const float t )
inline

Returns linear interpolation of a and b with ratio t.

Returns
a if t == 0, b if t == 1, and the linear interpolation else.

◆ mixHash()

uint64_t donner::mixHash ( uint64_t baseHash,
std::uint32_t seed )
constexpr

Mix a base hash value with a seed to produce a new hash. Used to construct perfect-hash bucket seeds during CompileTimeMap construction.

Uses uint64_t explicitly to ensure correct behavior on 32-bit platforms (e.g., WASM) where std::size_t is 32 bits and the >> 33 shift would be undefined behavior.

◆ NarrowToFloat()

float donner::NarrowToFloat ( double from)
inline

Semantically represent a narrowing conversion, such as converting a double to a float, to make the conversion more visible.

For example: const float f = NarrowToFloat(1.0);

◆ parentsGenerator()

template<ElementLike T>
ElementTraversalGenerator< T > donner::parentsGenerator ( T element)

A generator that yields all parents of an element, repeatedly following parentElement() until reaching the root.

Parameters
elementThe element to start from, which is not yielded.

◆ previousSiblingsGenerator()

template<ElementLike T>
ElementTraversalGenerator< T > donner::previousSiblingsGenerator ( T element)

A generator that yields all siblings of an element, in reverse order.

This repeatedly follows previousSibling().

Parameters
elementThe element to start from, which is not yielded.

◆ singleElementGenerator()

template<ElementLike T>
ElementTraversalGenerator< T > donner::singleElementGenerator ( T element)

A generator that yields a single element, if it exists.

Parameters
elementThe element to yield. If this is std::nullopt, the generator will yield nothing.

◆ SolveQuadratic()

template<typename T>
QuadraticSolution< T > donner::SolveQuadratic ( T a,
T b,
T c )

Solve a quadratic equation.

\( a x^2 + b x + c = 0 \)

Parameters
aFirst coefficient.
bSecond coefficient.
cThird coefficient.
Returns
QuadraticSolution, containing 0-2 solutions.

◆ toSVGTransformString()

RcString donner::toSVGTransformString ( const Transform2d & transform)
inline

Serialize a Transform2d to its canonical SVG transform attribute text, decomposing to the simplest form when possible:

  • Identity → empty string
  • Pure translate ([1 0 0 1 e f]) → translate(e, f), or translate(e) when f == 0
  • Pure uniform scale ([s 0 0 s 0 0]) → scale(s)
  • Pure non-uniform scale ([sx 0 0 sy 0 0]) → scale(sx, sy)
  • Pure rotation around origin ([cos -sin sin cos 0 0]) → rotate(deg)
  • General → matrix(a, b, c, d, e, f)

Numbers are emitted via {} (integer-valued doubles) or {:g} (fractional) so the output is the shortest form that round-trips. Arguments are comma-separated with a space after the comma, matching the canonical CSS transform syntax.

Round-trips with donner::svg::parser::TransformParser::Parse for every shape above.

Parameters
transformTransform to serialize.
Returns
Canonical SVG transform text (empty string for identity).

◆ UrlDecode()

std::vector< uint8_t > donner::UrlDecode ( std::string_view urlEncodedString)

Decode a URL-encoded string into a byte array, translating XX sequences into the corresponding byte value.

See also
https://url.spec.whatwg.org/#percent-encoded-bytes
Parameters
urlEncodedStringThe URL-encoded string to decode.
Returns
A vector of decoded byte values.