Skip to main content

graphrt_core/
graph.rs

1//! Compiled, validated, immutable graph.
2//!
3//! A [`Graph`] is built once from a [`Workflow`] document and shared (via
4//! `Arc`) by every run and every container frame. Runtime state (node and
5//! edge status) lives in the engine's per-frame state, never in the graph, so
6//! a graph can execute any number of runs concurrently.
7//!
8//! Each node belongs to exactly one *scope*: the root scope, or the body of a
9//! container node (iteration / loop). Edges never cross scopes, and every
10//! scope must be acyclic and have exactly one entry node.
11
12use std::collections::{HashMap, HashSet, VecDeque};
13use std::fmt;
14use std::hash::{Hash, Hasher};
15use std::sync::Arc;
16
17use crate::dsl::{NodeDoc, NodePolicy, Workflow};
18use crate::node::{ConfigError, Node, NodeRole, Registry};
19
20/// Default edge handle for non-branch nodes.
21pub const SOURCE_HANDLE: &str = "source";
22/// Handle taken when a node with the `fail-branch` strategy fails.
23pub const FAIL_BRANCH: &str = "fail-branch";
24
25/// Index of a node in [`Graph::nodes`].
26pub type NodeIx = usize;
27/// Index of an edge in [`Graph::edges`].
28pub type EdgeIx = usize;
29
30/// A compiled node.
31pub struct GraphNode {
32    pub id: Arc<str>,
33    /// Shared with every `NodeStarted` event, so starting a node copies no strings.
34    pub kind: Arc<str>,
35    pub title: Arc<str>,
36    /// Owning container, `None` for the root scope.
37    pub parent: Option<NodeIx>,
38    pub policy: NodePolicy,
39    pub role: NodeRole,
40    pub node: Arc<dyn Node>,
41    /// The source document (kept for introspection and tooling).
42    pub doc: NodeDoc,
43}
44
45impl fmt::Debug for GraphNode {
46    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47        f.debug_struct("GraphNode").field("id", &self.id).field("kind", &self.kind).field("role", &self.role).finish()
48    }
49}
50
51/// A compiled edge.
52#[derive(Clone, Debug, PartialEq, Eq)]
53pub struct GraphEdge {
54    pub id: Arc<str>,
55    pub source: NodeIx,
56    pub target: NodeIx,
57    pub handle: Arc<str>,
58}
59
60/// One scope: the root graph or a container body.
61#[derive(Clone, Debug, PartialEq, Eq)]
62pub struct Scope {
63    /// Container node owning this scope, `None` for the root.
64    pub owner: Option<NodeIx>,
65    /// Entry node.
66    pub entry: NodeIx,
67    /// Nodes in this scope, in topological order.
68    pub nodes: Vec<NodeIx>,
69}
70
71/// Graph construction / validation error.
72#[derive(Debug, thiserror::Error)]
73#[non_exhaustive]
74pub enum GraphError {
75    #[error(transparent)]
76    Config(#[from] ConfigError),
77    #[error("duplicate node id `{0}`")]
78    DuplicateNode(String),
79    #[error("duplicate edge id `{0}`")]
80    DuplicateEdge(String),
81    #[error("edge `{edge}` references unknown node `{node}`{}", did_you_mean(.suggestion))]
82    MissingNode { edge: String, node: String, suggestion: Option<String> },
83    #[error("node `{node}` references unknown parent `{parent}`{}", did_you_mean(.suggestion))]
84    MissingParent { node: String, parent: String, suggestion: Option<String> },
85    #[error("node `{0}` has a parent that is not a container node")]
86    ParentNotContainer(String),
87    #[error("container nesting cycle at node `{0}`")]
88    ParentCycle(String),
89    #[error("edge `{edge}` crosses scopes (`{source_node}` -> `{target}`)")]
90    CrossScopeEdge { edge: String, source_node: String, target: String },
91    #[error("cycle detected in scope `{scope}` involving node `{node}`")]
92    Cycle { scope: String, node: String },
93    #[error("scope `{scope}` has no entry node")]
94    NoEntry { scope: String },
95    #[error("scope `{scope}` has multiple entry nodes: {nodes:?}")]
96    MultipleEntries { scope: String, nodes: Vec<String> },
97    #[error("graph has no nodes")]
98    Empty,
99    #[error("workflow cannot be serialized: {0}")]
100    Unserializable(String),
101    #[error("invalid node id `{id}`: {reason}")]
102    InvalidNodeId { id: String, reason: String },
103    #[error(
104        "node `{node}` references `{selector}`, but no node or variable namespace `{namespace}` exists{}",
105        did_you_mean(.suggestion)
106    )]
107    UnknownReference { node: String, selector: String, namespace: String, suggestion: Option<String> },
108    /// A config field the node kind's catalog schema does not allow, or a
109    /// required one that is missing (strict nodes only).
110    #[error("node `{node}`: {message}")]
111    InvalidField { node: String, path: String, message: String },
112    /// An edge whose handle the source node never selects.
113    #[error("edge `{edge}`: {message}")]
114    UnknownHandle { edge: String, message: String },
115}
116
117use crate::validate::did_you_mean;
118
119/// Namespaces that are not node ids.
120pub(crate) const RESERVED_NAMESPACES: &[&str] = &[crate::pool::SYS, crate::pool::ENV, crate::pool::CONVERSATION];
121
122pub(crate) fn validate_node_id(id: &str) -> Result<(), GraphError> {
123    let reason = if id.is_empty() {
124        Some("must not be empty")
125    } else if RESERVED_NAMESPACES.contains(&id) {
126        Some("is a reserved variable namespace")
127    } else if id.contains('.') {
128        Some("must not contain `.` (it separates selector parts)")
129    } else if id.chars().any(char::is_whitespace) {
130        Some("must not contain whitespace")
131    } else {
132        None
133    };
134    match reason {
135        Some(reason) => Err(GraphError::InvalidNodeId { id: id.to_owned(), reason: reason.to_owned() }),
136        None => Ok(()),
137    }
138}
139
140/// An executable graph.
141pub struct Graph {
142    nodes: Vec<GraphNode>,
143    edges: Vec<GraphEdge>,
144    index: HashMap<Arc<str>, NodeIx>,
145    outgoing: Vec<Vec<EdgeIx>>,
146    incoming: Vec<Vec<EdgeIx>>,
147    scopes: HashMap<Option<NodeIx>, Scope>,
148    warnings: Vec<String>,
149    /// Computed on first use: only snapshots, run records and traces need it, and
150    /// hashing the canonical document is a large share of loading big workflows.
151    fingerprint: std::sync::OnceLock<String>,
152    workflow: Workflow,
153}
154
155impl fmt::Debug for Graph {
156    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
157        f.debug_struct("Graph")
158            .field("nodes", &self.nodes.len())
159            .field("edges", &self.edges.len())
160            .field("fingerprint", &self.fingerprint.get())
161            .finish()
162    }
163}
164
165impl Graph {
166    /// Build and validate a graph from a workflow document.
167    pub fn build(workflow: Workflow, registry: &Registry) -> Result<Self, GraphError> {
168        Self::build_inner(workflow, registry, None)
169    }
170
171    /// [`Graph::build`] for a document the validator already checked: `checked`
172    /// holds the node built from each document node, in order, after its fields
173    /// were checked against the catalog. Reusing them avoids constructing every
174    /// node and walking every config schema twice, which made loading large
175    /// workflows several times slower.
176    pub(crate) fn build_checked(
177        workflow: Workflow,
178        registry: &Registry,
179        checked: Vec<Arc<dyn Node>>,
180    ) -> Result<Self, GraphError> {
181        Self::build_inner(workflow, registry, Some(checked))
182    }
183
184    fn build_inner(
185        workflow: Workflow,
186        registry: &Registry,
187        checked: Option<Vec<Arc<dyn Node>>>,
188    ) -> Result<Self, GraphError> {
189        let docs = &workflow.graph.nodes;
190        // Only a complete set of pre-built nodes can stand in for building them here.
191        let mut checked = checked.filter(|nodes| nodes.len() == docs.len()).map(Vec::into_iter);
192        if docs.is_empty() {
193            return Err(GraphError::Empty);
194        }
195
196        // Nodes.
197        let mut index: HashMap<Arc<str>, NodeIx> = HashMap::with_capacity(docs.len());
198        for (ix, doc) in docs.iter().enumerate() {
199            validate_node_id(&doc.id)?;
200            if index.insert(Arc::from(doc.id.as_str()), ix).is_some() {
201                return Err(GraphError::DuplicateNode(doc.id.clone()));
202            }
203        }
204        let mut nodes = Vec::with_capacity(docs.len());
205        for doc in docs {
206            let parent = match &doc.parent {
207                Some(p) => Some(*index.get(p.as_str()).ok_or_else(|| GraphError::MissingParent {
208                    node: doc.id.clone(),
209                    parent: p.clone(),
210                    suggestion: crate::validate::suggest(p, docs.iter().map(|d| d.id.as_str())),
211                })?),
212                None => None,
213            };
214            let node = match checked.as_mut().and_then(Iterator::next) {
215                Some(node) => node,
216                None => {
217                    let node = registry.build(doc)?;
218                    if doc.strict {
219                        check_fields(doc, registry)?;
220                    }
221                    node
222                }
223            };
224            nodes.push(GraphNode {
225                id: Arc::from(doc.id.as_str()),
226                kind: Arc::from(doc.kind.as_str()),
227                title: Arc::from(doc.label()),
228                parent,
229                policy: doc.policy.clone(),
230                role: node.role(),
231                node,
232                doc: doc.clone(),
233            });
234        }
235
236        // Parents must be containers and nesting must be acyclic.
237        for (ix, n) in nodes.iter().enumerate() {
238            if let Some(p) = n.parent
239                && nodes.get(p).map(|pn| pn.role) != Some(NodeRole::Container)
240            {
241                return Err(GraphError::ParentNotContainer(n.id.to_string()));
242            }
243            let mut seen = HashSet::new();
244            let mut cur = Some(ix);
245            while let Some(c) = cur {
246                if !seen.insert(c) {
247                    return Err(GraphError::ParentCycle(n.id.to_string()));
248                }
249                cur = nodes.get(c).and_then(|x| x.parent);
250            }
251        }
252
253        // Edges.
254        let mut edges = Vec::with_capacity(workflow.graph.edges.len());
255        let mut dead_edges = Vec::new();
256        let mut edge_ids = HashSet::new();
257        let mut outgoing = vec![Vec::new(); nodes.len()];
258        let mut incoming = vec![Vec::new(); nodes.len()];
259        for (i, e) in workflow.graph.edges.iter().enumerate() {
260            let id: Arc<str> = Arc::from(e.id.clone().unwrap_or_else(|| format!("{}-{}-{i}", e.source, e.target)));
261            if !edge_ids.insert(id.clone()) {
262                return Err(GraphError::DuplicateEdge(id.to_string()));
263            }
264            let lookup = |n: &str| {
265                index.get(n).copied().ok_or_else(|| GraphError::MissingNode {
266                    edge: id.to_string(),
267                    node: n.to_owned(),
268                    suggestion: crate::validate::suggest(n, docs.iter().map(|d| d.id.as_str())),
269                })
270            };
271            let source = lookup(&e.source)?;
272            let target = lookup(&e.target)?;
273            let (sp, tp) = (nodes.get(source).and_then(|n| n.parent), nodes.get(target).and_then(|n| n.parent));
274            if sp != tp {
275                return Err(GraphError::CrossScopeEdge {
276                    edge: id.to_string(),
277                    source_node: e.source.clone(),
278                    target: e.target.clone(),
279                });
280            }
281            let handle = e.handle.as_deref().filter(|h| !h.is_empty()).unwrap_or(SOURCE_HANDLE);
282            if let Some(n) = nodes.get(source) {
283                let descriptor = registry.descriptor_ref(&n.doc.kind);
284                if let Some(message) = crate::validate::dead_fail_branch(&n.doc, handle) {
285                    dead_edges.push(message);
286                }
287                if let Some(allowed) = crate::validate::allowed_handles(n.node.as_ref(), descriptor)
288                    && !allowed.iter().any(|h| h == handle)
289                {
290                    let mut message = crate::validate::handle_message(&n.doc, handle, &allowed);
291                    message
292                        .push_str(&did_you_mean(&crate::validate::suggest(handle, allowed.iter().map(String::as_str))));
293                    return Err(GraphError::UnknownHandle { edge: id.to_string(), message });
294                }
295            }
296            let ex = edges.len();
297            edges.push(GraphEdge { id, source, target, handle: Arc::from(handle) });
298            if let Some(o) = outgoing.get_mut(source) {
299                o.push(ex);
300            }
301            if let Some(inc) = incoming.get_mut(target) {
302                inc.push(ex);
303            }
304        }
305
306        // Scopes.
307        let mut members: HashMap<Option<NodeIx>, Vec<NodeIx>> = HashMap::new();
308        for (ix, n) in nodes.iter().enumerate() {
309            members.entry(n.parent).or_default().push(ix);
310        }
311        // Containers without children still get an (invalid) scope check below.
312        for (ix, n) in nodes.iter().enumerate() {
313            if n.role == NodeRole::Container {
314                members.entry(Some(ix)).or_default();
315            }
316        }
317
318        let mut warnings = dead_edges;
319        let mut scopes = HashMap::new();
320        for (owner, scope_nodes) in members {
321            let scope_name =
322                owner.and_then(|o| nodes.get(o)).map(|n| n.id.to_string()).unwrap_or_else(|| "root".into());
323            let entry = find_entry(&nodes, &incoming, owner, &scope_nodes, &scope_name)?;
324            let order = topo_order(&scope_nodes, &outgoing, &incoming, &edges, &nodes, &scope_name)?;
325            // Reachability from the entry: unreachable nodes never run.
326            let reachable = reachable_from(entry, &outgoing, &edges);
327            for &ix in &scope_nodes {
328                if !reachable.contains(&ix)
329                    && let Some(n) = nodes.get(ix)
330                {
331                    warnings.push(format!("node `{}` is not reachable from the entry of scope `{scope_name}`", n.id));
332                }
333            }
334            scopes.insert(owner, Scope { owner, entry, nodes: order });
335        }
336
337        validate_references(&nodes, &index, &mut warnings)?;
338
339        let fingerprint = std::sync::OnceLock::new();
340        Ok(Self { nodes, edges, index, outgoing, incoming, scopes, warnings, fingerprint, workflow })
341    }
342
343    /// Parse (JSON or YAML) and build in one step.
344    pub fn from_text(text: &str, registry: &Registry) -> Result<Self, crate::Error> {
345        let wf = Workflow::parse(text)?;
346        Ok(Self::build(wf, registry)?)
347    }
348
349    pub fn nodes(&self) -> &[GraphNode] {
350        &self.nodes
351    }
352
353    pub fn edges(&self) -> &[GraphEdge] {
354        &self.edges
355    }
356
357    pub fn node(&self, ix: NodeIx) -> Option<&GraphNode> {
358        self.nodes.get(ix)
359    }
360
361    pub fn edge(&self, ix: EdgeIx) -> Option<&GraphEdge> {
362        self.edges.get(ix)
363    }
364
365    /// Look up a node index by id.
366    pub fn index_of(&self, id: &str) -> Option<NodeIx> {
367        self.index.get(id).copied()
368    }
369
370    pub fn node_by_id(&self, id: &str) -> Option<&GraphNode> {
371        self.index_of(id).and_then(|ix| self.nodes.get(ix))
372    }
373
374    pub fn outgoing(&self, ix: NodeIx) -> &[EdgeIx] {
375        self.outgoing.get(ix).map(Vec::as_slice).unwrap_or_default()
376    }
377
378    pub fn incoming(&self, ix: NodeIx) -> &[EdgeIx] {
379        self.incoming.get(ix).map(Vec::as_slice).unwrap_or_default()
380    }
381
382    /// The root scope.
383    pub fn root_scope(&self) -> Option<&Scope> {
384        self.scopes.get(&None)
385    }
386
387    /// The body scope of a container node.
388    pub fn scope_of(&self, container: NodeIx) -> Option<&Scope> {
389        self.scopes.get(&Some(container))
390    }
391
392    /// Whether `ix` is (transitively) inside container `ancestor`.
393    pub fn is_descendant(&self, ix: NodeIx, ancestor: NodeIx) -> bool {
394        let mut cur = self.nodes.get(ix).and_then(|n| n.parent);
395        while let Some(c) = cur {
396            if c == ancestor {
397                return true;
398            }
399            cur = self.nodes.get(c).and_then(|n| n.parent);
400        }
401        false
402    }
403
404    /// Non-fatal findings (e.g. unreachable nodes).
405    pub fn warnings(&self) -> &[String] {
406        &self.warnings
407    }
408
409    /// Stable fingerprint of the source document, used to validate snapshots.
410    ///
411    /// Computed on first call and cached. A workflow document always serializes
412    /// (string keys only); should that ever fail, the fingerprint is derived from
413    /// the error text instead, which still never matches a real document's.
414    pub fn fingerprint(&self) -> &str {
415        self.fingerprint.get_or_init(|| {
416            fingerprint(&self.workflow).unwrap_or_else(|error| fnv_hex(format!("unserializable: {error}").as_bytes()))
417        })
418    }
419
420    /// The source document.
421    pub fn workflow(&self) -> &Workflow {
422        &self.workflow
423    }
424}
425
426/// Check every selector a node declares in [`Node::inputs`]:
427///
428/// - its namespace must be a reserved namespace (`sys`, `env`, `conversation`)
429///   or a node id — otherwise the build fails, so typos surface at load time
430///   instead of silently resolving to null at run time;
431/// - a referenced node should be visible: in the same scope or an enclosing
432///   one (including the enclosing containers themselves), or inside the
433///   referencing container's own body. Other references only produce a warning,
434///   because they resolve to null at run time.
435fn validate_references(
436    nodes: &[GraphNode],
437    index: &HashMap<Arc<str>, NodeIx>,
438    warnings: &mut Vec<String>,
439) -> Result<(), GraphError> {
440    for (ix, n) in nodes.iter().enumerate() {
441        for selector in n.node.inputs() {
442            let namespace = selector.namespace();
443            if RESERVED_NAMESPACES.contains(&namespace) {
444                continue;
445            }
446            let Some(&target) = index.get(namespace) else {
447                let candidates = nodes.iter().map(|n| &*n.id).chain(RESERVED_NAMESPACES.iter().copied());
448                return Err(GraphError::UnknownReference {
449                    node: n.id.to_string(),
450                    selector: selector.to_string(),
451                    namespace: namespace.to_owned(),
452                    suggestion: crate::validate::suggest(namespace, candidates),
453                });
454            };
455            if !is_visible(nodes, ix, target) {
456                warnings.push(format!(
457                    "node `{}` references `{selector}` from a different container body; it will resolve to null",
458                    n.id
459                ));
460            }
461        }
462    }
463    Ok(())
464}
465
466/// Reject config fields the kind's catalog schema does not allow (closed
467/// schemas only) and missing required ones.
468fn check_fields(doc: &NodeDoc, registry: &Registry) -> Result<(), GraphError> {
469    let Some(descriptor) = registry.descriptor_ref(&doc.kind) else { return Ok(()) };
470    let base = crate::source_map::DocPath::root();
471    match crate::validate::config_diagnostics(doc, descriptor, &base).into_iter().find(|d| d.is_error()) {
472        None => Ok(()),
473        Some(d) => Err(GraphError::InvalidField {
474            node: doc.id.clone(),
475            path: d.path.to_string(),
476            message: format!("{}{}", d.message, did_you_mean(&d.suggestion)),
477        }),
478    }
479}
480
481/// Whether node `from` can read the outputs of node `target`.
482fn is_visible(nodes: &[GraphNode], from: NodeIx, target: NodeIx) -> bool {
483    let parent_of = |ix: NodeIx| nodes.get(ix).and_then(|n| n.parent);
484    let target_scope = parent_of(target);
485    // Same or enclosing scope.
486    let mut scope = parent_of(from);
487    loop {
488        if scope == target_scope {
489            return true;
490        }
491        match scope {
492            Some(s) => scope = parent_of(s),
493            None => break,
494        }
495    }
496    // Inside the referencing node's own body (a container reading its body outputs).
497    let mut cur = target_scope;
498    while let Some(c) = cur {
499        if c == from {
500            return true;
501        }
502        cur = parent_of(c);
503    }
504    false
505}
506
507fn find_entry(
508    nodes: &[GraphNode],
509    incoming: &[Vec<EdgeIx>],
510    owner: Option<NodeIx>,
511    scope_nodes: &[NodeIx],
512    scope_name: &str,
513) -> Result<NodeIx, GraphError> {
514    let wanted = if owner.is_some() { NodeRole::ScopeStart } else { NodeRole::Root };
515    let explicit: Vec<NodeIx> =
516        scope_nodes.iter().copied().filter(|&ix| nodes.get(ix).map(|n| n.role) == Some(wanted)).collect();
517    let candidates = if explicit.is_empty() {
518        // Fall back to the unique node without incoming edges.
519        scope_nodes.iter().copied().filter(|&ix| incoming.get(ix).is_none_or(Vec::is_empty)).collect()
520    } else {
521        explicit
522    };
523    match candidates.as_slice() {
524        [] => Err(GraphError::NoEntry { scope: scope_name.to_owned() }),
525        [one] => Ok(*one),
526        many => Err(GraphError::MultipleEntries {
527            scope: scope_name.to_owned(),
528            nodes: many.iter().filter_map(|&ix| nodes.get(ix)).map(|n| n.id.to_string()).collect(),
529        }),
530    }
531}
532
533fn topo_order(
534    scope_nodes: &[NodeIx],
535    outgoing: &[Vec<EdgeIx>],
536    incoming: &[Vec<EdgeIx>],
537    edges: &[GraphEdge],
538    nodes: &[GraphNode],
539    scope_name: &str,
540) -> Result<Vec<NodeIx>, GraphError> {
541    let mut indeg: HashMap<NodeIx, usize> =
542        scope_nodes.iter().map(|&ix| (ix, incoming.get(ix).map_or(0, Vec::len))).collect();
543    let mut queue: VecDeque<NodeIx> = scope_nodes.iter().copied().filter(|ix| indeg.get(ix) == Some(&0)).collect();
544    let mut order = Vec::with_capacity(scope_nodes.len());
545    while let Some(ix) = queue.pop_front() {
546        order.push(ix);
547        for &ex in outgoing.get(ix).map(Vec::as_slice).unwrap_or_default() {
548            if let Some(e) = edges.get(ex)
549                && let Some(d) = indeg.get_mut(&e.target)
550            {
551                *d = d.saturating_sub(1);
552                if *d == 0 {
553                    queue.push_back(e.target);
554                }
555            }
556        }
557    }
558    if order.len() != scope_nodes.len() {
559        let stuck = scope_nodes
560            .iter()
561            .find(|ix| indeg.get(ix).is_some_and(|d| *d > 0))
562            .and_then(|&ix| nodes.get(ix))
563            .map(|n| n.id.to_string())
564            .unwrap_or_default();
565        return Err(GraphError::Cycle { scope: scope_name.to_owned(), node: stuck });
566    }
567    Ok(order)
568}
569
570fn reachable_from(entry: NodeIx, outgoing: &[Vec<EdgeIx>], edges: &[GraphEdge]) -> HashSet<NodeIx> {
571    let mut seen = HashSet::from([entry]);
572    let mut stack = vec![entry];
573    while let Some(ix) = stack.pop() {
574        for &ex in outgoing.get(ix).map(Vec::as_slice).unwrap_or_default() {
575            if let Some(e) = edges.get(ex)
576                && seen.insert(e.target)
577            {
578                stack.push(e.target);
579            }
580        }
581    }
582    seen
583}
584
585/// FNV-1a over the canonical JSON of the graph section (stable across processes,
586/// unlike `DefaultHasher`).
587fn fingerprint(workflow: &Workflow) -> Result<String, GraphError> {
588    let text = workflow.canonical_graph_json().map_err(|e| GraphError::Unserializable(e.to_string()))?;
589    let mut h = Fnv(FNV_OFFSET);
590    text.hash(&mut h);
591    Ok(format!("{:016x}", h.finish()))
592}
593
594/// FNV-1a of raw bytes, as hex.
595fn fnv_hex(bytes: &[u8]) -> String {
596    let mut h = Fnv(FNV_OFFSET);
597    h.write(bytes);
598    format!("{:016x}", h.finish())
599}
600
601const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
602
603/// 64-bit FNV-1a.
604struct Fnv(u64);
605
606impl Hasher for Fnv {
607    fn finish(&self) -> u64 {
608        self.0
609    }
610    fn write(&mut self, bytes: &[u8]) {
611        for b in bytes {
612            self.0 ^= u64::from(*b);
613            self.0 = self.0.wrapping_mul(0x0100_0000_01b3);
614        }
615    }
616}