robin/maivi
a tiny cute lua web framework
git clone https://git.robinwobin.dev/robin/maivi
6507f5b
main
1const std =@import ( "std" ); 2 3const fern =@import ( "fern" ); 4const zlua =@import ( "zlua" ); 5const Lua =zlua . Lua ; 6 7const maivi =@import ( "../root.zig" ); 8 9pub fn lua_openstr ( l : * Lua ) ! i32 { 10l . createTable ( 0 , 2 ); 11 12l . pushFunction ( zlua . wrap ( len )); 13l . setField ( - 2 , "len" ); 14 15l . pushFunction ( zlua . wrap ( split )); 16l . setField ( - 2 , "split" ); 17 18l . pushFunction ( zlua . wrap ( escape )); 19l . setField ( - 2 , "escape" ); 20 21return 1 ; 22} 23 24pub fn len ( l : * Lua ) ! i32 { 25l . argCheck ( l . isString ( - 1 ), - 1 , "string" ); 26 27const str =try l . toString ( - 1 ); 28const s =try maivi . allocator . dupe ( u8 , str ); 29defer maivi . allocator . free ( s ); 30 31const str_len =try std . unicode . calcUtf16LeLen ( str ); 32l . pushInteger ( @intCast ( str_len )); 33 34return 1 ; 35} 36 37pub fn split ( l : * Lua ) ! i32 { 38l . argCheck ( l . isString ( - 2 ), - 2 , "string" ); 39l . argCheck ( l . isString ( - 1 ), - 1 , "string" ); 40 41const str =try l . toString ( - 2 ); 42const s =try maivi . allocator . dupe ( u8 , str ); 43defer maivi . allocator . free ( s ); 44 45const sep_str =try l . toString ( - 1 ); 46const sep =try maivi . allocator . dupe ( u8 , sep_str ); 47defer maivi . allocator . free ( sep ); 48 49l . newTable (); 50 51var it =std . mem . splitSequence ( u8 , s , sep ); 52while ( it . next ()) | x | { 53_ = l . pushString ( x ); 54 55const index =l . lenRaw ( - 2 ) + 1 ; 56l . setIndexRaw ( - 2 , @intCast ( index )); 57} 58 59return 1 ; 60} 61 62pub fn escape ( l : * Lua ) ! i32 { 63l . argCheck ( l . isString ( - 1 ), - 1 , "string" ); 64 65const stack_size_on_entry =l . getTop (); 66 67const strz =try l . toString ( - 1 ); 68 69var result : std . ArrayList ( u8 ) =try . initCapacity ( maivi . allocator , 0x100 ); 70defer result . deinit ( maivi . allocator ); 71 72for ( strz ) |char |{ 73const escaped : ? [] const u8 =switch ( char ) { 74'<' =>"<" , 75'>' =>">" , 76'&' =>"&" , 77'"' =>""" , 78else =>null , 79}; 80 81if ( escaped ) | e | 82try result . appendSlice ( maivi . allocator , e ) 83else 84try result . append ( maivi . allocator , char ); 85} 86 87const escaped =try result . toOwnedSlice ( maivi . allocator ); 88defer maivi . allocator . free ( escaped ); 89 90if ( l . getTop () != stack_size_on_entry ) return error . UnexpectedStackSize ; 91 92_ = l . pushString ( escaped ); 93 94return 1 ; 95}