github.com/arnodel/golua@v0.0.0-20230215163904-e0b5347eaaa1/lib/utf8lib/lua/utf8.quotas.lua (about) 1 -- utf8.char 2 do 3 -- utf8.char uses memory to build a string 4 local ctx, s = runtime.callcontext({kill={memory=10000}}, utf8.char, utf8.codepoint(("x"):rep(100), 1, 100)) 5 print(ctx, #s) 6 --> =done 100 7 8 print(runtime.callcontext({kill={memory=10000}}, utf8.char, utf8.codepoint(("x"):rep(1000), 1, 1000))) 9 --> =killed 10 11 -- utf8.cahr uses cpu to build a string 12 local ctx, s = runtime.callcontext({kill={cpu=1000}}, utf8.char, utf8.codepoint(("x"):rep(100), 1, 100)) 13 print(ctx, #s) 14 --> =done 100 15 16 print(runtime.callcontext({kill={cpu=1000}}, utf8.char, utf8.codepoint(("x"):rep(1000), 1, 1000))) 17 --> =killed 18 end 19 20 21 -- utf8.codes 22 do 23 local function len(s) 24 local len = 0 25 for x in utf8.codes(s) do 26 len = len + 1 27 end 28 return len 29 end 30 31 -- Iterating over utf8.codes(s) consumes cpu 32 print(runtime.callcontext({kill={cpu=1000}}, len, ("s"):rep(50))) 33 --> =done 50 34 35 print(runtime.callcontext({kill={cpu=1000}}, len, ("s"):rep(500))) 36 --> =killed 37 38 -- It doesn't consume memory 39 ctx1 = runtime.callcontext({kill={memory=1000}}, len, ("s"):rep(100)) 40 ctx2 = runtime.callcontext({kill={memory=1000}}, len, ("s"):rep(1000)) 41 print(ctx1, ctx2, ctx2.used.memory / ctx1.used.memory < 1.2) 42 --> =done done true 43 end 44 45 -- utf8.codepoint 46 do 47 local function codepoint(s) 48 -- drop the output to prevent requiring memory for it 49 utf8.codepoint(s, 1, #s) 50 end 51 52 -- utf8.codepoint requires cpu proportional to input size 53 54 print(runtime.callcontext({kill={cpu=1000}}, codepoint, ("a"):rep(500))) 55 --> =done 56 57 print(runtime.callcontext({kill={cpu=1000}}, codepoint, ("a"):rep(1000))) 58 --> =killed 59 end 60 61 -- utf8.len 62 do 63 -- utf8.len requires cpu proportional to input size 64 65 print(runtime.callcontext({kill={cpu=1000}}, utf8.len, ("a"):rep(500))) 66 --> =done 500 67 68 print(runtime.callcontext({kill={cpu=1000}}, utf8.len, ("a"):rep(1000))) 69 --> =killed 70 end 71 72 -- utf8.offset 73 do 74 -- utf8.offset requires cpu proportional to the displacement 75 76 print(runtime.callcontext({kill={cpu=1000}}, utf8.offset, ("日本誒"):rep(100), 200)) 77 --> =done 598 78 79 print(runtime.callcontext({kill={cpu=1000}}, utf8.offset, ("日本誒"):rep(100), -200)) 80 --> =done 301 81 82 print(runtime.callcontext({kill={cpu=2000}}, utf8.offset, ("日本誒"):rep(1000), 2000)) 83 --> =killed 84 85 print(runtime.callcontext({kill={cpu=2000}}, utf8.offset, ("日本誒"):rep(1000), -2000)) 86 --> =killed 87 end 88