【问题标题】:What is the meaning of "trap" in relation to integer underflow/overflow?与整数下溢/上溢相关的“陷阱”是什么意思?
【发布时间】:2021-12-04 04:47:27
【问题描述】:

阅读 Internet Computer 的 Motoko 的文档:

https://sdk.dfinity.org/docs/languages/motoko-at-a-glance.html#_bounded_numbers_trapping

我意识到我没有一个很好的模型来解释“诱捕”这个词在这里的含义:

有界数(陷印)Nat8、Nat16、Nat32、Nat64、Int8、Int16、 Int32, Int64

上溢和下溢的陷阱

需要指定类型注释

文字:13、0xf4、-20、1_000_000

这是否意味着如果尝试写入会导致上溢/下溢的数字,整数将保持在最大值/最小值?

在这种情况下,“陷阱”一词的由来是什么?它在这里的确切含义是什么?

【问题讨论】:

    标签: integer integer-overflow motoko internet-computer


    【解决方案1】:

    此上下文中的陷阱会导致执行中止。容器仍然可以,但对容器的调用将失败。见this part of the manual.

    作为演示,我从one of these templates 设置了一个类型为 Nat8 的计数器容器,因此它应该支持值 0..255(含),并将其初始化为 250:

    $ cat counter-canister/main.mo 
    actor {
        stable var currentValue: Nat8 = 250;
    
        public func increment(): async () {
            currentValue += 1;
        };
    
        public query func getValue(): async Nat8 {
            currentValue;
        };
    };
    

    然后我点击了“增量”按钮。正如预期的那样,它从 250 增加到 255,然后在下一次单击时,它会显示在浏览器控制台中:

    vendor.e49a5b15.js:831 Uncaught (in promise) Error: Call was rejected:
      Request ID: 0f549a49b80b31831e423196d086e36c12df51896ffaaa59e99bae7fa66047aa
      Reject code: 5
      Reject text: Canister ryjl3-tyaaa-aaaaa-aaaba-cai trapped explicitly: arithmetic overflow
    
        at pollForResponse (vendor.e49a5b15.js:831)
        at async n (vendor.e49a5b15.js:838)
        at async HTMLButtonElement.n (index.4a11dcea.js:5)
    

    重新加载页面显示该值仍然是最大值,255。

    罐子仍然可以正常工作。如果我也费心在那里放一个减量按钮,我可以倒计时一点,然后增加值,直到我再次达到极限。

    【讨论】:

      猜你喜欢
      • 2016-05-30
      • 2015-02-20
      • 1970-01-01
      • 2018-01-02
      • 2013-12-21
      • 2018-02-28
      • 2017-02-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多