blob: bc25bae0ed79700df5dc6ba2515ae6afa78019b6 [file] [edit]
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SRC_DEVELOPER_SHELL_JOSH_LIB_QJS_UTIL_H_
#define SRC_DEVELOPER_SHELL_JOSH_LIB_QJS_UTIL_H_
#include "third_party/quickjs/quickjs.h"
// This is one of those terrific grab-bag utilities files that everyone loves.
namespace shell {
// A unique_ptr-alike for C strings generated by quickjs from JS strings.
class CStringHolder {
public:
explicit CStringHolder(JSContext* ctx) : ctx_(ctx), val_(nullptr) {}
CStringHolder(JSContext* ctx, const JSValueConst& val)
: ctx_(ctx), val_(JS_ToCString(ctx, val)) {}
~CStringHolder() {
if (val_) {
JS_FreeCString(ctx_, val_);
}
}
const char* reset(const JSValueConst& val) {
if (val_) {
JS_FreeCString(ctx_, val_);
}
val_ = JS_ToCString(ctx_, val);
return val_;
}
const char* get() { return val_; }
private:
JSContext* ctx_;
const char* val_;
};
} // namespace shell
#endif // SRC_DEVELOPER_SHELL_JOSH_LIB_QJS_UTIL_H_