How to disable auto group codo in one line for a short function? - clang-format

int compare (const void * a, const void * b) {
return ( *(int*)a - *(int*)b );
}
The above code is indented like this by the following command. I'd like to keep its original style (if it is one line, the output is one line, if the input is three lines, the output should be three lines.) Is there a way to do so with clang-format?
$ clang-format -style='{IndentWidth: 8, UseTab: Always, SpaceBeforeParens: Never, IndentCaseLabels: true }'
int compare(const void *a, const void *b) { return (*(int *)a - *(int *)b); }

Given input.cpp:
int compare (const void * a, const void * b) { return ( *(int*)a - *(int*)b ); }
This is the result of using AllowShortFunctionsOnASingleLine: None:
% clang-format -style='{AllowShortFunctionsOnASingleLine: None}' input.cpp
int compare(const void *a, const void *b) {
return (*(int *)a - *(int *)b);
}
% clang-format --version
7.0.1

Related

A map functions? don't understand this dart

I see this source from google_fonts of dart pub. It seems we have a function map? and asMap() has a arrow function? Don't understand this.
static Map<
String,
TextStyle Function({
TextStyle? textStyle,
Color? color,
Color? backgroundColor,
double? fontSize,
FontWeight? fontWeight,
FontStyle? fontStyle,
double? letterSpacing,
double? wordSpacing,
TextBaseline? textBaseline,
double? height,
Locale? locale,
Paint? foreground,
Paint? background,
List<ui.Shadow>? shadows,
List<ui.FontFeature>? fontFeatures,
TextDecoration? decoration,
Color? decorationColor,
TextDecorationStyle? decorationStyle,
double? decorationThickness,
})> asMap() => const {
'ABeeZee': GoogleFonts.aBeeZee,
'Abel': GoogleFonts.abel}
You're seeing a generated code, in the very beginning of the file:
// GENERATED CODE - DO NOT EDIT
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
This function is defined as:
Name: asMap.
Scope: top-level (Since it is a static method).
Return type: Map<String, TextStyle Function({ ...args })>.
It seems we have a function map?
We have a function that returns a map of Strings and Closures. In Dart this is perfectly fine:
final Map<String, int Function(int, int)> operations = {
'sum': (int a, int b) => a + b,
'subtract': (int a, int b) => a - b,
'multiply': (int a, int b) => a * b,
'divide': (int a, int b) => a * b
};
operations['sum']!(30, 30); // 60
operations['subtract']!(30, 30); // 0
operations['multiply']!(30, 30); // 900
operations['divide']!(30, 30); // 1
In general this is not something we do by raw hands due to type implications (hard to maintain, you can see that it's pretty confusing + it's pretty easy to lost track of type definitions and, consequently, all intellisense features). So that's why this is being done through code generation.
And in this particular case, we are generating a map, like this example below:
class Arithmetic {
static int sum(int a, int b) {
return a + b;
}
static int subtract(int a, int b) {
return a - b;
}
static int multiply(int a, int b) {
return a * b;
}
static int divide(int a, int b) {
return a * b;
}
static Map<String, int Function(int, int)> asMap() {
const Map<String, int Function(int, int)> operationsAsMap = {
'sum': sum,
'subtract': subtract,
'multiply': multiply,
'divide': divide
};
return operationsAsMap;
}
}
asMap() has a arrow function?
No, the asMap() implementation is using an arrow function, which is an alias for:
// This is a shorthand...
static Map<...> asMap() => const { ... };
// For this:
static Map<...> asMap() {
return const { ... };
}

dmd can't infer type even when type is given

Here I want to lockstep iterate over two arrays of size_t
import std.stdio;
import std.range;
import std.exception;
import std.conv;
struct zip(R,Q)
if(isInputRange!(R) && isInputRange!(Q))
{
R r;
Q q;
#property
const auto front() {
return tuple(r.front, q.front);
}
void popFront() {
r.popFront();
q.popFront();
}
#property
const bool empty() {
bool re = r.empty;
enforce(re == q.empty);
return re;
}
}
void main() {
size_t[] a = [0,1,2,3,4,5];
size_t[] b = [2,3,4,5,6,7];
foreach(size_t i, size_t j; zip!(size_t[],size_t[])(a,b)) {
writeln(to!string(i) ~ " " ~ to!string(j));
}
}
But this fails to compile with
src/Interpreter.d(30): Error: cannot infer argument types
However when I change the foreach line to use uint instead of size_t (I'm on a 32-bit laptop)
foreach(uint i, uint j; zip!(size_t[],size_t[])(a,b)) {
It compiles and runs just fine. What's going on?
It might be a bug. In v2.065.0 it doesn't work, but it does work in the latest git-head development version.

Weird characters in printf

My environment: Xcode5, iOS, Objective-C/Objective-C++ mix.
I am trying to figure out what causes the next problem. I am writing my own logging function:
int _me_log(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
char *c = va_arg(args, char *);
char *message = NULL;
printf(fmt, args);
int n = asprintf(&message, fmt, args);
if (n != -1 && message != NULL) {
//do something with 'message' like writing to file, etc.
UPDATE:
//we need to handle memory created for 'message' storage.
free(message);
}
va_end(args);
return n;
}
Then I call it like this:
_me_log("socket %s did open", "Socket: 0x1fd1c880");
And instead of correct output socket Socket: 0x1fd1c880 did open I get some gibberish like this socket \\323\331/ did open in this line printf(fmt, args);.
If I call it this way printf("%s", c); I get correct results.
I have googled several implementations (this or this ) of logging functions and functions which pass variable parameters and it seems that I do everything correctly.
Could you please suggest me what I'm doing wrong?
You've got the right idea to use va_list here, but if you work with va_list you should use vasprintf instead of asprintf:
int _me_log(const char *fmt, ...)
{
va_list args;
char *message = NULL;
int n;
va_start(args, fmt);
n = vasprintf(&message, fmt, args);
if (n != -1 && message != NULL) {
// ... use message ...
}
free(message);
va_end(args);
return n;
}
For every routine of the printf family, there is a variant that takes a va_list instead of the variadic argument ... and whose name is prefixed with the letter v, for example:
int printf(const char *format, ...);
int vprintf(const char *format, va_list ap);
These routines exist so you can write you own (non-macro) wrapper for xprintf.
Seems like a very complicated implementation. Try:
int _me_log(const char *fmt, ...) {
int ret = 0;
va_list va;
va_start(va, fmt);
ret = vprintf(fmt, va);
va_end(va);
putc('\n', stdout);
return ret;
}
But, of course, that is no different from printf(), except for forcing a newline.

argument of pthread_create()

We know that we call pthread like this
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void* arg);
However, if in the start_routine function I wanna call has more than one argument, what can I do?
You can put whatever you want into a struct and pass a pointer to that.
In C:
typedef struct {
int a;
int b;
} ChildMainArgs;
void child_main(int a,int b);
void child_main_thread(void *arg)
{
ChildMainArgs *args_ptr = (ChildMainArgs *)arg;
child_main(args_ptr->a,args_ptr->b);
}
ChildMainArgs args;
args.a = 5;
args.b = 7;
pthread_create(..,..,child_main_thread,&args);

How do I create a class object in Lua-C API 5.2?

I'm wrapping a C function with Lua, using the Lua-C API for Lua 5.2:
#include <lua.h>
#include <lauxlib.h>
#include <stdlib.h>
#include <stdio.h>
int foo_gc();
int foo_index();
int foo_newindex();
int foo_dosomething();
int foo_new();
struct foo {
int x;
};
static const luaL_Reg _meta[] = {
{"__gc", foo_gc},
{"__index", foo_index},
{"__newindex", foo_newindex},
{ NULL, NULL }
};
static const luaL_Reg _methods[] = {
{"new", foo_new},
{"dosomething", foo_dosomething},
{ NULL, NULL }
};
int foo_gc(lua_State* L) {
printf("## __gc\n");
return 0;
}
int foo_newindex(lua_State* L) {
printf("## __newindex\n");
return 0;
}
int foo_index(lua_State* L) {
printf("## __index\n");
return 0;
}
int foo_dosomething(lua_State* L) {
printf("## dosomething\n");
return 0;
}
int foo_new(lua_State* L) {
printf("## new\n");
lua_newuserdata(L,sizeof(Foo));
luaL_getmetatable(L, "Foo");
lua_setmetatable(L, -2);
return 1;
}
void register_foo_class(lua_State* L) {
luaL_newlib(L, _methods);
luaL_newmetatable(L, "Foo");
luaL_setfuncs(L, _meta, 0);
lua_setmetatable(L, -2);
lua_setglobal(L, "Foo");
}
When I run this Lua:
local foo = Foo.new()
foo:dosomething()
...I see this output (with error):
## new
## __index
Failed to run script: script.lua:2: attempt to call method 'dosomething' (a nil value)
What am I doing wrong?
Ok, got it working. I had to add __index and __metatable to Foo's new metatable, as shown below:
void register_foo_class(lua_State* L) {
int lib_id, meta_id;
/* newclass = {} */
lua_createtable(L, 0, 0);
lib_id = lua_gettop(L);
/* metatable = {} */
luaL_newmetatable(L, "Foo");
meta_id = lua_gettop(L);
luaL_setfuncs(L, _meta, 0);
/* metatable.__index = _methods */
luaL_newlib(L, _methods);
lua_setfield(L, meta_id, "__index");
/* metatable.__metatable = _meta */
luaL_newlib(L, _meta);
lua_setfield(L, meta_id, "__metatable");
/* class.__metatable = metatable */
lua_setmetatable(L, lib_id);
/* _G["Foo"] = newclass */
lua_setglobal(L, "Foo");
}
I tried replying to your solution but apparently I don't have the reputation to do so yet, so here goes a separate answer.
Your solution is pretty nice, but it does not allow for something that I'd like to do: Have both "array-like" access to an object and still have functions on it. Have a look at this Lua code:
Foo = {}
mt = {
__index = function(table, key)
print("Accessing array index ", tostring(key), "\n")
return 42
end
}
setmetatable(Foo, mt)
Foo.bar = function()
return 43
end
print(tostring(Foo[13]), "\n")
print(tostring(Foo.bar()), "\n")
--[[
Output:
Accessing array index 13
42
43
]]--
Registering a class using your solution does not seem to allow for this, as the __index entry is overwritten.
It might not make sense to have both array access and function access on a class, but for the sake of simplicity (offering one C function for registering both types of classes) I'd like to use the same code everywhere. Does anyone have an idea how this restriction could be circumvented, so that I can create a class from C which has both a function Foo.bar() but also Foo[13]?
Here's how I would satisfy both your criteria as well as j_schultz's
#include <lua.h>
#include <lauxlib.h>
#include <stdlib.h>
#include <stdio.h>
#define LUA_FOO "Foo"
typedef struct {
int x;
} Foo;
static int foo_gc(lua_State *L) {
printf("## __gc\n");
Foo *foo = *(Foo**)luaL_checkudata(L, 1, LUA_FOO);
free(foo);
return 0;
}
static int foo_doSomething(lua_State *L) {
printf("## doSomething\n");
Foo *foo = *(Foo**)luaL_checkudata(L, 1, LUA_FOO);
lua_pushinteger(L, foo->x);
return 1;
}
static int foo_new(lua_State* L) {
printf("## new\n");
Foo *foo = malloc(sizeof(Foo));
int i = 1 + lua_istable(L, 1);
foo->x = !lua_isnoneornil(L, i) ? luaL_checkinteger(L, i) : 0;
*(Foo**)lua_newuserdata(L, sizeof(Foo*)) = foo;
luaL_setmetatable(L, LUA_FOO);
return 1;
}
static int foo_index(lua_State *L) {
printf("## index\n");
int i = luaL_checkinteger(L, 2);
lua_pushinteger(L, i);
return 1;
}
int luaopen_foo(lua_State *L) {
// instance functions
static const luaL_Reg meta[] =
{ { "__gc" ,foo_gc },
{ NULL ,NULL } };
static const luaL_Reg meth[] =
{ { "doSomething" ,foo_doSomething },
{ NULL ,NULL } };
luaL_newmetatable(L, LUA_FOO);
luaL_setfuncs (L, meta, 0);
luaL_newlib (L, meth);
lua_setfield (L, -2, "__index");
lua_pop (L, 1);
// static functions
static const luaL_Reg static_meta[] =
{ { "__index" ,foo_index },
{ "__call" ,foo_new },
{ NULL ,NULL } };
static const luaL_Reg static_meth[] =
{ { "new" ,foo_new },
{ NULL ,NULL } };
luaL_newlib (L, static_meth);
luaL_newlib (L, static_meta);
lua_setmetatable (L, -2);
return 1;
}
Lua code:
local Foo = require('foo')
local foo = Foo.new(12)
local bar = Foo(24)
print(Foo[13])
print(foo:doSomething())
print(bar:doSomething())
Lua output:
## new
## new
## index
13
## doSomething
12
## doSomething
24
## __gc
## __gc

Resources